00a4ac6a8f9817813347fe6cfb41b7c3ad92df01
[oota-llvm.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 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 defines the interfaces that AArch64 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "aarch64-isel"
16 #include "AArch64.h"
17 #include "AArch64ISelLowering.h"
18 #include "AArch64MachineFunctionInfo.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29
30 using namespace llvm;
31
32 static TargetLoweringObjectFile *createTLOF(AArch64TargetMachine &TM) {
33   assert (TM.getSubtarget<AArch64Subtarget>().isTargetELF() &&
34           "unknown subtarget type");
35   return new AArch64ElfTargetObjectFile();
36 }
37
38 AArch64TargetLowering::AArch64TargetLowering(AArch64TargetMachine &TM)
39   : TargetLowering(TM, createTLOF(TM)), Itins(TM.getInstrItineraryData()) {
40
41   const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
42
43   // SIMD compares set the entire lane's bits to 1
44   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
45
46   // Scalar register <-> type mapping
47   addRegisterClass(MVT::i32, &AArch64::GPR32RegClass);
48   addRegisterClass(MVT::i64, &AArch64::GPR64RegClass);
49
50   if (Subtarget->hasFPARMv8()) {
51     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
52     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
53     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
54     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
55   }
56
57   if (Subtarget->hasNEON()) {
58     // And the vectors
59     addRegisterClass(MVT::v1i8,  &AArch64::FPR8RegClass);
60     addRegisterClass(MVT::v1i16, &AArch64::FPR16RegClass);
61     addRegisterClass(MVT::v1i32, &AArch64::FPR32RegClass);
62     addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
63     addRegisterClass(MVT::v1f64, &AArch64::FPR64RegClass);
64     addRegisterClass(MVT::v8i8,  &AArch64::FPR64RegClass);
65     addRegisterClass(MVT::v4i16, &AArch64::FPR64RegClass);
66     addRegisterClass(MVT::v2i32, &AArch64::FPR64RegClass);
67     addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
68     addRegisterClass(MVT::v2f32, &AArch64::FPR64RegClass);
69     addRegisterClass(MVT::v16i8, &AArch64::FPR128RegClass);
70     addRegisterClass(MVT::v8i16, &AArch64::FPR128RegClass);
71     addRegisterClass(MVT::v4i32, &AArch64::FPR128RegClass);
72     addRegisterClass(MVT::v2i64, &AArch64::FPR128RegClass);
73     addRegisterClass(MVT::v4f32, &AArch64::FPR128RegClass);
74     addRegisterClass(MVT::v2f64, &AArch64::FPR128RegClass);
75   }
76
77   computeRegisterProperties();
78
79   // We combine OR nodes for bitfield and NEON BSL operations.
80   setTargetDAGCombine(ISD::OR);
81
82   setTargetDAGCombine(ISD::AND);
83   setTargetDAGCombine(ISD::SRA);
84   setTargetDAGCombine(ISD::SRL);
85   setTargetDAGCombine(ISD::SHL);
86
87   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
88   setTargetDAGCombine(ISD::INTRINSIC_VOID);
89   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
90
91   // AArch64 does not have i1 loads, or much of anything for i1 really.
92   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
94   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
95
96   setStackPointerRegisterToSaveRestore(AArch64::XSP);
97   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
98   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
99   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
100
101   // We'll lower globals to wrappers for selection.
102   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
103   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
104
105   // A64 instructions have the comparison predicate attached to the user of the
106   // result, but having a separate comparison is valuable for matching.
107   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
108   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
109   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
110   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
111
112   setOperationAction(ISD::SELECT, MVT::i32, Custom);
113   setOperationAction(ISD::SELECT, MVT::i64, Custom);
114   setOperationAction(ISD::SELECT, MVT::f32, Custom);
115   setOperationAction(ISD::SELECT, MVT::f64, Custom);
116
117   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
118   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
119   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
120   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
121
122   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
123
124   setOperationAction(ISD::SETCC, MVT::i32, Custom);
125   setOperationAction(ISD::SETCC, MVT::i64, Custom);
126   setOperationAction(ISD::SETCC, MVT::f32, Custom);
127   setOperationAction(ISD::SETCC, MVT::f64, Custom);
128
129   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
130   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
132
133   setOperationAction(ISD::VASTART, MVT::Other, Custom);
134   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
135   setOperationAction(ISD::VAEND, MVT::Other, Expand);
136   setOperationAction(ISD::VAARG, MVT::Other, Expand);
137
138   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
139   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
140
141   setOperationAction(ISD::ROTL, MVT::i32, Expand);
142   setOperationAction(ISD::ROTL, MVT::i64, Expand);
143
144   setOperationAction(ISD::UREM, MVT::i32, Expand);
145   setOperationAction(ISD::UREM, MVT::i64, Expand);
146   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
147   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
148
149   setOperationAction(ISD::SREM, MVT::i32, Expand);
150   setOperationAction(ISD::SREM, MVT::i64, Expand);
151   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
152   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
153
154   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
157   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
158
159   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
160   setOperationAction(ISD::CTPOP, MVT::i64, Expand);
161
162   // Legal floating-point operations.
163   setOperationAction(ISD::FABS, MVT::f32, Legal);
164   setOperationAction(ISD::FABS, MVT::f64, Legal);
165
166   setOperationAction(ISD::FCEIL, MVT::f32, Legal);
167   setOperationAction(ISD::FCEIL, MVT::f64, Legal);
168
169   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
170   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
171
172   setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
173   setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
174
175   setOperationAction(ISD::FNEG, MVT::f32, Legal);
176   setOperationAction(ISD::FNEG, MVT::f64, Legal);
177
178   setOperationAction(ISD::FRINT, MVT::f32, Legal);
179   setOperationAction(ISD::FRINT, MVT::f64, Legal);
180
181   setOperationAction(ISD::FSQRT, MVT::f32, Legal);
182   setOperationAction(ISD::FSQRT, MVT::f64, Legal);
183
184   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
185   setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
186
187   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
188   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
189   setOperationAction(ISD::ConstantFP, MVT::f128, Legal);
190
191   // Illegal floating-point operations.
192   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
193   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194
195   setOperationAction(ISD::FCOS, MVT::f32, Expand);
196   setOperationAction(ISD::FCOS, MVT::f64, Expand);
197
198   setOperationAction(ISD::FEXP, MVT::f32, Expand);
199   setOperationAction(ISD::FEXP, MVT::f64, Expand);
200
201   setOperationAction(ISD::FEXP2, MVT::f32, Expand);
202   setOperationAction(ISD::FEXP2, MVT::f64, Expand);
203
204   setOperationAction(ISD::FLOG, MVT::f32, Expand);
205   setOperationAction(ISD::FLOG, MVT::f64, Expand);
206
207   setOperationAction(ISD::FLOG2, MVT::f32, Expand);
208   setOperationAction(ISD::FLOG2, MVT::f64, Expand);
209
210   setOperationAction(ISD::FLOG10, MVT::f32, Expand);
211   setOperationAction(ISD::FLOG10, MVT::f64, Expand);
212
213   setOperationAction(ISD::FPOW, MVT::f32, Expand);
214   setOperationAction(ISD::FPOW, MVT::f64, Expand);
215
216   setOperationAction(ISD::FPOWI, MVT::f32, Expand);
217   setOperationAction(ISD::FPOWI, MVT::f64, Expand);
218
219   setOperationAction(ISD::FREM, MVT::f32, Expand);
220   setOperationAction(ISD::FREM, MVT::f64, Expand);
221
222   setOperationAction(ISD::FSIN, MVT::f32, Expand);
223   setOperationAction(ISD::FSIN, MVT::f64, Expand);
224
225   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
226   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
227
228   // Virtually no operation on f128 is legal, but LLVM can't expand them when
229   // there's a valid register class, so we need custom operations in most cases.
230   setOperationAction(ISD::FABS,       MVT::f128, Expand);
231   setOperationAction(ISD::FADD,       MVT::f128, Custom);
232   setOperationAction(ISD::FCOPYSIGN,  MVT::f128, Expand);
233   setOperationAction(ISD::FCOS,       MVT::f128, Expand);
234   setOperationAction(ISD::FDIV,       MVT::f128, Custom);
235   setOperationAction(ISD::FMA,        MVT::f128, Expand);
236   setOperationAction(ISD::FMUL,       MVT::f128, Custom);
237   setOperationAction(ISD::FNEG,       MVT::f128, Expand);
238   setOperationAction(ISD::FP_EXTEND,  MVT::f128, Expand);
239   setOperationAction(ISD::FP_ROUND,   MVT::f128, Expand);
240   setOperationAction(ISD::FPOW,       MVT::f128, Expand);
241   setOperationAction(ISD::FREM,       MVT::f128, Expand);
242   setOperationAction(ISD::FRINT,      MVT::f128, Expand);
243   setOperationAction(ISD::FSIN,       MVT::f128, Expand);
244   setOperationAction(ISD::FSINCOS,    MVT::f128, Expand);
245   setOperationAction(ISD::FSQRT,      MVT::f128, Expand);
246   setOperationAction(ISD::FSUB,       MVT::f128, Custom);
247   setOperationAction(ISD::FTRUNC,     MVT::f128, Expand);
248   setOperationAction(ISD::SETCC,      MVT::f128, Custom);
249   setOperationAction(ISD::BR_CC,      MVT::f128, Custom);
250   setOperationAction(ISD::SELECT,     MVT::f128, Expand);
251   setOperationAction(ISD::SELECT_CC,  MVT::f128, Custom);
252   setOperationAction(ISD::FP_EXTEND,  MVT::f128, Custom);
253
254   // Lowering for many of the conversions is actually specified by the non-f128
255   // type. The LowerXXX function will be trivial when f128 isn't involved.
256   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
257   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
258   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
259   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
260   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
261   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
262   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
263   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
264   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
265   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
266   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
267   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
268   setOperationAction(ISD::FP_ROUND,  MVT::f32, Custom);
269   setOperationAction(ISD::FP_ROUND,  MVT::f64, Custom);
270
271   // This prevents LLVM trying to compress double constants into a floating
272   // constant-pool entry and trying to load from there. It's of doubtful benefit
273   // for A64: we'd need LDR followed by FCVT, I believe.
274   setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
275   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
276   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
277
278   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
279   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
280   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
281   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
282   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
283   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
284
285   setExceptionPointerRegister(AArch64::X0);
286   setExceptionSelectorRegister(AArch64::X1);
287
288   if (Subtarget->hasNEON()) {
289     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Expand);
290     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Expand);
291     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Expand);
292     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v1i64, Expand);
293     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v16i8, Expand);
294     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Expand);
295     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Expand);
296     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Expand);
297
298     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i8, Custom);
299     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
300     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
301     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i16, Custom);
302     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
303     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
304     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i32, Custom);
305     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
306     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
307     setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
308     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
309     setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
310     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
311     setOperationAction(ISD::BUILD_VECTOR, MVT::v1f64, Custom);
312     setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
313
314     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
315     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
316     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
317     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
318     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
319     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i32, Custom);
320     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
321     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
322     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f32, Custom);
323     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
324     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1f64, Custom);
325     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
326
327     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i32, Legal);
328     setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Legal);
329     setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Legal);
330     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Legal);
331     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Legal);
332     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Legal);
333     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Legal);
334
335     setOperationAction(ISD::SETCC, MVT::v8i8, Custom);
336     setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
337     setOperationAction(ISD::SETCC, MVT::v4i16, Custom);
338     setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
339     setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
340     setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
341     setOperationAction(ISD::SETCC, MVT::v1i64, Custom);
342     setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
343     setOperationAction(ISD::SETCC, MVT::v2f32, Custom);
344     setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
345     setOperationAction(ISD::SETCC, MVT::v1f64, Custom);
346     setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
347
348     setOperationAction(ISD::FFLOOR, MVT::v2f32, Legal);
349     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
350     setOperationAction(ISD::FFLOOR, MVT::v1f64, Legal);
351     setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
352
353     setOperationAction(ISD::FCEIL, MVT::v2f32, Legal);
354     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
355     setOperationAction(ISD::FCEIL, MVT::v1f64, Legal);
356     setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
357
358     setOperationAction(ISD::FTRUNC, MVT::v2f32, Legal);
359     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
360     setOperationAction(ISD::FTRUNC, MVT::v1f64, Legal);
361     setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
362
363     setOperationAction(ISD::FRINT, MVT::v2f32, Legal);
364     setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
365     setOperationAction(ISD::FRINT, MVT::v1f64, Legal);
366     setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
367
368     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Legal);
369     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
370     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Legal);
371     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
372
373     setOperationAction(ISD::FROUND, MVT::v2f32, Legal);
374     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
375     setOperationAction(ISD::FROUND, MVT::v1f64, Legal);
376     setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
377
378     // Vector ExtLoad and TruncStore are expanded.
379     for (unsigned I = MVT::FIRST_VECTOR_VALUETYPE;
380          I <= MVT::LAST_VECTOR_VALUETYPE; ++I) {
381       MVT VT = (MVT::SimpleValueType) I;
382       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
383       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
384       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
385       for (unsigned II = MVT::FIRST_VECTOR_VALUETYPE;
386            II <= MVT::LAST_VECTOR_VALUETYPE; ++II) {
387         MVT VT1 = (MVT::SimpleValueType) II;
388         // A TruncStore has two vector types of the same number of elements
389         // and different element sizes.
390         if (VT.getVectorNumElements() == VT1.getVectorNumElements() &&
391             VT.getVectorElementType().getSizeInBits()
392                 > VT1.getVectorElementType().getSizeInBits())
393           setTruncStoreAction(VT, VT1, Expand);
394       }
395     }
396
397     // There is no v1i64/v2i64 multiply, expand v1i64/v2i64 to GPR i64 multiply.
398     // FIXME: For a v2i64 multiply, we copy VPR to GPR and do 2 i64 multiplies,
399     // and then copy back to VPR. This solution may be optimized by Following 3
400     // NEON instructions:
401     //        pmull  v2.1q, v0.1d, v1.1d
402     //        pmull2 v3.1q, v0.2d, v1.2d
403     //        ins    v2.d[1], v3.d[0]
404     // As currently we can't verify the correctness of such assumption, we can
405     // do such optimization in the future.
406     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
407     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
408   }
409 }
410
411 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
412   // It's reasonably important that this value matches the "natural" legal
413   // promotion from i1 for scalar types. Otherwise LegalizeTypes can get itself
414   // in a twist (e.g. inserting an any_extend which then becomes i64 -> i64).
415   if (!VT.isVector()) return MVT::i32;
416   return VT.changeVectorElementTypeToInteger();
417 }
418
419 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
420                                   unsigned &LdrOpc,
421                                   unsigned &StrOpc) {
422   static const unsigned LoadBares[] = {AArch64::LDXR_byte, AArch64::LDXR_hword,
423                                        AArch64::LDXR_word, AArch64::LDXR_dword};
424   static const unsigned LoadAcqs[] = {AArch64::LDAXR_byte, AArch64::LDAXR_hword,
425                                      AArch64::LDAXR_word, AArch64::LDAXR_dword};
426   static const unsigned StoreBares[] = {AArch64::STXR_byte, AArch64::STXR_hword,
427                                        AArch64::STXR_word, AArch64::STXR_dword};
428   static const unsigned StoreRels[] = {AArch64::STLXR_byte,AArch64::STLXR_hword,
429                                      AArch64::STLXR_word, AArch64::STLXR_dword};
430
431   const unsigned *LoadOps, *StoreOps;
432   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
433     LoadOps = LoadAcqs;
434   else
435     LoadOps = LoadBares;
436
437   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
438     StoreOps = StoreRels;
439   else
440     StoreOps = StoreBares;
441
442   assert(isPowerOf2_32(Size) && Size <= 8 &&
443          "unsupported size for atomic binary op!");
444
445   LdrOpc = LoadOps[Log2_32(Size)];
446   StrOpc = StoreOps[Log2_32(Size)];
447 }
448
449 // FIXME: AArch64::DTripleRegClass and AArch64::QTripleRegClass don't really
450 // have value type mapped, and they are both being defined as MVT::untyped.
451 // Without knowing the MVT type, MachineLICM::getRegisterClassIDAndCost
452 // would fail to figure out the register pressure correctly.
453 std::pair<const TargetRegisterClass*, uint8_t>
454 AArch64TargetLowering::findRepresentativeClass(MVT VT) const{
455   const TargetRegisterClass *RRC = 0;
456   uint8_t Cost = 1;
457   switch (VT.SimpleTy) {
458   default:
459     return TargetLowering::findRepresentativeClass(VT);
460   case MVT::v4i64:
461     RRC = &AArch64::QPairRegClass;
462     Cost = 2;
463     break;
464   case MVT::v8i64:
465     RRC = &AArch64::QQuadRegClass;
466     Cost = 4;
467     break;
468   }
469   return std::make_pair(RRC, Cost);
470 }
471
472 MachineBasicBlock *
473 AArch64TargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
474                                         unsigned Size,
475                                         unsigned BinOpcode) const {
476   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
477   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
478
479   const BasicBlock *LLVM_BB = BB->getBasicBlock();
480   MachineFunction *MF = BB->getParent();
481   MachineFunction::iterator It = BB;
482   ++It;
483
484   unsigned dest = MI->getOperand(0).getReg();
485   unsigned ptr = MI->getOperand(1).getReg();
486   unsigned incr = MI->getOperand(2).getReg();
487   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
488   DebugLoc dl = MI->getDebugLoc();
489
490   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
491
492   unsigned ldrOpc, strOpc;
493   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
494
495   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
496   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
497   MF->insert(It, loopMBB);
498   MF->insert(It, exitMBB);
499
500   // Transfer the remainder of BB and its successor edges to exitMBB.
501   exitMBB->splice(exitMBB->begin(), BB,
502                   llvm::next(MachineBasicBlock::iterator(MI)),
503                   BB->end());
504   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
505
506   const TargetRegisterClass *TRC
507     = Size == 8 ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
508   unsigned scratch = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
509
510   //  thisMBB:
511   //   ...
512   //   fallthrough --> loopMBB
513   BB->addSuccessor(loopMBB);
514
515   //  loopMBB:
516   //   ldxr dest, ptr
517   //   <binop> scratch, dest, incr
518   //   stxr stxr_status, scratch, ptr
519   //   cbnz stxr_status, loopMBB
520   //   fallthrough --> exitMBB
521   BB = loopMBB;
522   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
523   if (BinOpcode) {
524     // All arithmetic operations we'll be creating are designed to take an extra
525     // shift or extend operand, which we can conveniently set to zero.
526
527     // Operand order needs to go the other way for NAND.
528     if (BinOpcode == AArch64::BICwww_lsl || BinOpcode == AArch64::BICxxx_lsl)
529       BuildMI(BB, dl, TII->get(BinOpcode), scratch)
530         .addReg(incr).addReg(dest).addImm(0);
531     else
532       BuildMI(BB, dl, TII->get(BinOpcode), scratch)
533         .addReg(dest).addReg(incr).addImm(0);
534   }
535
536   // From the stxr, the register is GPR32; from the cmp it's GPR32wsp
537   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
538   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
539
540   BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(scratch).addReg(ptr);
541   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
542     .addReg(stxr_status).addMBB(loopMBB);
543
544   BB->addSuccessor(loopMBB);
545   BB->addSuccessor(exitMBB);
546
547   //  exitMBB:
548   //   ...
549   BB = exitMBB;
550
551   MI->eraseFromParent();   // The instruction is gone now.
552
553   return BB;
554 }
555
556 MachineBasicBlock *
557 AArch64TargetLowering::emitAtomicBinaryMinMax(MachineInstr *MI,
558                                               MachineBasicBlock *BB,
559                                               unsigned Size,
560                                               unsigned CmpOp,
561                                               A64CC::CondCodes Cond) const {
562   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
563
564   const BasicBlock *LLVM_BB = BB->getBasicBlock();
565   MachineFunction *MF = BB->getParent();
566   MachineFunction::iterator It = BB;
567   ++It;
568
569   unsigned dest = MI->getOperand(0).getReg();
570   unsigned ptr = MI->getOperand(1).getReg();
571   unsigned incr = MI->getOperand(2).getReg();
572   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
573
574   unsigned oldval = dest;
575   DebugLoc dl = MI->getDebugLoc();
576
577   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
578   const TargetRegisterClass *TRC, *TRCsp;
579   if (Size == 8) {
580     TRC = &AArch64::GPR64RegClass;
581     TRCsp = &AArch64::GPR64xspRegClass;
582   } else {
583     TRC = &AArch64::GPR32RegClass;
584     TRCsp = &AArch64::GPR32wspRegClass;
585   }
586
587   unsigned ldrOpc, strOpc;
588   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
589
590   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
591   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
592   MF->insert(It, loopMBB);
593   MF->insert(It, exitMBB);
594
595   // Transfer the remainder of BB and its successor edges to exitMBB.
596   exitMBB->splice(exitMBB->begin(), BB,
597                   llvm::next(MachineBasicBlock::iterator(MI)),
598                   BB->end());
599   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
600
601   unsigned scratch = MRI.createVirtualRegister(TRC);
602   MRI.constrainRegClass(scratch, TRCsp);
603
604   //  thisMBB:
605   //   ...
606   //   fallthrough --> loopMBB
607   BB->addSuccessor(loopMBB);
608
609   //  loopMBB:
610   //   ldxr dest, ptr
611   //   cmp incr, dest (, sign extend if necessary)
612   //   csel scratch, dest, incr, cond
613   //   stxr stxr_status, scratch, ptr
614   //   cbnz stxr_status, loopMBB
615   //   fallthrough --> exitMBB
616   BB = loopMBB;
617   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
618
619   // Build compare and cmov instructions.
620   MRI.constrainRegClass(incr, TRCsp);
621   BuildMI(BB, dl, TII->get(CmpOp))
622     .addReg(incr).addReg(oldval).addImm(0);
623
624   BuildMI(BB, dl, TII->get(Size == 8 ? AArch64::CSELxxxc : AArch64::CSELwwwc),
625           scratch)
626     .addReg(oldval).addReg(incr).addImm(Cond);
627
628   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
629   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
630
631   BuildMI(BB, dl, TII->get(strOpc), stxr_status)
632     .addReg(scratch).addReg(ptr);
633   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
634     .addReg(stxr_status).addMBB(loopMBB);
635
636   BB->addSuccessor(loopMBB);
637   BB->addSuccessor(exitMBB);
638
639   //  exitMBB:
640   //   ...
641   BB = exitMBB;
642
643   MI->eraseFromParent();   // The instruction is gone now.
644
645   return BB;
646 }
647
648 MachineBasicBlock *
649 AArch64TargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
650                                          MachineBasicBlock *BB,
651                                          unsigned Size) const {
652   unsigned dest    = MI->getOperand(0).getReg();
653   unsigned ptr     = MI->getOperand(1).getReg();
654   unsigned oldval  = MI->getOperand(2).getReg();
655   unsigned newval  = MI->getOperand(3).getReg();
656   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
657   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
658   DebugLoc dl = MI->getDebugLoc();
659
660   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
661   const TargetRegisterClass *TRCsp;
662   TRCsp = Size == 8 ? &AArch64::GPR64xspRegClass : &AArch64::GPR32wspRegClass;
663
664   unsigned ldrOpc, strOpc;
665   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
666
667   MachineFunction *MF = BB->getParent();
668   const BasicBlock *LLVM_BB = BB->getBasicBlock();
669   MachineFunction::iterator It = BB;
670   ++It; // insert the new blocks after the current block
671
672   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
673   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
674   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
675   MF->insert(It, loop1MBB);
676   MF->insert(It, loop2MBB);
677   MF->insert(It, exitMBB);
678
679   // Transfer the remainder of BB and its successor edges to exitMBB.
680   exitMBB->splice(exitMBB->begin(), BB,
681                   llvm::next(MachineBasicBlock::iterator(MI)),
682                   BB->end());
683   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
684
685   //  thisMBB:
686   //   ...
687   //   fallthrough --> loop1MBB
688   BB->addSuccessor(loop1MBB);
689
690   // loop1MBB:
691   //   ldxr dest, [ptr]
692   //   cmp dest, oldval
693   //   b.ne exitMBB
694   BB = loop1MBB;
695   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
696
697   unsigned CmpOp = Size == 8 ? AArch64::CMPxx_lsl : AArch64::CMPww_lsl;
698   MRI.constrainRegClass(dest, TRCsp);
699   BuildMI(BB, dl, TII->get(CmpOp))
700     .addReg(dest).addReg(oldval).addImm(0);
701   BuildMI(BB, dl, TII->get(AArch64::Bcc))
702     .addImm(A64CC::NE).addMBB(exitMBB);
703   BB->addSuccessor(loop2MBB);
704   BB->addSuccessor(exitMBB);
705
706   // loop2MBB:
707   //   strex stxr_status, newval, [ptr]
708   //   cbnz stxr_status, loop1MBB
709   BB = loop2MBB;
710   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
711   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
712
713   BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(newval).addReg(ptr);
714   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
715     .addReg(stxr_status).addMBB(loop1MBB);
716   BB->addSuccessor(loop1MBB);
717   BB->addSuccessor(exitMBB);
718
719   //  exitMBB:
720   //   ...
721   BB = exitMBB;
722
723   MI->eraseFromParent();   // The instruction is gone now.
724
725   return BB;
726 }
727
728 MachineBasicBlock *
729 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
730                                     MachineBasicBlock *MBB) const {
731   // We materialise the F128CSEL pseudo-instruction using conditional branches
732   // and loads, giving an instruciton sequence like:
733   //     str q0, [sp]
734   //     b.ne IfTrue
735   //     b Finish
736   // IfTrue:
737   //     str q1, [sp]
738   // Finish:
739   //     ldr q0, [sp]
740   //
741   // Using virtual registers would probably not be beneficial since COPY
742   // instructions are expensive for f128 (there's no actual instruction to
743   // implement them).
744   //
745   // An alternative would be to do an integer-CSEL on some address. E.g.:
746   //     mov x0, sp
747   //     add x1, sp, #16
748   //     str q0, [x0]
749   //     str q1, [x1]
750   //     csel x0, x0, x1, ne
751   //     ldr q0, [x0]
752   //
753   // It's unclear which approach is actually optimal.
754   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
755   MachineFunction *MF = MBB->getParent();
756   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
757   DebugLoc DL = MI->getDebugLoc();
758   MachineFunction::iterator It = MBB;
759   ++It;
760
761   unsigned DestReg = MI->getOperand(0).getReg();
762   unsigned IfTrueReg = MI->getOperand(1).getReg();
763   unsigned IfFalseReg = MI->getOperand(2).getReg();
764   unsigned CondCode = MI->getOperand(3).getImm();
765   bool NZCVKilled = MI->getOperand(4).isKill();
766
767   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
768   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
769   MF->insert(It, TrueBB);
770   MF->insert(It, EndBB);
771
772   // Transfer rest of current basic-block to EndBB
773   EndBB->splice(EndBB->begin(), MBB,
774                 llvm::next(MachineBasicBlock::iterator(MI)),
775                 MBB->end());
776   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
777
778   // We need somewhere to store the f128 value needed.
779   int ScratchFI = MF->getFrameInfo()->CreateSpillStackObject(16, 16);
780
781   //     [... start of incoming MBB ...]
782   //     str qIFFALSE, [sp]
783   //     b.cc IfTrue
784   //     b Done
785   BuildMI(MBB, DL, TII->get(AArch64::LSFP128_STR))
786     .addReg(IfFalseReg)
787     .addFrameIndex(ScratchFI)
788     .addImm(0);
789   BuildMI(MBB, DL, TII->get(AArch64::Bcc))
790     .addImm(CondCode)
791     .addMBB(TrueBB);
792   BuildMI(MBB, DL, TII->get(AArch64::Bimm))
793     .addMBB(EndBB);
794   MBB->addSuccessor(TrueBB);
795   MBB->addSuccessor(EndBB);
796
797   if (!NZCVKilled) {
798     // NZCV is live-through TrueBB.
799     TrueBB->addLiveIn(AArch64::NZCV);
800     EndBB->addLiveIn(AArch64::NZCV);
801   }
802
803   // IfTrue:
804   //     str qIFTRUE, [sp]
805   BuildMI(TrueBB, DL, TII->get(AArch64::LSFP128_STR))
806     .addReg(IfTrueReg)
807     .addFrameIndex(ScratchFI)
808     .addImm(0);
809
810   // Note: fallthrough. We can rely on LLVM adding a branch if it reorders the
811   // blocks.
812   TrueBB->addSuccessor(EndBB);
813
814   // Done:
815   //     ldr qDEST, [sp]
816   //     [... rest of incoming MBB ...]
817   MachineInstr *StartOfEnd = EndBB->begin();
818   BuildMI(*EndBB, StartOfEnd, DL, TII->get(AArch64::LSFP128_LDR), DestReg)
819     .addFrameIndex(ScratchFI)
820     .addImm(0);
821
822   MI->eraseFromParent();
823   return EndBB;
824 }
825
826 MachineBasicBlock *
827 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
828                                                  MachineBasicBlock *MBB) const {
829   switch (MI->getOpcode()) {
830   default: llvm_unreachable("Unhandled instruction with custom inserter");
831   case AArch64::F128CSEL:
832     return EmitF128CSEL(MI, MBB);
833   case AArch64::ATOMIC_LOAD_ADD_I8:
834     return emitAtomicBinary(MI, MBB, 1, AArch64::ADDwww_lsl);
835   case AArch64::ATOMIC_LOAD_ADD_I16:
836     return emitAtomicBinary(MI, MBB, 2, AArch64::ADDwww_lsl);
837   case AArch64::ATOMIC_LOAD_ADD_I32:
838     return emitAtomicBinary(MI, MBB, 4, AArch64::ADDwww_lsl);
839   case AArch64::ATOMIC_LOAD_ADD_I64:
840     return emitAtomicBinary(MI, MBB, 8, AArch64::ADDxxx_lsl);
841
842   case AArch64::ATOMIC_LOAD_SUB_I8:
843     return emitAtomicBinary(MI, MBB, 1, AArch64::SUBwww_lsl);
844   case AArch64::ATOMIC_LOAD_SUB_I16:
845     return emitAtomicBinary(MI, MBB, 2, AArch64::SUBwww_lsl);
846   case AArch64::ATOMIC_LOAD_SUB_I32:
847     return emitAtomicBinary(MI, MBB, 4, AArch64::SUBwww_lsl);
848   case AArch64::ATOMIC_LOAD_SUB_I64:
849     return emitAtomicBinary(MI, MBB, 8, AArch64::SUBxxx_lsl);
850
851   case AArch64::ATOMIC_LOAD_AND_I8:
852     return emitAtomicBinary(MI, MBB, 1, AArch64::ANDwww_lsl);
853   case AArch64::ATOMIC_LOAD_AND_I16:
854     return emitAtomicBinary(MI, MBB, 2, AArch64::ANDwww_lsl);
855   case AArch64::ATOMIC_LOAD_AND_I32:
856     return emitAtomicBinary(MI, MBB, 4, AArch64::ANDwww_lsl);
857   case AArch64::ATOMIC_LOAD_AND_I64:
858     return emitAtomicBinary(MI, MBB, 8, AArch64::ANDxxx_lsl);
859
860   case AArch64::ATOMIC_LOAD_OR_I8:
861     return emitAtomicBinary(MI, MBB, 1, AArch64::ORRwww_lsl);
862   case AArch64::ATOMIC_LOAD_OR_I16:
863     return emitAtomicBinary(MI, MBB, 2, AArch64::ORRwww_lsl);
864   case AArch64::ATOMIC_LOAD_OR_I32:
865     return emitAtomicBinary(MI, MBB, 4, AArch64::ORRwww_lsl);
866   case AArch64::ATOMIC_LOAD_OR_I64:
867     return emitAtomicBinary(MI, MBB, 8, AArch64::ORRxxx_lsl);
868
869   case AArch64::ATOMIC_LOAD_XOR_I8:
870     return emitAtomicBinary(MI, MBB, 1, AArch64::EORwww_lsl);
871   case AArch64::ATOMIC_LOAD_XOR_I16:
872     return emitAtomicBinary(MI, MBB, 2, AArch64::EORwww_lsl);
873   case AArch64::ATOMIC_LOAD_XOR_I32:
874     return emitAtomicBinary(MI, MBB, 4, AArch64::EORwww_lsl);
875   case AArch64::ATOMIC_LOAD_XOR_I64:
876     return emitAtomicBinary(MI, MBB, 8, AArch64::EORxxx_lsl);
877
878   case AArch64::ATOMIC_LOAD_NAND_I8:
879     return emitAtomicBinary(MI, MBB, 1, AArch64::BICwww_lsl);
880   case AArch64::ATOMIC_LOAD_NAND_I16:
881     return emitAtomicBinary(MI, MBB, 2, AArch64::BICwww_lsl);
882   case AArch64::ATOMIC_LOAD_NAND_I32:
883     return emitAtomicBinary(MI, MBB, 4, AArch64::BICwww_lsl);
884   case AArch64::ATOMIC_LOAD_NAND_I64:
885     return emitAtomicBinary(MI, MBB, 8, AArch64::BICxxx_lsl);
886
887   case AArch64::ATOMIC_LOAD_MIN_I8:
888     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::GT);
889   case AArch64::ATOMIC_LOAD_MIN_I16:
890     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::GT);
891   case AArch64::ATOMIC_LOAD_MIN_I32:
892     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::GT);
893   case AArch64::ATOMIC_LOAD_MIN_I64:
894     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::GT);
895
896   case AArch64::ATOMIC_LOAD_MAX_I8:
897     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::LT);
898   case AArch64::ATOMIC_LOAD_MAX_I16:
899     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::LT);
900   case AArch64::ATOMIC_LOAD_MAX_I32:
901     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LT);
902   case AArch64::ATOMIC_LOAD_MAX_I64:
903     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LT);
904
905   case AArch64::ATOMIC_LOAD_UMIN_I8:
906     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::HI);
907   case AArch64::ATOMIC_LOAD_UMIN_I16:
908     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::HI);
909   case AArch64::ATOMIC_LOAD_UMIN_I32:
910     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::HI);
911   case AArch64::ATOMIC_LOAD_UMIN_I64:
912     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::HI);
913
914   case AArch64::ATOMIC_LOAD_UMAX_I8:
915     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::LO);
916   case AArch64::ATOMIC_LOAD_UMAX_I16:
917     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::LO);
918   case AArch64::ATOMIC_LOAD_UMAX_I32:
919     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LO);
920   case AArch64::ATOMIC_LOAD_UMAX_I64:
921     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LO);
922
923   case AArch64::ATOMIC_SWAP_I8:
924     return emitAtomicBinary(MI, MBB, 1, 0);
925   case AArch64::ATOMIC_SWAP_I16:
926     return emitAtomicBinary(MI, MBB, 2, 0);
927   case AArch64::ATOMIC_SWAP_I32:
928     return emitAtomicBinary(MI, MBB, 4, 0);
929   case AArch64::ATOMIC_SWAP_I64:
930     return emitAtomicBinary(MI, MBB, 8, 0);
931
932   case AArch64::ATOMIC_CMP_SWAP_I8:
933     return emitAtomicCmpSwap(MI, MBB, 1);
934   case AArch64::ATOMIC_CMP_SWAP_I16:
935     return emitAtomicCmpSwap(MI, MBB, 2);
936   case AArch64::ATOMIC_CMP_SWAP_I32:
937     return emitAtomicCmpSwap(MI, MBB, 4);
938   case AArch64::ATOMIC_CMP_SWAP_I64:
939     return emitAtomicCmpSwap(MI, MBB, 8);
940   }
941 }
942
943
944 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
945   switch (Opcode) {
946   case AArch64ISD::BR_CC:          return "AArch64ISD::BR_CC";
947   case AArch64ISD::Call:           return "AArch64ISD::Call";
948   case AArch64ISD::FPMOV:          return "AArch64ISD::FPMOV";
949   case AArch64ISD::GOTLoad:        return "AArch64ISD::GOTLoad";
950   case AArch64ISD::BFI:            return "AArch64ISD::BFI";
951   case AArch64ISD::EXTR:           return "AArch64ISD::EXTR";
952   case AArch64ISD::Ret:            return "AArch64ISD::Ret";
953   case AArch64ISD::SBFX:           return "AArch64ISD::SBFX";
954   case AArch64ISD::SELECT_CC:      return "AArch64ISD::SELECT_CC";
955   case AArch64ISD::SETCC:          return "AArch64ISD::SETCC";
956   case AArch64ISD::TC_RETURN:      return "AArch64ISD::TC_RETURN";
957   case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
958   case AArch64ISD::TLSDESCCALL:    return "AArch64ISD::TLSDESCCALL";
959   case AArch64ISD::WrapperLarge:   return "AArch64ISD::WrapperLarge";
960   case AArch64ISD::WrapperSmall:   return "AArch64ISD::WrapperSmall";
961
962   case AArch64ISD::NEON_MOVIMM:
963     return "AArch64ISD::NEON_MOVIMM";
964   case AArch64ISD::NEON_MVNIMM:
965     return "AArch64ISD::NEON_MVNIMM";
966   case AArch64ISD::NEON_FMOVIMM:
967     return "AArch64ISD::NEON_FMOVIMM";
968   case AArch64ISD::NEON_CMP:
969     return "AArch64ISD::NEON_CMP";
970   case AArch64ISD::NEON_CMPZ:
971     return "AArch64ISD::NEON_CMPZ";
972   case AArch64ISD::NEON_TST:
973     return "AArch64ISD::NEON_TST";
974   case AArch64ISD::NEON_QSHLs:
975     return "AArch64ISD::NEON_QSHLs";
976   case AArch64ISD::NEON_QSHLu:
977     return "AArch64ISD::NEON_QSHLu";
978   case AArch64ISD::NEON_VDUP:
979     return "AArch64ISD::NEON_VDUP";
980   case AArch64ISD::NEON_VDUPLANE:
981     return "AArch64ISD::NEON_VDUPLANE";
982   case AArch64ISD::NEON_REV16:
983     return "AArch64ISD::NEON_REV16";
984   case AArch64ISD::NEON_REV32:
985     return "AArch64ISD::NEON_REV32";
986   case AArch64ISD::NEON_REV64:
987     return "AArch64ISD::NEON_REV64";
988   case AArch64ISD::NEON_UZP1:
989     return "AArch64ISD::NEON_UZP1";
990   case AArch64ISD::NEON_UZP2:
991     return "AArch64ISD::NEON_UZP2";
992   case AArch64ISD::NEON_ZIP1:
993     return "AArch64ISD::NEON_ZIP1";
994   case AArch64ISD::NEON_ZIP2:
995     return "AArch64ISD::NEON_ZIP2";
996   case AArch64ISD::NEON_TRN1:
997     return "AArch64ISD::NEON_TRN1";
998   case AArch64ISD::NEON_TRN2:
999     return "AArch64ISD::NEON_TRN2";
1000   case AArch64ISD::NEON_LD1_UPD:
1001     return "AArch64ISD::NEON_LD1_UPD";
1002   case AArch64ISD::NEON_LD2_UPD:
1003     return "AArch64ISD::NEON_LD2_UPD";
1004   case AArch64ISD::NEON_LD3_UPD:
1005     return "AArch64ISD::NEON_LD3_UPD";
1006   case AArch64ISD::NEON_LD4_UPD:
1007     return "AArch64ISD::NEON_LD4_UPD";
1008   case AArch64ISD::NEON_ST1_UPD:
1009     return "AArch64ISD::NEON_ST1_UPD";
1010   case AArch64ISD::NEON_ST2_UPD:
1011     return "AArch64ISD::NEON_ST2_UPD";
1012   case AArch64ISD::NEON_ST3_UPD:
1013     return "AArch64ISD::NEON_ST3_UPD";
1014   case AArch64ISD::NEON_ST4_UPD:
1015     return "AArch64ISD::NEON_ST4_UPD";
1016   case AArch64ISD::NEON_LD1x2_UPD:
1017     return "AArch64ISD::NEON_LD1x2_UPD";
1018   case AArch64ISD::NEON_LD1x3_UPD:
1019     return "AArch64ISD::NEON_LD1x3_UPD";
1020   case AArch64ISD::NEON_LD1x4_UPD:
1021     return "AArch64ISD::NEON_LD1x4_UPD";
1022   case AArch64ISD::NEON_ST1x2_UPD:
1023     return "AArch64ISD::NEON_ST1x2_UPD";
1024   case AArch64ISD::NEON_ST1x3_UPD:
1025     return "AArch64ISD::NEON_ST1x3_UPD";
1026   case AArch64ISD::NEON_ST1x4_UPD:
1027     return "AArch64ISD::NEON_ST1x4_UPD";
1028   case AArch64ISD::NEON_LD2DUP:
1029     return "AArch64ISD::NEON_LD2DUP";
1030   case AArch64ISD::NEON_LD3DUP:
1031     return "AArch64ISD::NEON_LD3DUP";
1032   case AArch64ISD::NEON_LD4DUP:
1033     return "AArch64ISD::NEON_LD4DUP";
1034   case AArch64ISD::NEON_LD2DUP_UPD:
1035     return "AArch64ISD::NEON_LD2DUP_UPD";
1036   case AArch64ISD::NEON_LD3DUP_UPD:
1037     return "AArch64ISD::NEON_LD3DUP_UPD";
1038   case AArch64ISD::NEON_LD4DUP_UPD:
1039     return "AArch64ISD::NEON_LD4DUP_UPD";
1040   case AArch64ISD::NEON_LD2LN_UPD:
1041     return "AArch64ISD::NEON_LD2LN_UPD";
1042   case AArch64ISD::NEON_LD3LN_UPD:
1043     return "AArch64ISD::NEON_LD3LN_UPD";
1044   case AArch64ISD::NEON_LD4LN_UPD:
1045     return "AArch64ISD::NEON_LD4LN_UPD";
1046   case AArch64ISD::NEON_ST2LN_UPD:
1047     return "AArch64ISD::NEON_ST2LN_UPD";
1048   case AArch64ISD::NEON_ST3LN_UPD:
1049     return "AArch64ISD::NEON_ST3LN_UPD";
1050   case AArch64ISD::NEON_ST4LN_UPD:
1051     return "AArch64ISD::NEON_ST4LN_UPD";
1052   case AArch64ISD::NEON_VEXTRACT:
1053     return "AArch64ISD::NEON_VEXTRACT";
1054   default:
1055     return NULL;
1056   }
1057 }
1058
1059 static const uint16_t AArch64FPRArgRegs[] = {
1060   AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
1061   AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7
1062 };
1063 static const unsigned NumFPRArgRegs = llvm::array_lengthof(AArch64FPRArgRegs);
1064
1065 static const uint16_t AArch64ArgRegs[] = {
1066   AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3,
1067   AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7
1068 };
1069 static const unsigned NumArgRegs = llvm::array_lengthof(AArch64ArgRegs);
1070
1071 static bool CC_AArch64NoMoreRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
1072                                  CCValAssign::LocInfo LocInfo,
1073                                  ISD::ArgFlagsTy ArgFlags, CCState &State) {
1074   // Mark all remaining general purpose registers as allocated. We don't
1075   // backtrack: if (for example) an i128 gets put on the stack, no subsequent
1076   // i64 will go in registers (C.11).
1077   for (unsigned i = 0; i < NumArgRegs; ++i)
1078     State.AllocateReg(AArch64ArgRegs[i]);
1079
1080   return false;
1081 }
1082
1083 #include "AArch64GenCallingConv.inc"
1084
1085 CCAssignFn *AArch64TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1086
1087   switch(CC) {
1088   default: llvm_unreachable("Unsupported calling convention");
1089   case CallingConv::Fast:
1090   case CallingConv::C:
1091     return CC_A64_APCS;
1092   }
1093 }
1094
1095 void
1096 AArch64TargetLowering::SaveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG,
1097                                            SDLoc DL, SDValue &Chain) const {
1098   MachineFunction &MF = DAG.getMachineFunction();
1099   MachineFrameInfo *MFI = MF.getFrameInfo();
1100   AArch64MachineFunctionInfo *FuncInfo
1101     = MF.getInfo<AArch64MachineFunctionInfo>();
1102
1103   SmallVector<SDValue, 8> MemOps;
1104
1105   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(AArch64ArgRegs,
1106                                                          NumArgRegs);
1107   unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(AArch64FPRArgRegs,
1108                                                          NumFPRArgRegs);
1109
1110   unsigned GPRSaveSize = 8 * (NumArgRegs - FirstVariadicGPR);
1111   int GPRIdx = 0;
1112   if (GPRSaveSize != 0) {
1113     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1114
1115     SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1116
1117     for (unsigned i = FirstVariadicGPR; i < NumArgRegs; ++i) {
1118       unsigned VReg = MF.addLiveIn(AArch64ArgRegs[i], &AArch64::GPR64RegClass);
1119       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1120       SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
1121                                    MachinePointerInfo::getStack(i * 8),
1122                                    false, false, 0);
1123       MemOps.push_back(Store);
1124       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1125                         DAG.getConstant(8, getPointerTy()));
1126     }
1127   }
1128
1129   if (getSubtarget()->hasFPARMv8()) {
1130   unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1131   int FPRIdx = 0;
1132     // According to the AArch64 Procedure Call Standard, section B.1/B.3, we
1133     // can omit a register save area if we know we'll never use registers of
1134     // that class.
1135     if (FPRSaveSize != 0) {
1136       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1137
1138       SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1139
1140       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1141         unsigned VReg = MF.addLiveIn(AArch64FPRArgRegs[i],
1142             &AArch64::FPR128RegClass);
1143         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
1144         SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
1145             MachinePointerInfo::getStack(i * 16),
1146             false, false, 0);
1147         MemOps.push_back(Store);
1148         FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1149             DAG.getConstant(16, getPointerTy()));
1150       }
1151     }
1152     FuncInfo->setVariadicFPRIdx(FPRIdx);
1153     FuncInfo->setVariadicFPRSize(FPRSaveSize);
1154   }
1155
1156   int StackIdx = MFI->CreateFixedObject(8, CCInfo.getNextStackOffset(), true);
1157
1158   FuncInfo->setVariadicStackIdx(StackIdx);
1159   FuncInfo->setVariadicGPRIdx(GPRIdx);
1160   FuncInfo->setVariadicGPRSize(GPRSaveSize);
1161
1162   if (!MemOps.empty()) {
1163     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
1164                         MemOps.size());
1165   }
1166 }
1167
1168
1169 SDValue
1170 AArch64TargetLowering::LowerFormalArguments(SDValue Chain,
1171                                       CallingConv::ID CallConv, bool isVarArg,
1172                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1173                                       SDLoc dl, SelectionDAG &DAG,
1174                                       SmallVectorImpl<SDValue> &InVals) const {
1175   MachineFunction &MF = DAG.getMachineFunction();
1176   AArch64MachineFunctionInfo *FuncInfo
1177     = MF.getInfo<AArch64MachineFunctionInfo>();
1178   MachineFrameInfo *MFI = MF.getFrameInfo();
1179   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1180
1181   SmallVector<CCValAssign, 16> ArgLocs;
1182   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1183                  getTargetMachine(), ArgLocs, *DAG.getContext());
1184   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1185
1186   SmallVector<SDValue, 16> ArgValues;
1187
1188   SDValue ArgValue;
1189   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1190     CCValAssign &VA = ArgLocs[i];
1191     ISD::ArgFlagsTy Flags = Ins[i].Flags;
1192
1193     if (Flags.isByVal()) {
1194       // Byval is used for small structs and HFAs in the PCS, but the system
1195       // should work in a non-compliant manner for larger structs.
1196       EVT PtrTy = getPointerTy();
1197       int Size = Flags.getByValSize();
1198       unsigned NumRegs = (Size + 7) / 8;
1199
1200       unsigned FrameIdx = MFI->CreateFixedObject(8 * NumRegs,
1201                                                  VA.getLocMemOffset(),
1202                                                  false);
1203       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1204       InVals.push_back(FrameIdxN);
1205
1206       continue;
1207     } else if (VA.isRegLoc()) {
1208       MVT RegVT = VA.getLocVT();
1209       const TargetRegisterClass *RC = getRegClassFor(RegVT);
1210       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1211
1212       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1213     } else { // VA.isRegLoc()
1214       assert(VA.isMemLoc());
1215
1216       int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
1217                                       VA.getLocMemOffset(), true);
1218
1219       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1220       ArgValue = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1221                              MachinePointerInfo::getFixedStack(FI),
1222                              false, false, false, 0);
1223
1224
1225     }
1226
1227     switch (VA.getLocInfo()) {
1228     default: llvm_unreachable("Unknown loc info!");
1229     case CCValAssign::Full: break;
1230     case CCValAssign::BCvt:
1231       ArgValue = DAG.getNode(ISD::BITCAST,dl, VA.getValVT(), ArgValue);
1232       break;
1233     case CCValAssign::SExt:
1234     case CCValAssign::ZExt:
1235     case CCValAssign::AExt:
1236     case CCValAssign::FPExt: {
1237       unsigned DestSize = VA.getValVT().getSizeInBits();
1238       unsigned DestSubReg;
1239
1240       switch (DestSize) {
1241       case 8: DestSubReg = AArch64::sub_8; break;
1242       case 16: DestSubReg = AArch64::sub_16; break;
1243       case 32: DestSubReg = AArch64::sub_32; break;
1244       case 64: DestSubReg = AArch64::sub_64; break;
1245       default: llvm_unreachable("Unexpected argument promotion");
1246       }
1247
1248       ArgValue = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1249                                    VA.getValVT(), ArgValue,
1250                                    DAG.getTargetConstant(DestSubReg, MVT::i32)),
1251                          0);
1252       break;
1253     }
1254     }
1255
1256     InVals.push_back(ArgValue);
1257   }
1258
1259   if (isVarArg)
1260     SaveVarArgRegisters(CCInfo, DAG, dl, Chain);
1261
1262   unsigned StackArgSize = CCInfo.getNextStackOffset();
1263   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1264     // This is a non-standard ABI so by fiat I say we're allowed to make full
1265     // use of the stack area to be popped, which must be aligned to 16 bytes in
1266     // any case:
1267     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1268
1269     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1270     // a multiple of 16.
1271     FuncInfo->setArgumentStackToRestore(StackArgSize);
1272
1273     // This realignment carries over to the available bytes below. Our own
1274     // callers will guarantee the space is free by giving an aligned value to
1275     // CALLSEQ_START.
1276   }
1277   // Even if we're not expected to free up the space, it's useful to know how
1278   // much is there while considering tail calls (because we can reuse it).
1279   FuncInfo->setBytesInStackArgArea(StackArgSize);
1280
1281   return Chain;
1282 }
1283
1284 SDValue
1285 AArch64TargetLowering::LowerReturn(SDValue Chain,
1286                                    CallingConv::ID CallConv, bool isVarArg,
1287                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1288                                    const SmallVectorImpl<SDValue> &OutVals,
1289                                    SDLoc dl, SelectionDAG &DAG) const {
1290   // CCValAssign - represent the assignment of the return value to a location.
1291   SmallVector<CCValAssign, 16> RVLocs;
1292
1293   // CCState - Info about the registers and stack slots.
1294   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1295                  getTargetMachine(), RVLocs, *DAG.getContext());
1296
1297   // Analyze outgoing return values.
1298   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv));
1299
1300   SDValue Flag;
1301   SmallVector<SDValue, 4> RetOps(1, Chain);
1302
1303   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1304     // PCS: "If the type, T, of the result of a function is such that
1305     // void func(T arg) would require that arg be passed as a value in a
1306     // register (or set of registers) according to the rules in 5.4, then the
1307     // result is returned in the same registers as would be used for such an
1308     // argument.
1309     //
1310     // Otherwise, the caller shall reserve a block of memory of sufficient
1311     // size and alignment to hold the result. The address of the memory block
1312     // shall be passed as an additional argument to the function in x8."
1313     //
1314     // This is implemented in two places. The register-return values are dealt
1315     // with here, more complex returns are passed as an sret parameter, which
1316     // means we don't have to worry about it during actual return.
1317     CCValAssign &VA = RVLocs[i];
1318     assert(VA.isRegLoc() && "Only register-returns should be created by PCS");
1319
1320
1321     SDValue Arg = OutVals[i];
1322
1323     // There's no convenient note in the ABI about this as there is for normal
1324     // arguments, but it says return values are passed in the same registers as
1325     // an argument would be. I believe that includes the comments about
1326     // unspecified higher bits, putting the burden of widening on the *caller*
1327     // for return values.
1328     switch (VA.getLocInfo()) {
1329     default: llvm_unreachable("Unknown loc info");
1330     case CCValAssign::Full: break;
1331     case CCValAssign::SExt:
1332     case CCValAssign::ZExt:
1333     case CCValAssign::AExt:
1334       // Floating-point values should only be extended when they're going into
1335       // memory, which can't happen here so an integer extend is acceptable.
1336       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1337       break;
1338     case CCValAssign::BCvt:
1339       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1340       break;
1341     }
1342
1343     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1344     Flag = Chain.getValue(1);
1345     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1346   }
1347
1348   RetOps[0] = Chain;  // Update chain.
1349
1350   // Add the flag if we have it.
1351   if (Flag.getNode())
1352     RetOps.push_back(Flag);
1353
1354   return DAG.getNode(AArch64ISD::Ret, dl, MVT::Other,
1355                      &RetOps[0], RetOps.size());
1356 }
1357
1358 unsigned AArch64TargetLowering::getByValTypeAlignment(Type *Ty) const {
1359   // This is a new backend. For anything more precise than this a FE should
1360   // set an explicit alignment.
1361   return 4;
1362 }
1363
1364 SDValue
1365 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1366                                  SmallVectorImpl<SDValue> &InVals) const {
1367   SelectionDAG &DAG                     = CLI.DAG;
1368   SDLoc &dl                             = CLI.DL;
1369   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1370   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1371   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1372   SDValue Chain                         = CLI.Chain;
1373   SDValue Callee                        = CLI.Callee;
1374   bool &IsTailCall                      = CLI.IsTailCall;
1375   CallingConv::ID CallConv              = CLI.CallConv;
1376   bool IsVarArg                         = CLI.IsVarArg;
1377
1378   MachineFunction &MF = DAG.getMachineFunction();
1379   AArch64MachineFunctionInfo *FuncInfo
1380     = MF.getInfo<AArch64MachineFunctionInfo>();
1381   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1382   bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1383   bool IsSibCall = false;
1384
1385   if (IsTailCall) {
1386     IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1387                     IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1388                                                    Outs, OutVals, Ins, DAG);
1389
1390     // A sibling call is one where we're under the usual C ABI and not planning
1391     // to change that but can still do a tail call:
1392     if (!TailCallOpt && IsTailCall)
1393       IsSibCall = true;
1394   }
1395
1396   SmallVector<CCValAssign, 16> ArgLocs;
1397   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1398                  getTargetMachine(), ArgLocs, *DAG.getContext());
1399   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1400
1401   // On AArch64 (and all other architectures I'm aware of) the most this has to
1402   // do is adjust the stack pointer.
1403   unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1404   if (IsSibCall) {
1405     // Since we're not changing the ABI to make this a tail call, the memory
1406     // operands are already available in the caller's incoming argument space.
1407     NumBytes = 0;
1408   }
1409
1410   // FPDiff is the byte offset of the call's argument area from the callee's.
1411   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1412   // by this amount for a tail call. In a sibling call it must be 0 because the
1413   // caller will deallocate the entire stack and the callee still expects its
1414   // arguments to begin at SP+0. Completely unused for non-tail calls.
1415   int FPDiff = 0;
1416
1417   if (IsTailCall && !IsSibCall) {
1418     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1419
1420     // FPDiff will be negative if this tail call requires more space than we
1421     // would automatically have in our incoming argument space. Positive if we
1422     // can actually shrink the stack.
1423     FPDiff = NumReusableBytes - NumBytes;
1424
1425     // The stack pointer must be 16-byte aligned at all times it's used for a
1426     // memory operation, which in practice means at *all* times and in
1427     // particular across call boundaries. Therefore our own arguments started at
1428     // a 16-byte aligned SP and the delta applied for the tail call should
1429     // satisfy the same constraint.
1430     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1431   }
1432
1433   if (!IsSibCall)
1434     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1435                                  dl);
1436
1437   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1438                                         getPointerTy());
1439
1440   SmallVector<SDValue, 8> MemOpChains;
1441   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1442
1443   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1444     CCValAssign &VA = ArgLocs[i];
1445     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1446     SDValue Arg = OutVals[i];
1447
1448     // Callee does the actual widening, so all extensions just use an implicit
1449     // definition of the rest of the Loc. Aesthetically, this would be nicer as
1450     // an ANY_EXTEND, but that isn't valid for floating-point types and this
1451     // alternative works on integer types too.
1452     switch (VA.getLocInfo()) {
1453     default: llvm_unreachable("Unknown loc info!");
1454     case CCValAssign::Full: break;
1455     case CCValAssign::SExt:
1456     case CCValAssign::ZExt:
1457     case CCValAssign::AExt:
1458     case CCValAssign::FPExt: {
1459       unsigned SrcSize = VA.getValVT().getSizeInBits();
1460       unsigned SrcSubReg;
1461
1462       switch (SrcSize) {
1463       case 8: SrcSubReg = AArch64::sub_8; break;
1464       case 16: SrcSubReg = AArch64::sub_16; break;
1465       case 32: SrcSubReg = AArch64::sub_32; break;
1466       case 64: SrcSubReg = AArch64::sub_64; break;
1467       default: llvm_unreachable("Unexpected argument promotion");
1468       }
1469
1470       Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1471                                     VA.getLocVT(),
1472                                     DAG.getUNDEF(VA.getLocVT()),
1473                                     Arg,
1474                                     DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1475                     0);
1476
1477       break;
1478     }
1479     case CCValAssign::BCvt:
1480       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1481       break;
1482     }
1483
1484     if (VA.isRegLoc()) {
1485       // A normal register (sub-) argument. For now we just note it down because
1486       // we want to copy things into registers as late as possible to avoid
1487       // register-pressure (and possibly worse).
1488       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1489       continue;
1490     }
1491
1492     assert(VA.isMemLoc() && "unexpected argument location");
1493
1494     SDValue DstAddr;
1495     MachinePointerInfo DstInfo;
1496     if (IsTailCall) {
1497       uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1498                                           VA.getLocVT().getSizeInBits();
1499       OpSize = (OpSize + 7) / 8;
1500       int32_t Offset = VA.getLocMemOffset() + FPDiff;
1501       int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1502
1503       DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1504       DstInfo = MachinePointerInfo::getFixedStack(FI);
1505
1506       // Make sure any stack arguments overlapping with where we're storing are
1507       // loaded before this eventual operation. Otherwise they'll be clobbered.
1508       Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1509     } else {
1510       SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1511
1512       DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1513       DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1514     }
1515
1516     if (Flags.isByVal()) {
1517       SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1518       SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1519                                   Flags.getByValAlign(),
1520                                   /*isVolatile = */ false,
1521                                   /*alwaysInline = */ false,
1522                                   DstInfo, MachinePointerInfo(0));
1523       MemOpChains.push_back(Cpy);
1524     } else {
1525       // Normal stack argument, put it where it's needed.
1526       SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1527                                    false, false, 0);
1528       MemOpChains.push_back(Store);
1529     }
1530   }
1531
1532   // The loads and stores generated above shouldn't clash with each
1533   // other. Combining them with this TokenFactor notes that fact for the rest of
1534   // the backend.
1535   if (!MemOpChains.empty())
1536     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1537                         &MemOpChains[0], MemOpChains.size());
1538
1539   // Most of the rest of the instructions need to be glued together; we don't
1540   // want assignments to actual registers used by a call to be rearranged by a
1541   // well-meaning scheduler.
1542   SDValue InFlag;
1543
1544   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1545     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1546                              RegsToPass[i].second, InFlag);
1547     InFlag = Chain.getValue(1);
1548   }
1549
1550   // The linker is responsible for inserting veneers when necessary to put a
1551   // function call destination in range, so we don't need to bother with a
1552   // wrapper here.
1553   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1554     const GlobalValue *GV = G->getGlobal();
1555     Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1556   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1557     const char *Sym = S->getSymbol();
1558     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1559   }
1560
1561   // We don't usually want to end the call-sequence here because we would tidy
1562   // the frame up *after* the call, however in the ABI-changing tail-call case
1563   // we've carefully laid out the parameters so that when sp is reset they'll be
1564   // in the correct location.
1565   if (IsTailCall && !IsSibCall) {
1566     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1567                                DAG.getIntPtrConstant(0, true), InFlag, dl);
1568     InFlag = Chain.getValue(1);
1569   }
1570
1571   // We produce the following DAG scheme for the actual call instruction:
1572   //     (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1573   //
1574   // Most arguments aren't going to be used and just keep the values live as
1575   // far as LLVM is concerned. It's expected to be selected as simply "bl
1576   // callee" (for a direct, non-tail call).
1577   std::vector<SDValue> Ops;
1578   Ops.push_back(Chain);
1579   Ops.push_back(Callee);
1580
1581   if (IsTailCall) {
1582     // Each tail call may have to adjust the stack by a different amount, so
1583     // this information must travel along with the operation for eventual
1584     // consumption by emitEpilogue.
1585     Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1586   }
1587
1588   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1589     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1590                                   RegsToPass[i].second.getValueType()));
1591
1592
1593   // Add a register mask operand representing the call-preserved registers. This
1594   // is used later in codegen to constrain register-allocation.
1595   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1596   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1597   assert(Mask && "Missing call preserved mask for calling convention");
1598   Ops.push_back(DAG.getRegisterMask(Mask));
1599
1600   // If we needed glue, put it in as the last argument.
1601   if (InFlag.getNode())
1602     Ops.push_back(InFlag);
1603
1604   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1605
1606   if (IsTailCall) {
1607     return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1608   }
1609
1610   Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1611   InFlag = Chain.getValue(1);
1612
1613   // Now we can reclaim the stack, just as well do it before working out where
1614   // our return value is.
1615   if (!IsSibCall) {
1616     uint64_t CalleePopBytes
1617       = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1618
1619     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1620                                DAG.getIntPtrConstant(CalleePopBytes, true),
1621                                InFlag, dl);
1622     InFlag = Chain.getValue(1);
1623   }
1624
1625   return LowerCallResult(Chain, InFlag, CallConv,
1626                          IsVarArg, Ins, dl, DAG, InVals);
1627 }
1628
1629 SDValue
1630 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1631                                       CallingConv::ID CallConv, bool IsVarArg,
1632                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1633                                       SDLoc dl, SelectionDAG &DAG,
1634                                       SmallVectorImpl<SDValue> &InVals) const {
1635   // Assign locations to each value returned by this call.
1636   SmallVector<CCValAssign, 16> RVLocs;
1637   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1638                  getTargetMachine(), RVLocs, *DAG.getContext());
1639   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1640
1641   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1642     CCValAssign VA = RVLocs[i];
1643
1644     // Return values that are too big to fit into registers should use an sret
1645     // pointer, so this can be a lot simpler than the main argument code.
1646     assert(VA.isRegLoc() && "Memory locations not expected for call return");
1647
1648     SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1649                                      InFlag);
1650     Chain = Val.getValue(1);
1651     InFlag = Val.getValue(2);
1652
1653     switch (VA.getLocInfo()) {
1654     default: llvm_unreachable("Unknown loc info!");
1655     case CCValAssign::Full: break;
1656     case CCValAssign::BCvt:
1657       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1658       break;
1659     case CCValAssign::ZExt:
1660     case CCValAssign::SExt:
1661     case CCValAssign::AExt:
1662       // Floating-point arguments only get extended/truncated if they're going
1663       // in memory, so using the integer operation is acceptable here.
1664       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1665       break;
1666     }
1667
1668     InVals.push_back(Val);
1669   }
1670
1671   return Chain;
1672 }
1673
1674 bool
1675 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1676                                     CallingConv::ID CalleeCC,
1677                                     bool IsVarArg,
1678                                     bool IsCalleeStructRet,
1679                                     bool IsCallerStructRet,
1680                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1681                                     const SmallVectorImpl<SDValue> &OutVals,
1682                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1683                                     SelectionDAG& DAG) const {
1684
1685   // For CallingConv::C this function knows whether the ABI needs
1686   // changing. That's not true for other conventions so they will have to opt in
1687   // manually.
1688   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1689     return false;
1690
1691   const MachineFunction &MF = DAG.getMachineFunction();
1692   const Function *CallerF = MF.getFunction();
1693   CallingConv::ID CallerCC = CallerF->getCallingConv();
1694   bool CCMatch = CallerCC == CalleeCC;
1695
1696   // Byval parameters hand the function a pointer directly into the stack area
1697   // we want to reuse during a tail call. Working around this *is* possible (see
1698   // X86) but less efficient and uglier in LowerCall.
1699   for (Function::const_arg_iterator i = CallerF->arg_begin(),
1700          e = CallerF->arg_end(); i != e; ++i)
1701     if (i->hasByValAttr())
1702       return false;
1703
1704   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1705     if (IsTailCallConvention(CalleeCC) && CCMatch)
1706       return true;
1707     return false;
1708   }
1709
1710   // Now we search for cases where we can use a tail call without changing the
1711   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1712   // concept.
1713
1714   // I want anyone implementing a new calling convention to think long and hard
1715   // about this assert.
1716   assert((!IsVarArg || CalleeCC == CallingConv::C)
1717          && "Unexpected variadic calling convention");
1718
1719   if (IsVarArg && !Outs.empty()) {
1720     // At least two cases here: if caller is fastcc then we can't have any
1721     // memory arguments (we'd be expected to clean up the stack afterwards). If
1722     // caller is C then we could potentially use its argument area.
1723
1724     // FIXME: for now we take the most conservative of these in both cases:
1725     // disallow all variadic memory operands.
1726     SmallVector<CCValAssign, 16> ArgLocs;
1727     CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1728                    getTargetMachine(), ArgLocs, *DAG.getContext());
1729
1730     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1731     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1732       if (!ArgLocs[i].isRegLoc())
1733         return false;
1734   }
1735
1736   // If the calling conventions do not match, then we'd better make sure the
1737   // results are returned in the same way as what the caller expects.
1738   if (!CCMatch) {
1739     SmallVector<CCValAssign, 16> RVLocs1;
1740     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1741                     getTargetMachine(), RVLocs1, *DAG.getContext());
1742     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1743
1744     SmallVector<CCValAssign, 16> RVLocs2;
1745     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1746                     getTargetMachine(), RVLocs2, *DAG.getContext());
1747     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1748
1749     if (RVLocs1.size() != RVLocs2.size())
1750       return false;
1751     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1752       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1753         return false;
1754       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1755         return false;
1756       if (RVLocs1[i].isRegLoc()) {
1757         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1758           return false;
1759       } else {
1760         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1761           return false;
1762       }
1763     }
1764   }
1765
1766   // Nothing more to check if the callee is taking no arguments
1767   if (Outs.empty())
1768     return true;
1769
1770   SmallVector<CCValAssign, 16> ArgLocs;
1771   CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1772                  getTargetMachine(), ArgLocs, *DAG.getContext());
1773
1774   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1775
1776   const AArch64MachineFunctionInfo *FuncInfo
1777     = MF.getInfo<AArch64MachineFunctionInfo>();
1778
1779   // If the stack arguments for this call would fit into our own save area then
1780   // the call can be made tail.
1781   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1782 }
1783
1784 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1785                                                    bool TailCallOpt) const {
1786   return CallCC == CallingConv::Fast && TailCallOpt;
1787 }
1788
1789 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1790   return CallCC == CallingConv::Fast;
1791 }
1792
1793 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1794                                                    SelectionDAG &DAG,
1795                                                    MachineFrameInfo *MFI,
1796                                                    int ClobberedFI) const {
1797   SmallVector<SDValue, 8> ArgChains;
1798   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1799   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1800
1801   // Include the original chain at the beginning of the list. When this is
1802   // used by target LowerCall hooks, this helps legalize find the
1803   // CALLSEQ_BEGIN node.
1804   ArgChains.push_back(Chain);
1805
1806   // Add a chain value for each stack argument corresponding
1807   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1808          UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1809     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1810       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1811         if (FI->getIndex() < 0) {
1812           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1813           int64_t InLastByte = InFirstByte;
1814           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1815
1816           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1817               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1818             ArgChains.push_back(SDValue(L, 1));
1819         }
1820
1821    // Build a tokenfactor for all the chains.
1822    return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1823                       &ArgChains[0], ArgChains.size());
1824 }
1825
1826 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1827   switch (CC) {
1828   case ISD::SETEQ:  return A64CC::EQ;
1829   case ISD::SETGT:  return A64CC::GT;
1830   case ISD::SETGE:  return A64CC::GE;
1831   case ISD::SETLT:  return A64CC::LT;
1832   case ISD::SETLE:  return A64CC::LE;
1833   case ISD::SETNE:  return A64CC::NE;
1834   case ISD::SETUGT: return A64CC::HI;
1835   case ISD::SETUGE: return A64CC::HS;
1836   case ISD::SETULT: return A64CC::LO;
1837   case ISD::SETULE: return A64CC::LS;
1838   default: llvm_unreachable("Unexpected condition code");
1839   }
1840 }
1841
1842 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1843   // icmp is implemented using adds/subs immediate, which take an unsigned
1844   // 12-bit immediate, optionally shifted left by 12 bits.
1845
1846   // Symmetric by using adds/subs
1847   if (Val < 0)
1848     Val = -Val;
1849
1850   return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1851 }
1852
1853 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1854                                         ISD::CondCode CC, SDValue &A64cc,
1855                                         SelectionDAG &DAG, SDLoc &dl) const {
1856   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1857     int64_t C = 0;
1858     EVT VT = RHSC->getValueType(0);
1859     bool knownInvalid = false;
1860
1861     // I'm not convinced the rest of LLVM handles these edge cases properly, but
1862     // we can at least get it right.
1863     if (isSignedIntSetCC(CC)) {
1864       C = RHSC->getSExtValue();
1865     } else if (RHSC->getZExtValue() > INT64_MAX) {
1866       // A 64-bit constant not representable by a signed 64-bit integer is far
1867       // too big to fit into a SUBS immediate anyway.
1868       knownInvalid = true;
1869     } else {
1870       C = RHSC->getZExtValue();
1871     }
1872
1873     if (!knownInvalid && !isLegalICmpImmediate(C)) {
1874       // Constant does not fit, try adjusting it by one?
1875       switch (CC) {
1876       default: break;
1877       case ISD::SETLT:
1878       case ISD::SETGE:
1879         if (isLegalICmpImmediate(C-1)) {
1880           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1881           RHS = DAG.getConstant(C-1, VT);
1882         }
1883         break;
1884       case ISD::SETULT:
1885       case ISD::SETUGE:
1886         if (isLegalICmpImmediate(C-1)) {
1887           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1888           RHS = DAG.getConstant(C-1, VT);
1889         }
1890         break;
1891       case ISD::SETLE:
1892       case ISD::SETGT:
1893         if (isLegalICmpImmediate(C+1)) {
1894           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1895           RHS = DAG.getConstant(C+1, VT);
1896         }
1897         break;
1898       case ISD::SETULE:
1899       case ISD::SETUGT:
1900         if (isLegalICmpImmediate(C+1)) {
1901           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1902           RHS = DAG.getConstant(C+1, VT);
1903         }
1904         break;
1905       }
1906     }
1907   }
1908
1909   A64CC::CondCodes CondCode = IntCCToA64CC(CC);
1910   A64cc = DAG.getConstant(CondCode, MVT::i32);
1911   return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1912                      DAG.getCondCode(CC));
1913 }
1914
1915 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
1916                                     A64CC::CondCodes &Alternative) {
1917   A64CC::CondCodes CondCode = A64CC::Invalid;
1918   Alternative = A64CC::Invalid;
1919
1920   switch (CC) {
1921   default: llvm_unreachable("Unknown FP condition!");
1922   case ISD::SETEQ:
1923   case ISD::SETOEQ: CondCode = A64CC::EQ; break;
1924   case ISD::SETGT:
1925   case ISD::SETOGT: CondCode = A64CC::GT; break;
1926   case ISD::SETGE:
1927   case ISD::SETOGE: CondCode = A64CC::GE; break;
1928   case ISD::SETOLT: CondCode = A64CC::MI; break;
1929   case ISD::SETOLE: CondCode = A64CC::LS; break;
1930   case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
1931   case ISD::SETO:   CondCode = A64CC::VC; break;
1932   case ISD::SETUO:  CondCode = A64CC::VS; break;
1933   case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
1934   case ISD::SETUGT: CondCode = A64CC::HI; break;
1935   case ISD::SETUGE: CondCode = A64CC::PL; break;
1936   case ISD::SETLT:
1937   case ISD::SETULT: CondCode = A64CC::LT; break;
1938   case ISD::SETLE:
1939   case ISD::SETULE: CondCode = A64CC::LE; break;
1940   case ISD::SETNE:
1941   case ISD::SETUNE: CondCode = A64CC::NE; break;
1942   }
1943   return CondCode;
1944 }
1945
1946 SDValue
1947 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1948   SDLoc DL(Op);
1949   EVT PtrVT = getPointerTy();
1950   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1951
1952   switch(getTargetMachine().getCodeModel()) {
1953   case CodeModel::Small:
1954     // The most efficient code is PC-relative anyway for the small memory model,
1955     // so we don't need to worry about relocation model.
1956     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
1957                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
1958                                                  AArch64II::MO_NO_FLAG),
1959                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
1960                                                  AArch64II::MO_LO12),
1961                        DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
1962   case CodeModel::Large:
1963     return DAG.getNode(
1964       AArch64ISD::WrapperLarge, DL, PtrVT,
1965       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
1966       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1967       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1968       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1969   default:
1970     llvm_unreachable("Only small and large code models supported now");
1971   }
1972 }
1973
1974
1975 // (BRCOND chain, val, dest)
1976 SDValue
1977 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1978   SDLoc dl(Op);
1979   SDValue Chain = Op.getOperand(0);
1980   SDValue TheBit = Op.getOperand(1);
1981   SDValue DestBB = Op.getOperand(2);
1982
1983   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
1984   // that as the consumer we are responsible for ignoring rubbish in higher
1985   // bits.
1986   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
1987                        DAG.getConstant(1, MVT::i32));
1988
1989   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
1990                                DAG.getConstant(0, TheBit.getValueType()),
1991                                DAG.getCondCode(ISD::SETNE));
1992
1993   return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
1994                      A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
1995                      DestBB);
1996 }
1997
1998 // (BR_CC chain, condcode, lhs, rhs, dest)
1999 SDValue
2000 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2001   SDLoc dl(Op);
2002   SDValue Chain = Op.getOperand(0);
2003   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2004   SDValue LHS = Op.getOperand(2);
2005   SDValue RHS = Op.getOperand(3);
2006   SDValue DestBB = Op.getOperand(4);
2007
2008   if (LHS.getValueType() == MVT::f128) {
2009     // f128 comparisons are lowered to runtime calls by a routine which sets
2010     // LHS, RHS and CC appropriately for the rest of this function to continue.
2011     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2012
2013     // If softenSetCCOperands returned a scalar, we need to compare the result
2014     // against zero to select between true and false values.
2015     if (RHS.getNode() == 0) {
2016       RHS = DAG.getConstant(0, LHS.getValueType());
2017       CC = ISD::SETNE;
2018     }
2019   }
2020
2021   if (LHS.getValueType().isInteger()) {
2022     SDValue A64cc;
2023
2024     // Integers are handled in a separate function because the combinations of
2025     // immediates and tests can get hairy and we may want to fiddle things.
2026     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2027
2028     return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2029                        Chain, CmpOp, A64cc, DestBB);
2030   }
2031
2032   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2033   // conditional branch, hence FPCCToA64CC can set a second test, where either
2034   // passing is sufficient.
2035   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2036   CondCode = FPCCToA64CC(CC, Alternative);
2037   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2038   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2039                               DAG.getCondCode(CC));
2040   SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2041                                  Chain, SetCC, A64cc, DestBB);
2042
2043   if (Alternative != A64CC::Invalid) {
2044     A64cc = DAG.getConstant(Alternative, MVT::i32);
2045     A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2046                            A64BR_CC, SetCC, A64cc, DestBB);
2047
2048   }
2049
2050   return A64BR_CC;
2051 }
2052
2053 SDValue
2054 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
2055                                        RTLIB::Libcall Call) const {
2056   ArgListTy Args;
2057   ArgListEntry Entry;
2058   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
2059     EVT ArgVT = Op.getOperand(i).getValueType();
2060     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2061     Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
2062     Entry.isSExt = false;
2063     Entry.isZExt = false;
2064     Args.push_back(Entry);
2065   }
2066   SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
2067
2068   Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
2069
2070   // By default, the input chain to this libcall is the entry node of the
2071   // function. If the libcall is going to be emitted as a tail call then
2072   // isUsedByReturnOnly will change it to the right chain if the return
2073   // node which is being folded has a non-entry input chain.
2074   SDValue InChain = DAG.getEntryNode();
2075
2076   // isTailCall may be true since the callee does not reference caller stack
2077   // frame. Check if it's in the right position.
2078   SDValue TCChain = InChain;
2079   bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
2080   if (isTailCall)
2081     InChain = TCChain;
2082
2083   TargetLowering::
2084   CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
2085                     0, getLibcallCallingConv(Call), isTailCall,
2086                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
2087                     Callee, Args, DAG, SDLoc(Op));
2088   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2089
2090   if (!CallInfo.second.getNode())
2091     // It's a tailcall, return the chain (which is the DAG root).
2092     return DAG.getRoot();
2093
2094   return CallInfo.first;
2095 }
2096
2097 SDValue
2098 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2099   if (Op.getOperand(0).getValueType() != MVT::f128) {
2100     // It's legal except when f128 is involved
2101     return Op;
2102   }
2103
2104   RTLIB::Libcall LC;
2105   LC  = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2106
2107   SDValue SrcVal = Op.getOperand(0);
2108   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
2109                      /*isSigned*/ false, SDLoc(Op)).first;
2110 }
2111
2112 SDValue
2113 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
2114   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2115
2116   RTLIB::Libcall LC;
2117   LC  = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2118
2119   return LowerF128ToCall(Op, DAG, LC);
2120 }
2121
2122 SDValue
2123 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
2124                                       bool IsSigned) const {
2125   if (Op.getOperand(0).getValueType() != MVT::f128) {
2126     // It's legal except when f128 is involved
2127     return Op;
2128   }
2129
2130   RTLIB::Libcall LC;
2131   if (IsSigned)
2132     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2133   else
2134     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2135
2136   return LowerF128ToCall(Op, DAG, LC);
2137 }
2138
2139 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
2140   MachineFunction &MF = DAG.getMachineFunction();
2141   MachineFrameInfo *MFI = MF.getFrameInfo();
2142   MFI->setReturnAddressIsTaken(true);
2143
2144   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2145     return SDValue();
2146
2147   EVT VT = Op.getValueType();
2148   SDLoc dl(Op);
2149   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2150   if (Depth) {
2151     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
2152     SDValue Offset = DAG.getConstant(8, MVT::i64);
2153     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
2154                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
2155                        MachinePointerInfo(), false, false, false, 0);
2156   }
2157
2158   // Return X30, which contains the return address. Mark it an implicit live-in.
2159   unsigned Reg = MF.addLiveIn(AArch64::X30, getRegClassFor(MVT::i64));
2160   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, MVT::i64);
2161 }
2162
2163
2164 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG)
2165                                               const {
2166   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2167   MFI->setFrameAddressIsTaken(true);
2168
2169   EVT VT = Op.getValueType();
2170   SDLoc dl(Op);
2171   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2172   unsigned FrameReg = AArch64::X29;
2173   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2174   while (Depth--)
2175     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
2176                             MachinePointerInfo(),
2177                             false, false, false, 0);
2178   return FrameAddr;
2179 }
2180
2181 SDValue
2182 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
2183                                                   SelectionDAG &DAG) const {
2184   assert(getTargetMachine().getCodeModel() == CodeModel::Large);
2185   assert(getTargetMachine().getRelocationModel() == Reloc::Static);
2186
2187   EVT PtrVT = getPointerTy();
2188   SDLoc dl(Op);
2189   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2190   const GlobalValue *GV = GN->getGlobal();
2191
2192   SDValue GlobalAddr = DAG.getNode(
2193       AArch64ISD::WrapperLarge, dl, PtrVT,
2194       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
2195       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
2196       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
2197       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
2198
2199   if (GN->getOffset() != 0)
2200     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2201                        DAG.getConstant(GN->getOffset(), PtrVT));
2202
2203   return GlobalAddr;
2204 }
2205
2206 SDValue
2207 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
2208                                                   SelectionDAG &DAG) const {
2209   assert(getTargetMachine().getCodeModel() == CodeModel::Small);
2210
2211   EVT PtrVT = getPointerTy();
2212   SDLoc dl(Op);
2213   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2214   const GlobalValue *GV = GN->getGlobal();
2215   unsigned Alignment = GV->getAlignment();
2216   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2217   if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
2218     // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
2219     // to zero when they remain undefined. In PIC mode the GOT can take care of
2220     // this, but in absolute mode we use a constant pool load.
2221     SDValue PoolAddr;
2222     PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2223                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2224                                                      AArch64II::MO_NO_FLAG),
2225                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2226                                                      AArch64II::MO_LO12),
2227                            DAG.getConstant(8, MVT::i32));
2228     SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
2229                                      MachinePointerInfo::getConstantPool(),
2230                                      /*isVolatile=*/ false,
2231                                      /*isNonTemporal=*/ true,
2232                                      /*isInvariant=*/ true, 8);
2233     if (GN->getOffset() != 0)
2234       return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2235                          DAG.getConstant(GN->getOffset(), PtrVT));
2236
2237     return GlobalAddr;
2238   }
2239
2240   if (Alignment == 0) {
2241     const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2242     if (GVPtrTy->getElementType()->isSized()) {
2243       Alignment
2244         = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2245     } else {
2246       // Be conservative if we can't guess, not that it really matters:
2247       // functions and labels aren't valid for loads, and the methods used to
2248       // actually calculate an address work with any alignment.
2249       Alignment = 1;
2250     }
2251   }
2252
2253   unsigned char HiFixup, LoFixup;
2254   bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2255
2256   if (UseGOT) {
2257     HiFixup = AArch64II::MO_GOT;
2258     LoFixup = AArch64II::MO_GOT_LO12;
2259     Alignment = 8;
2260   } else {
2261     HiFixup = AArch64II::MO_NO_FLAG;
2262     LoFixup = AArch64II::MO_LO12;
2263   }
2264
2265   // AArch64's small model demands the following sequence:
2266   // ADRP x0, somewhere
2267   // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2268   SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2269                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2270                                                              HiFixup),
2271                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2272                                                              LoFixup),
2273                                   DAG.getConstant(Alignment, MVT::i32));
2274
2275   if (UseGOT) {
2276     GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2277                             GlobalRef);
2278   }
2279
2280   if (GN->getOffset() != 0)
2281     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2282                        DAG.getConstant(GN->getOffset(), PtrVT));
2283
2284   return GlobalRef;
2285 }
2286
2287 SDValue
2288 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2289                                              SelectionDAG &DAG) const {
2290   // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2291   // we make those distinctions here.
2292
2293   switch (getTargetMachine().getCodeModel()) {
2294   case CodeModel::Small:
2295     return LowerGlobalAddressELFSmall(Op, DAG);
2296   case CodeModel::Large:
2297     return LowerGlobalAddressELFLarge(Op, DAG);
2298   default:
2299     llvm_unreachable("Only small and large code models supported now");
2300   }
2301 }
2302
2303 SDValue
2304 AArch64TargetLowering::LowerConstantPool(SDValue Op,
2305                                          SelectionDAG &DAG) const {
2306   SDLoc DL(Op);
2307   EVT PtrVT = getPointerTy();
2308   ConstantPoolSDNode *CN = cast<ConstantPoolSDNode>(Op);
2309   const Constant *C = CN->getConstVal();
2310
2311   switch(getTargetMachine().getCodeModel()) {
2312   case CodeModel::Small:
2313     // The most efficient code is PC-relative anyway for the small memory model,
2314     // so we don't need to worry about relocation model.
2315     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2316                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2317                                                  AArch64II::MO_NO_FLAG),
2318                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2319                                                  AArch64II::MO_LO12),
2320                        DAG.getConstant(CN->getAlignment(), MVT::i32));
2321   case CodeModel::Large:
2322     return DAG.getNode(
2323       AArch64ISD::WrapperLarge, DL, PtrVT,
2324       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G3),
2325       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G2_NC),
2326       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G1_NC),
2327       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G0_NC));
2328   default:
2329     llvm_unreachable("Only small and large code models supported now");
2330   }
2331 }
2332
2333 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2334                                                 SDValue DescAddr,
2335                                                 SDLoc DL,
2336                                                 SelectionDAG &DAG) const {
2337   EVT PtrVT = getPointerTy();
2338
2339   // The function we need to call is simply the first entry in the GOT for this
2340   // descriptor, load it in preparation.
2341   SDValue Func, Chain;
2342   Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2343                      DescAddr);
2344
2345   // The function takes only one argument: the address of the descriptor itself
2346   // in X0.
2347   SDValue Glue;
2348   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2349   Glue = Chain.getValue(1);
2350
2351   // Finally, there's a special calling-convention which means that the lookup
2352   // must preserve all registers (except X0, obviously).
2353   const TargetRegisterInfo *TRI  = getTargetMachine().getRegisterInfo();
2354   const AArch64RegisterInfo *A64RI
2355     = static_cast<const AArch64RegisterInfo *>(TRI);
2356   const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2357
2358   // We're now ready to populate the argument list, as with a normal call:
2359   std::vector<SDValue> Ops;
2360   Ops.push_back(Chain);
2361   Ops.push_back(Func);
2362   Ops.push_back(SymAddr);
2363   Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2364   Ops.push_back(DAG.getRegisterMask(Mask));
2365   Ops.push_back(Glue);
2366
2367   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2368   Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2369                       Ops.size());
2370   Glue = Chain.getValue(1);
2371
2372   // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2373   // back to the generic handling code.
2374   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2375 }
2376
2377 SDValue
2378 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2379                                              SelectionDAG &DAG) const {
2380   assert(getSubtarget()->isTargetELF() &&
2381          "TLS not implemented for non-ELF targets");
2382   assert(getTargetMachine().getCodeModel() == CodeModel::Small
2383          && "TLS only supported in small memory model");
2384   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2385
2386   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2387
2388   SDValue TPOff;
2389   EVT PtrVT = getPointerTy();
2390   SDLoc DL(Op);
2391   const GlobalValue *GV = GA->getGlobal();
2392
2393   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2394
2395   if (Model == TLSModel::InitialExec) {
2396     TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2397                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2398                                                    AArch64II::MO_GOTTPREL),
2399                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2400                                                    AArch64II::MO_GOTTPREL_LO12),
2401                         DAG.getConstant(8, MVT::i32));
2402     TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2403                         TPOff);
2404   } else if (Model == TLSModel::LocalExec) {
2405     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2406                                                AArch64II::MO_TPREL_G1);
2407     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2408                                                AArch64II::MO_TPREL_G0_NC);
2409
2410     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2411                                        DAG.getTargetConstant(1, MVT::i32)), 0);
2412     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2413                                        TPOff, LoVar,
2414                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2415   } else if (Model == TLSModel::GeneralDynamic) {
2416     // Accesses used in this sequence go via the TLS descriptor which lives in
2417     // the GOT. Prepare an address we can use to handle this.
2418     SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2419                                                 AArch64II::MO_TLSDESC);
2420     SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2421                                                 AArch64II::MO_TLSDESC_LO12);
2422     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2423                                    HiDesc, LoDesc,
2424                                    DAG.getConstant(8, MVT::i32));
2425     SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2426
2427     TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2428   } else if (Model == TLSModel::LocalDynamic) {
2429     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2430     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2431     // the beginning of the module's TLS region, followed by a DTPREL offset
2432     // calculation.
2433
2434     // These accesses will need deduplicating if there's more than one.
2435     AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2436       .getInfo<AArch64MachineFunctionInfo>();
2437     MFI->incNumLocalDynamicTLSAccesses();
2438
2439
2440     // Get the location of _TLS_MODULE_BASE_:
2441     SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2442                                                 AArch64II::MO_TLSDESC);
2443     SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2444                                                 AArch64II::MO_TLSDESC_LO12);
2445     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2446                                    HiDesc, LoDesc,
2447                                    DAG.getConstant(8, MVT::i32));
2448     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2449
2450     ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2451
2452     // Get the variable's offset from _TLS_MODULE_BASE_
2453     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2454                                                AArch64II::MO_DTPREL_G1);
2455     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2456                                                AArch64II::MO_DTPREL_G0_NC);
2457
2458     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2459                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2460     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2461                                        TPOff, LoVar,
2462                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2463   } else
2464       llvm_unreachable("Unsupported TLS access model");
2465
2466
2467   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2468 }
2469
2470 SDValue
2471 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2472                                       bool IsSigned) const {
2473   if (Op.getValueType() != MVT::f128) {
2474     // Legal for everything except f128.
2475     return Op;
2476   }
2477
2478   RTLIB::Libcall LC;
2479   if (IsSigned)
2480     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2481   else
2482     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2483
2484   return LowerF128ToCall(Op, DAG, LC);
2485 }
2486
2487
2488 SDValue
2489 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2490   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2491   SDLoc dl(JT);
2492   EVT PtrVT = getPointerTy();
2493
2494   // When compiling PIC, jump tables get put in the code section so a static
2495   // relocation-style is acceptable for both cases.
2496   switch (getTargetMachine().getCodeModel()) {
2497   case CodeModel::Small:
2498     return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2499                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2500                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2501                                               AArch64II::MO_LO12),
2502                        DAG.getConstant(1, MVT::i32));
2503   case CodeModel::Large:
2504     return DAG.getNode(
2505       AArch64ISD::WrapperLarge, dl, PtrVT,
2506       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2507       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2508       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2509       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2510   default:
2511     llvm_unreachable("Only small and large code models supported now");
2512   }
2513 }
2514
2515 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
2516 SDValue
2517 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2518   SDLoc dl(Op);
2519   SDValue LHS = Op.getOperand(0);
2520   SDValue RHS = Op.getOperand(1);
2521   SDValue IfTrue = Op.getOperand(2);
2522   SDValue IfFalse = Op.getOperand(3);
2523   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2524
2525   if (LHS.getValueType() == MVT::f128) {
2526     // f128 comparisons are lowered to libcalls, but slot in nicely here
2527     // afterwards.
2528     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2529
2530     // If softenSetCCOperands returned a scalar, we need to compare the result
2531     // against zero to select between true and false values.
2532     if (RHS.getNode() == 0) {
2533       RHS = DAG.getConstant(0, LHS.getValueType());
2534       CC = ISD::SETNE;
2535     }
2536   }
2537
2538   if (LHS.getValueType().isInteger()) {
2539     SDValue A64cc;
2540
2541     // Integers are handled in a separate function because the combinations of
2542     // immediates and tests can get hairy and we may want to fiddle things.
2543     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2544
2545     return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2546                        CmpOp, IfTrue, IfFalse, A64cc);
2547   }
2548
2549   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2550   // conditional branch, hence FPCCToA64CC can set a second test, where either
2551   // passing is sufficient.
2552   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2553   CondCode = FPCCToA64CC(CC, Alternative);
2554   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2555   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2556                               DAG.getCondCode(CC));
2557   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
2558                                      Op.getValueType(),
2559                                      SetCC, IfTrue, IfFalse, A64cc);
2560
2561   if (Alternative != A64CC::Invalid) {
2562     A64cc = DAG.getConstant(Alternative, MVT::i32);
2563     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2564                                SetCC, IfTrue, A64SELECT_CC, A64cc);
2565
2566   }
2567
2568   return A64SELECT_CC;
2569 }
2570
2571 // (SELECT testbit, iftrue, iffalse)
2572 SDValue
2573 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2574   SDLoc dl(Op);
2575   SDValue TheBit = Op.getOperand(0);
2576   SDValue IfTrue = Op.getOperand(1);
2577   SDValue IfFalse = Op.getOperand(2);
2578
2579   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2580   // that as the consumer we are responsible for ignoring rubbish in higher
2581   // bits.
2582   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2583                        DAG.getConstant(1, MVT::i32));
2584   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2585                                DAG.getConstant(0, TheBit.getValueType()),
2586                                DAG.getCondCode(ISD::SETNE));
2587
2588   return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2589                      A64CMP, IfTrue, IfFalse,
2590                      DAG.getConstant(A64CC::NE, MVT::i32));
2591 }
2592
2593 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2594   SDLoc DL(Op);
2595   SDValue LHS = Op.getOperand(0);
2596   SDValue RHS = Op.getOperand(1);
2597   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2598   EVT VT = Op.getValueType();
2599   bool Invert = false;
2600   SDValue Op0, Op1;
2601   unsigned Opcode;
2602
2603   if (LHS.getValueType().isInteger()) {
2604
2605     // Attempt to use Vector Integer Compare Mask Test instruction.
2606     // TST = icmp ne (and (op0, op1), zero).
2607     if (CC == ISD::SETNE) {
2608       if (((LHS.getOpcode() == ISD::AND) &&
2609            ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2610           ((RHS.getOpcode() == ISD::AND) &&
2611            ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2612
2613         SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2614         SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2615         SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2616         return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2617       }
2618     }
2619
2620     // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2621     // Note: Compare against Zero does not support unsigned predicates.
2622     if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2623          ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2624         !isUnsignedIntSetCC(CC)) {
2625
2626       // If LHS is the zero value, swap operands and CondCode.
2627       if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2628         CC = getSetCCSwappedOperands(CC);
2629         Op0 = RHS;
2630       } else
2631         Op0 = LHS;
2632
2633       // Ensure valid CondCode for Compare Mask against Zero instruction:
2634       // EQ, GE, GT, LE, LT.
2635       if (ISD::SETNE == CC) {
2636         Invert = true;
2637         CC = ISD::SETEQ;
2638       }
2639
2640       // Using constant type to differentiate integer and FP compares with zero.
2641       Op1 = DAG.getConstant(0, MVT::i32);
2642       Opcode = AArch64ISD::NEON_CMPZ;
2643
2644     } else {
2645       // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2646       // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2647       bool Swap = false;
2648       switch (CC) {
2649       default:
2650         llvm_unreachable("Illegal integer comparison.");
2651       case ISD::SETEQ:
2652       case ISD::SETGT:
2653       case ISD::SETGE:
2654       case ISD::SETUGT:
2655       case ISD::SETUGE:
2656         break;
2657       case ISD::SETNE:
2658         Invert = true;
2659         CC = ISD::SETEQ;
2660         break;
2661       case ISD::SETULT:
2662       case ISD::SETULE:
2663       case ISD::SETLT:
2664       case ISD::SETLE:
2665         Swap = true;
2666         CC = getSetCCSwappedOperands(CC);
2667       }
2668
2669       if (Swap)
2670         std::swap(LHS, RHS);
2671
2672       Opcode = AArch64ISD::NEON_CMP;
2673       Op0 = LHS;
2674       Op1 = RHS;
2675     }
2676
2677     // Generate Compare Mask instr or Compare Mask against Zero instr.
2678     SDValue NeonCmp =
2679         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2680
2681     if (Invert)
2682       NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2683
2684     return NeonCmp;
2685   }
2686
2687   // Now handle Floating Point cases.
2688   // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2689   if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2690       ISD::isBuildVectorAllZeros(LHS.getNode())) {
2691
2692     // If LHS is the zero value, swap operands and CondCode.
2693     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2694       CC = getSetCCSwappedOperands(CC);
2695       Op0 = RHS;
2696     } else
2697       Op0 = LHS;
2698
2699     // Using constant type to differentiate integer and FP compares with zero.
2700     Op1 = DAG.getConstantFP(0, MVT::f32);
2701     Opcode = AArch64ISD::NEON_CMPZ;
2702   } else {
2703     // Attempt to use Vector Floating Point Compare Mask instruction.
2704     Op0 = LHS;
2705     Op1 = RHS;
2706     Opcode = AArch64ISD::NEON_CMP;
2707   }
2708
2709   SDValue NeonCmpAlt;
2710   // Some register compares have to be implemented with swapped CC and operands,
2711   // e.g.: OLT implemented as OGT with swapped operands.
2712   bool SwapIfRegArgs = false;
2713
2714   // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2715   // EQ, GE, GT, LE, LT.
2716   // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2717   switch (CC) {
2718   default:
2719     llvm_unreachable("Illegal FP comparison");
2720   case ISD::SETUNE:
2721   case ISD::SETNE:
2722     Invert = true; // Fallthrough
2723   case ISD::SETOEQ:
2724   case ISD::SETEQ:
2725     CC = ISD::SETEQ;
2726     break;
2727   case ISD::SETOLT:
2728   case ISD::SETLT:
2729     CC = ISD::SETLT;
2730     SwapIfRegArgs = true;
2731     break;
2732   case ISD::SETOGT:
2733   case ISD::SETGT:
2734     CC = ISD::SETGT;
2735     break;
2736   case ISD::SETOLE:
2737   case ISD::SETLE:
2738     CC = ISD::SETLE;
2739     SwapIfRegArgs = true;
2740     break;
2741   case ISD::SETOGE:
2742   case ISD::SETGE:
2743     CC = ISD::SETGE;
2744     break;
2745   case ISD::SETUGE:
2746     Invert = true;
2747     CC = ISD::SETLT;
2748     SwapIfRegArgs = true;
2749     break;
2750   case ISD::SETULE:
2751     Invert = true;
2752     CC = ISD::SETGT;
2753     break;
2754   case ISD::SETUGT:
2755     Invert = true;
2756     CC = ISD::SETLE;
2757     SwapIfRegArgs = true;
2758     break;
2759   case ISD::SETULT:
2760     Invert = true;
2761     CC = ISD::SETGE;
2762     break;
2763   case ISD::SETUEQ:
2764     Invert = true; // Fallthrough
2765   case ISD::SETONE:
2766     // Expand this to (OGT |OLT).
2767     NeonCmpAlt =
2768         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2769     CC = ISD::SETLT;
2770     SwapIfRegArgs = true;
2771     break;
2772   case ISD::SETUO:
2773     Invert = true; // Fallthrough
2774   case ISD::SETO:
2775     // Expand this to (OGE | OLT).
2776     NeonCmpAlt =
2777         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2778     CC = ISD::SETLT;
2779     SwapIfRegArgs = true;
2780     break;
2781   }
2782
2783   if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2784     CC = getSetCCSwappedOperands(CC);
2785     std::swap(Op0, Op1);
2786   }
2787
2788   // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2789   SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2790
2791   if (NeonCmpAlt.getNode())
2792     NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2793
2794   if (Invert)
2795     NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2796
2797   return NeonCmp;
2798 }
2799
2800 // (SETCC lhs, rhs, condcode)
2801 SDValue
2802 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2803   SDLoc dl(Op);
2804   SDValue LHS = Op.getOperand(0);
2805   SDValue RHS = Op.getOperand(1);
2806   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2807   EVT VT = Op.getValueType();
2808
2809   if (VT.isVector())
2810     return LowerVectorSETCC(Op, DAG);
2811
2812   if (LHS.getValueType() == MVT::f128) {
2813     // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2814     // for the rest of the function (some i32 or i64 values).
2815     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2816
2817     // If softenSetCCOperands returned a scalar, use it.
2818     if (RHS.getNode() == 0) {
2819       assert(LHS.getValueType() == Op.getValueType() &&
2820              "Unexpected setcc expansion!");
2821       return LHS;
2822     }
2823   }
2824
2825   if (LHS.getValueType().isInteger()) {
2826     SDValue A64cc;
2827
2828     // Integers are handled in a separate function because the combinations of
2829     // immediates and tests can get hairy and we may want to fiddle things.
2830     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2831
2832     return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2833                        CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2834                        A64cc);
2835   }
2836
2837   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2838   // conditional branch, hence FPCCToA64CC can set a second test, where either
2839   // passing is sufficient.
2840   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2841   CondCode = FPCCToA64CC(CC, Alternative);
2842   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2843   SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2844                               DAG.getCondCode(CC));
2845   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2846                                      CmpOp, DAG.getConstant(1, VT),
2847                                      DAG.getConstant(0, VT), A64cc);
2848
2849   if (Alternative != A64CC::Invalid) {
2850     A64cc = DAG.getConstant(Alternative, MVT::i32);
2851     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
2852                                DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
2853   }
2854
2855   return A64SELECT_CC;
2856 }
2857
2858 SDValue
2859 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2860   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2861   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2862
2863   // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
2864   // rather than just 8.
2865   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
2866                        Op.getOperand(1), Op.getOperand(2),
2867                        DAG.getConstant(32, MVT::i32), 8, false, false,
2868                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
2869 }
2870
2871 SDValue
2872 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2873   // The layout of the va_list struct is specified in the AArch64 Procedure Call
2874   // Standard, section B.3.
2875   MachineFunction &MF = DAG.getMachineFunction();
2876   AArch64MachineFunctionInfo *FuncInfo
2877     = MF.getInfo<AArch64MachineFunctionInfo>();
2878   SDLoc DL(Op);
2879
2880   SDValue Chain = Op.getOperand(0);
2881   SDValue VAList = Op.getOperand(1);
2882   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2883   SmallVector<SDValue, 4> MemOps;
2884
2885   // void *__stack at offset 0
2886   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
2887                                     getPointerTy());
2888   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
2889                                 MachinePointerInfo(SV), false, false, 0));
2890
2891   // void *__gr_top at offset 8
2892   int GPRSize = FuncInfo->getVariadicGPRSize();
2893   if (GPRSize > 0) {
2894     SDValue GRTop, GRTopAddr;
2895
2896     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2897                             DAG.getConstant(8, getPointerTy()));
2898
2899     GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
2900     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
2901                         DAG.getConstant(GPRSize, getPointerTy()));
2902
2903     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
2904                                   MachinePointerInfo(SV, 8),
2905                                   false, false, 0));
2906   }
2907
2908   // void *__vr_top at offset 16
2909   int FPRSize = FuncInfo->getVariadicFPRSize();
2910   if (FPRSize > 0) {
2911     SDValue VRTop, VRTopAddr;
2912     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2913                             DAG.getConstant(16, getPointerTy()));
2914
2915     VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
2916     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
2917                         DAG.getConstant(FPRSize, getPointerTy()));
2918
2919     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
2920                                   MachinePointerInfo(SV, 16),
2921                                   false, false, 0));
2922   }
2923
2924   // int __gr_offs at offset 24
2925   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2926                                    DAG.getConstant(24, getPointerTy()));
2927   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
2928                                 GROffsAddr, MachinePointerInfo(SV, 24),
2929                                 false, false, 0));
2930
2931   // int __vr_offs at offset 28
2932   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2933                                    DAG.getConstant(28, getPointerTy()));
2934   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
2935                                 VROffsAddr, MachinePointerInfo(SV, 28),
2936                                 false, false, 0));
2937
2938   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2939                      MemOps.size());
2940 }
2941
2942 SDValue
2943 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2944   switch (Op.getOpcode()) {
2945   default: llvm_unreachable("Don't know how to custom lower this!");
2946   case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
2947   case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
2948   case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
2949   case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
2950   case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
2951   case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
2952   case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
2953   case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
2954   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
2955   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
2956   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
2957   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2958
2959   case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
2960   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2961   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
2962   case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
2963   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
2964   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
2965   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
2966   case ISD::SELECT: return LowerSELECT(Op, DAG);
2967   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
2968   case ISD::SETCC: return LowerSETCC(Op, DAG);
2969   case ISD::VACOPY: return LowerVACOPY(Op, DAG);
2970   case ISD::VASTART: return LowerVASTART(Op, DAG);
2971   case ISD::BUILD_VECTOR:
2972     return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
2973   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2974   }
2975
2976   return SDValue();
2977 }
2978
2979 /// Check if the specified splat value corresponds to a valid vector constant
2980 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI).  If
2981 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
2982 /// values.
2983 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2984                               unsigned SplatBitSize, SelectionDAG &DAG,
2985                               bool is128Bits, NeonModImmType type, EVT &VT,
2986                               unsigned &Imm, unsigned &OpCmode) {
2987   switch (SplatBitSize) {
2988   default:
2989     llvm_unreachable("unexpected size for isNeonModifiedImm");
2990   case 8: {
2991     if (type != Neon_Mov_Imm)
2992       return false;
2993     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2994     // Neon movi per byte: Op=0, Cmode=1110.
2995     OpCmode = 0xe;
2996     Imm = SplatBits;
2997     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
2998     break;
2999   }
3000   case 16: {
3001     // Neon move inst per halfword
3002     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3003     if ((SplatBits & ~0xff) == 0) {
3004       // Value = 0x00nn is 0x00nn LSL 0
3005       // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
3006       // bic:  Op=1, Cmode=1001;  orr:  Op=0, Cmode=1001
3007       // Op=x, Cmode=100y
3008       Imm = SplatBits;
3009       OpCmode = 0x8;
3010       break;
3011     }
3012     if ((SplatBits & ~0xff00) == 0) {
3013       // Value = 0xnn00 is 0x00nn LSL 8
3014       // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
3015       // bic:  Op=1, Cmode=1011;  orr:  Op=0, Cmode=1011
3016       // Op=x, Cmode=101x
3017       Imm = SplatBits >> 8;
3018       OpCmode = 0xa;
3019       break;
3020     }
3021     // can't handle any other
3022     return false;
3023   }
3024
3025   case 32: {
3026     // First the LSL variants (MSL is unusable by some interested instructions).
3027
3028     // Neon move instr per word, shift zeros
3029     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3030     if ((SplatBits & ~0xff) == 0) {
3031       // Value = 0x000000nn is 0x000000nn LSL 0
3032       // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
3033       // bic:  Op=1, Cmode= 0001; orr:  Op=0, Cmode= 0001
3034       // Op=x, Cmode=000x
3035       Imm = SplatBits;
3036       OpCmode = 0;
3037       break;
3038     }
3039     if ((SplatBits & ~0xff00) == 0) {
3040       // Value = 0x0000nn00 is 0x000000nn LSL 8
3041       // movi: Op=0, Cmode= 0010;  mvni: Op=1, Cmode= 0010
3042       // bic:  Op=1, Cmode= 0011;  orr : Op=0, Cmode= 0011
3043       // Op=x, Cmode=001x
3044       Imm = SplatBits >> 8;
3045       OpCmode = 0x2;
3046       break;
3047     }
3048     if ((SplatBits & ~0xff0000) == 0) {
3049       // Value = 0x00nn0000 is 0x000000nn LSL 16
3050       // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
3051       // bic:  Op=1, Cmode= 0101; orr:  Op=0, Cmode= 0101
3052       // Op=x, Cmode=010x
3053       Imm = SplatBits >> 16;
3054       OpCmode = 0x4;
3055       break;
3056     }
3057     if ((SplatBits & ~0xff000000) == 0) {
3058       // Value = 0xnn000000 is 0x000000nn LSL 24
3059       // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
3060       // bic:  Op=1, Cmode= 0111; orr:  Op=0, Cmode= 0111
3061       // Op=x, Cmode=011x
3062       Imm = SplatBits >> 24;
3063       OpCmode = 0x6;
3064       break;
3065     }
3066
3067     // Now the MSL immediates.
3068
3069     // Neon move instr per word, shift ones
3070     if ((SplatBits & ~0xffff) == 0 &&
3071         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3072       // Value = 0x0000nnff is 0x000000nn MSL 8
3073       // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
3074       // Op=x, Cmode=1100
3075       Imm = SplatBits >> 8;
3076       OpCmode = 0xc;
3077       break;
3078     }
3079     if ((SplatBits & ~0xffffff) == 0 &&
3080         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3081       // Value = 0x00nnffff is 0x000000nn MSL 16
3082       // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
3083       // Op=x, Cmode=1101
3084       Imm = SplatBits >> 16;
3085       OpCmode = 0xd;
3086       break;
3087     }
3088     // can't handle any other
3089     return false;
3090   }
3091
3092   case 64: {
3093     if (type != Neon_Mov_Imm)
3094       return false;
3095     // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
3096     // movi Op=1, Cmode=1110.
3097     OpCmode = 0x1e;
3098     uint64_t BitMask = 0xff;
3099     uint64_t Val = 0;
3100     unsigned ImmMask = 1;
3101     Imm = 0;
3102     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3103       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3104         Val |= BitMask;
3105         Imm |= ImmMask;
3106       } else if ((SplatBits & BitMask) != 0) {
3107         return false;
3108       }
3109       BitMask <<= 8;
3110       ImmMask <<= 1;
3111     }
3112     SplatBits = Val;
3113     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3114     break;
3115   }
3116   }
3117
3118   return true;
3119 }
3120
3121 static SDValue PerformANDCombine(SDNode *N,
3122                                  TargetLowering::DAGCombinerInfo &DCI) {
3123
3124   SelectionDAG &DAG = DCI.DAG;
3125   SDLoc DL(N);
3126   EVT VT = N->getValueType(0);
3127
3128   // We're looking for an SRA/SHL pair which form an SBFX.
3129
3130   if (VT != MVT::i32 && VT != MVT::i64)
3131     return SDValue();
3132
3133   if (!isa<ConstantSDNode>(N->getOperand(1)))
3134     return SDValue();
3135
3136   uint64_t TruncMask = N->getConstantOperandVal(1);
3137   if (!isMask_64(TruncMask))
3138     return SDValue();
3139
3140   uint64_t Width = CountPopulation_64(TruncMask);
3141   SDValue Shift = N->getOperand(0);
3142
3143   if (Shift.getOpcode() != ISD::SRL)
3144     return SDValue();
3145
3146   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3147     return SDValue();
3148   uint64_t LSB = Shift->getConstantOperandVal(1);
3149
3150   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3151     return SDValue();
3152
3153   return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
3154                      DAG.getConstant(LSB, MVT::i64),
3155                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3156 }
3157
3158 /// For a true bitfield insert, the bits getting into that contiguous mask
3159 /// should come from the low part of an existing value: they must be formed from
3160 /// a compatible SHL operation (unless they're already low). This function
3161 /// checks that condition and returns the least-significant bit that's
3162 /// intended. If the operation not a field preparation, -1 is returned.
3163 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
3164                             SDValue &MaskedVal, uint64_t Mask) {
3165   if (!isShiftedMask_64(Mask))
3166     return -1;
3167
3168   // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
3169   // instruction. BFI will do a left-shift by LSB before applying the mask we've
3170   // spotted, so in general we should pre-emptively "undo" that by making sure
3171   // the incoming bits have had a right-shift applied to them.
3172   //
3173   // This right shift, however, will combine with existing left/right shifts. In
3174   // the simplest case of a completely straight bitfield operation, it will be
3175   // expected to completely cancel out with an existing SHL. More complicated
3176   // cases (e.g. bitfield to bitfield copy) may still need a real shift before
3177   // the BFI.
3178
3179   uint64_t LSB = countTrailingZeros(Mask);
3180   int64_t ShiftRightRequired = LSB;
3181   if (MaskedVal.getOpcode() == ISD::SHL &&
3182       isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3183     ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
3184     MaskedVal = MaskedVal.getOperand(0);
3185   } else if (MaskedVal.getOpcode() == ISD::SRL &&
3186              isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3187     ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
3188     MaskedVal = MaskedVal.getOperand(0);
3189   }
3190
3191   if (ShiftRightRequired > 0)
3192     MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
3193                             DAG.getConstant(ShiftRightRequired, MVT::i64));
3194   else if (ShiftRightRequired < 0) {
3195     // We could actually end up with a residual left shift, for example with
3196     // "struc.bitfield = val << 1".
3197     MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
3198                             DAG.getConstant(-ShiftRightRequired, MVT::i64));
3199   }
3200
3201   return LSB;
3202 }
3203
3204 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
3205 /// a mask and an extension. Returns true if a BFI was found and provides
3206 /// information on its surroundings.
3207 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
3208                           bool &Extended) {
3209   Extended = false;
3210   if (N.getOpcode() == ISD::ZERO_EXTEND) {
3211     Extended = true;
3212     N = N.getOperand(0);
3213   }
3214
3215   if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
3216     Mask = N->getConstantOperandVal(1);
3217     N = N.getOperand(0);
3218   } else {
3219     // Mask is the whole width.
3220     Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
3221   }
3222
3223   if (N.getOpcode() == AArch64ISD::BFI) {
3224     BFI = N;
3225     return true;
3226   }
3227
3228   return false;
3229 }
3230
3231 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
3232 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
3233 /// can often be further combined with a larger mask. Ultimately, we want mask
3234 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
3235 static SDValue tryCombineToBFI(SDNode *N,
3236                                TargetLowering::DAGCombinerInfo &DCI,
3237                                const AArch64Subtarget *Subtarget) {
3238   SelectionDAG &DAG = DCI.DAG;
3239   SDLoc DL(N);
3240   EVT VT = N->getValueType(0);
3241
3242   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3243
3244   // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
3245   // abandon the effort.
3246   SDValue LHS = N->getOperand(0);
3247   if (LHS.getOpcode() != ISD::AND)
3248     return SDValue();
3249
3250   uint64_t LHSMask;
3251   if (isa<ConstantSDNode>(LHS.getOperand(1)))
3252     LHSMask = LHS->getConstantOperandVal(1);
3253   else
3254     return SDValue();
3255
3256   // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
3257   // is or abandon the effort.
3258   SDValue RHS = N->getOperand(1);
3259   if (RHS.getOpcode() != ISD::AND)
3260     return SDValue();
3261
3262   uint64_t RHSMask;
3263   if (isa<ConstantSDNode>(RHS.getOperand(1)))
3264     RHSMask = RHS->getConstantOperandVal(1);
3265   else
3266     return SDValue();
3267
3268   // Can't do anything if the masks are incompatible.
3269   if (LHSMask & RHSMask)
3270     return SDValue();
3271
3272   // Now we need one of the masks to be a contiguous field. Without loss of
3273   // generality that should be the RHS one.
3274   SDValue Bitfield = LHS.getOperand(0);
3275   if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3276     // We know that LHS is a candidate new value, and RHS isn't already a better
3277     // one.
3278     std::swap(LHS, RHS);
3279     std::swap(LHSMask, RHSMask);
3280   }
3281
3282   // We've done our best to put the right operands in the right places, all we
3283   // can do now is check whether a BFI exists.
3284   Bitfield = RHS.getOperand(0);
3285   int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3286   if (LSB == -1)
3287     return SDValue();
3288
3289   uint32_t Width = CountPopulation_64(RHSMask);
3290   assert(Width && "Expected non-zero bitfield width");
3291
3292   SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3293                             LHS.getOperand(0), Bitfield,
3294                             DAG.getConstant(LSB, MVT::i64),
3295                             DAG.getConstant(Width, MVT::i64));
3296
3297   // Mask is trivial
3298   if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3299     return BFI;
3300
3301   return DAG.getNode(ISD::AND, DL, VT, BFI,
3302                      DAG.getConstant(LHSMask | RHSMask, VT));
3303 }
3304
3305 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3306 /// original input. This is surprisingly common because SROA splits things up
3307 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3308 /// on the low (say) byte of a word. This is then orred into the rest of the
3309 /// word afterwards.
3310 ///
3311 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3312 ///
3313 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3314 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3315 /// involved.
3316 static SDValue tryCombineToLargerBFI(SDNode *N,
3317                                      TargetLowering::DAGCombinerInfo &DCI,
3318                                      const AArch64Subtarget *Subtarget) {
3319   SelectionDAG &DAG = DCI.DAG;
3320   SDLoc DL(N);
3321   EVT VT = N->getValueType(0);
3322
3323   // First job is to hunt for a MaskedBFI on either the left or right. Swap
3324   // operands if it's actually on the right.
3325   SDValue BFI;
3326   SDValue PossExtraMask;
3327   uint64_t ExistingMask = 0;
3328   bool Extended = false;
3329   if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3330     PossExtraMask = N->getOperand(1);
3331   else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3332     PossExtraMask = N->getOperand(0);
3333   else
3334     return SDValue();
3335
3336   // We can only combine a BFI with another compatible mask.
3337   if (PossExtraMask.getOpcode() != ISD::AND ||
3338       !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3339     return SDValue();
3340
3341   uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3342
3343   // Masks must be compatible.
3344   if (ExtraMask & ExistingMask)
3345     return SDValue();
3346
3347   SDValue OldBFIVal = BFI.getOperand(0);
3348   SDValue NewBFIVal = BFI.getOperand(1);
3349   if (Extended) {
3350     // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3351     // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3352     // need to be made compatible.
3353     assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3354            && "Invalid types for BFI");
3355     OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3356     NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3357   }
3358
3359   // We need the MaskedBFI to be combined with a mask of the *same* value.
3360   if (PossExtraMask.getOperand(0) != OldBFIVal)
3361     return SDValue();
3362
3363   BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3364                     OldBFIVal, NewBFIVal,
3365                     BFI.getOperand(2), BFI.getOperand(3));
3366
3367   // If the masking is trivial, we don't need to create it.
3368   if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3369     return BFI;
3370
3371   return DAG.getNode(ISD::AND, DL, VT, BFI,
3372                      DAG.getConstant(ExtraMask | ExistingMask, VT));
3373 }
3374
3375 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3376 /// searches for and classifies those shifts.
3377 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3378                          bool &FromHi) {
3379   if (N.getOpcode() == ISD::SHL)
3380     FromHi = false;
3381   else if (N.getOpcode() == ISD::SRL)
3382     FromHi = true;
3383   else
3384     return false;
3385
3386   if (!isa<ConstantSDNode>(N.getOperand(1)))
3387     return false;
3388
3389   ShiftAmount = N->getConstantOperandVal(1);
3390   Src = N->getOperand(0);
3391   return true;
3392 }
3393
3394 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3395 /// registers viewed as a high/low pair. This function looks for the pattern:
3396 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3397 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3398 /// independent.
3399 static SDValue tryCombineToEXTR(SDNode *N,
3400                                 TargetLowering::DAGCombinerInfo &DCI) {
3401   SelectionDAG &DAG = DCI.DAG;
3402   SDLoc DL(N);
3403   EVT VT = N->getValueType(0);
3404
3405   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3406
3407   if (VT != MVT::i32 && VT != MVT::i64)
3408     return SDValue();
3409
3410   SDValue LHS;
3411   uint32_t ShiftLHS = 0;
3412   bool LHSFromHi = 0;
3413   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3414     return SDValue();
3415
3416   SDValue RHS;
3417   uint32_t ShiftRHS = 0;
3418   bool RHSFromHi = 0;
3419   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3420     return SDValue();
3421
3422   // If they're both trying to come from the high part of the register, they're
3423   // not really an EXTR.
3424   if (LHSFromHi == RHSFromHi)
3425     return SDValue();
3426
3427   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3428     return SDValue();
3429
3430   if (LHSFromHi) {
3431     std::swap(LHS, RHS);
3432     std::swap(ShiftLHS, ShiftRHS);
3433   }
3434
3435   return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3436                      LHS, RHS,
3437                      DAG.getConstant(ShiftRHS, MVT::i64));
3438 }
3439
3440 /// Target-specific dag combine xforms for ISD::OR
3441 static SDValue PerformORCombine(SDNode *N,
3442                                 TargetLowering::DAGCombinerInfo &DCI,
3443                                 const AArch64Subtarget *Subtarget) {
3444
3445   SelectionDAG &DAG = DCI.DAG;
3446   SDLoc DL(N);
3447   EVT VT = N->getValueType(0);
3448
3449   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3450     return SDValue();
3451
3452   // Attempt to recognise bitfield-insert operations.
3453   SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3454   if (Res.getNode())
3455     return Res;
3456
3457   // Attempt to combine an existing MaskedBFI operation into one with a larger
3458   // mask.
3459   Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3460   if (Res.getNode())
3461     return Res;
3462
3463   Res = tryCombineToEXTR(N, DCI);
3464   if (Res.getNode())
3465     return Res;
3466
3467   if (!Subtarget->hasNEON())
3468     return SDValue();
3469
3470   // Attempt to use vector immediate-form BSL
3471   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3472
3473   SDValue N0 = N->getOperand(0);
3474   if (N0.getOpcode() != ISD::AND)
3475     return SDValue();
3476
3477   SDValue N1 = N->getOperand(1);
3478   if (N1.getOpcode() != ISD::AND)
3479     return SDValue();
3480
3481   if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3482     APInt SplatUndef;
3483     unsigned SplatBitSize;
3484     bool HasAnyUndefs;
3485     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3486     APInt SplatBits0;
3487     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3488                                       HasAnyUndefs) &&
3489         !HasAnyUndefs) {
3490       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3491       APInt SplatBits1;
3492       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3493                                         HasAnyUndefs) && !HasAnyUndefs &&
3494           SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
3495           SplatBits0 == ~SplatBits1) {
3496
3497         return DAG.getNode(ISD::VSELECT, DL, VT, N0->getOperand(1),
3498                            N0->getOperand(0), N1->getOperand(0));
3499       }
3500     }
3501   }
3502
3503   return SDValue();
3504 }
3505
3506 /// Target-specific dag combine xforms for ISD::SRA
3507 static SDValue PerformSRACombine(SDNode *N,
3508                                  TargetLowering::DAGCombinerInfo &DCI) {
3509
3510   SelectionDAG &DAG = DCI.DAG;
3511   SDLoc DL(N);
3512   EVT VT = N->getValueType(0);
3513
3514   // We're looking for an SRA/SHL pair which form an SBFX.
3515
3516   if (VT != MVT::i32 && VT != MVT::i64)
3517     return SDValue();
3518
3519   if (!isa<ConstantSDNode>(N->getOperand(1)))
3520     return SDValue();
3521
3522   uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3523   SDValue Shift = N->getOperand(0);
3524
3525   if (Shift.getOpcode() != ISD::SHL)
3526     return SDValue();
3527
3528   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3529     return SDValue();
3530
3531   uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3532   uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3533   uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3534
3535   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3536     return SDValue();
3537
3538   return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3539                      DAG.getConstant(LSB, MVT::i64),
3540                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3541 }
3542
3543 /// Check if this is a valid build_vector for the immediate operand of
3544 /// a vector shift operation, where all the elements of the build_vector
3545 /// must have the same constant integer value.
3546 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3547   // Ignore bit_converts.
3548   while (Op.getOpcode() == ISD::BITCAST)
3549     Op = Op.getOperand(0);
3550   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3551   APInt SplatBits, SplatUndef;
3552   unsigned SplatBitSize;
3553   bool HasAnyUndefs;
3554   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3555                                       HasAnyUndefs, ElementBits) ||
3556       SplatBitSize > ElementBits)
3557     return false;
3558   Cnt = SplatBits.getSExtValue();
3559   return true;
3560 }
3561
3562 /// Check if this is a valid build_vector for the immediate operand of
3563 /// a vector shift left operation.  That value must be in the range:
3564 /// 0 <= Value < ElementBits
3565 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3566   assert(VT.isVector() && "vector shift count is not a vector type");
3567   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3568   if (!getVShiftImm(Op, ElementBits, Cnt))
3569     return false;
3570   return (Cnt >= 0 && Cnt < ElementBits);
3571 }
3572
3573 /// Check if this is a valid build_vector for the immediate operand of a
3574 /// vector shift right operation. The value must be in the range:
3575 ///   1 <= Value <= ElementBits
3576 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3577   assert(VT.isVector() && "vector shift count is not a vector type");
3578   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3579   if (!getVShiftImm(Op, ElementBits, Cnt))
3580     return false;
3581   return (Cnt >= 1 && Cnt <= ElementBits);
3582 }
3583
3584 static SDValue GenForSextInreg(SDNode *N,
3585                                TargetLowering::DAGCombinerInfo &DCI,
3586                                EVT SrcVT, EVT DestVT, EVT SubRegVT,
3587                                const int *Mask, SDValue Src) {
3588   SelectionDAG &DAG = DCI.DAG;
3589   SDValue Bitcast
3590     = DAG.getNode(ISD::BITCAST, SDLoc(N), SrcVT, Src);
3591   SDValue Sext
3592     = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), DestVT, Bitcast);
3593   SDValue ShuffleVec
3594     = DAG.getVectorShuffle(DestVT, SDLoc(N), Sext, DAG.getUNDEF(DestVT), Mask);
3595   SDValue ExtractSubreg
3596     = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, SDLoc(N),
3597                 SubRegVT, ShuffleVec,
3598                 DAG.getTargetConstant(AArch64::sub_64, MVT::i32)), 0);
3599   return ExtractSubreg;
3600 }
3601
3602 /// Checks for vector shifts and lowers them.
3603 static SDValue PerformShiftCombine(SDNode *N,
3604                                    TargetLowering::DAGCombinerInfo &DCI,
3605                                    const AArch64Subtarget *ST) {
3606   SelectionDAG &DAG = DCI.DAG;
3607   EVT VT = N->getValueType(0);
3608   if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3609     return PerformSRACombine(N, DCI);
3610
3611   // We're looking for an SRA/SHL pair to help generating instruction
3612   //   sshll  v0.8h, v0.8b, #0
3613   // The instruction STXL is also the alias of this instruction.
3614   //
3615   // For example, for DAG like below,
3616   //   v2i32 = sra (v2i32 (shl v2i32, 16)), 16
3617   // we can transform it into
3618   //   v2i32 = EXTRACT_SUBREG 
3619   //             (v4i32 (suffle_vector
3620   //                       (v4i32 (sext (v4i16 (bitcast v2i32))), 
3621   //                       undef, (0, 2, u, u)),
3622   //             sub_64
3623   //
3624   // With this transformation we expect to generate "SSHLL + UZIP1"
3625   // Sometimes UZIP1 can be optimized away by combining with other context.
3626   int64_t ShrCnt, ShlCnt;
3627   if (N->getOpcode() == ISD::SRA
3628       && (VT == MVT::v2i32 || VT == MVT::v4i16)
3629       && isVShiftRImm(N->getOperand(1), VT, ShrCnt)
3630       && N->getOperand(0).getOpcode() == ISD::SHL
3631       && isVShiftRImm(N->getOperand(0).getOperand(1), VT, ShlCnt)) {
3632     SDValue Src = N->getOperand(0).getOperand(0);
3633     if (VT == MVT::v2i32 && ShrCnt == 16 && ShlCnt == 16) {
3634       // sext_inreg(v2i32, v2i16)
3635       // We essentially only care the Mask {0, 2, u, u}
3636       int Mask[4] = {0, 2, 4, 6};
3637       return GenForSextInreg(N, DCI, MVT::v4i16, MVT::v4i32, MVT::v2i32,
3638                              Mask, Src); 
3639     }
3640     else if (VT == MVT::v2i32 && ShrCnt == 24 && ShlCnt == 24) {
3641       // sext_inreg(v2i16, v2i8)
3642       // We essentially only care the Mask {0, u, 4, u, u, u, u, u, u, u, u, u}
3643       int Mask[8] = {0, 2, 4, 6, 8, 10, 12, 14};
3644       return GenForSextInreg(N, DCI, MVT::v8i8, MVT::v8i16, MVT::v2i32,
3645                              Mask, Src);
3646     }
3647     else if (VT == MVT::v4i16 && ShrCnt == 8 && ShlCnt == 8) {
3648       // sext_inreg(v4i16, v4i8)
3649       // We essentially only care the Mask {0, 2, 4, 6, u, u, u, u, u, u, u, u}
3650       int Mask[8] = {0, 2, 4, 6, 8, 10, 12, 14};
3651       return GenForSextInreg(N, DCI, MVT::v8i8, MVT::v8i16, MVT::v4i16,
3652                              Mask, Src);
3653     }
3654   }
3655
3656   // Nothing to be done for scalar shifts.
3657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3658   if (!VT.isVector() || !TLI.isTypeLegal(VT))
3659     return SDValue();
3660
3661   assert(ST->hasNEON() && "unexpected vector shift");
3662   int64_t Cnt;
3663
3664   switch (N->getOpcode()) {
3665   default:
3666     llvm_unreachable("unexpected shift opcode");
3667
3668   case ISD::SHL:
3669     if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3670       SDValue RHS =
3671           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
3672                       DAG.getConstant(Cnt, MVT::i32));
3673       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3674     }
3675     break;
3676
3677   case ISD::SRA:
3678   case ISD::SRL:
3679     if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
3680       SDValue RHS =
3681           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
3682                       DAG.getConstant(Cnt, MVT::i32));
3683       return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
3684     }
3685     break;
3686   }
3687
3688   return SDValue();
3689 }
3690
3691 /// ARM-specific DAG combining for intrinsics.
3692 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3693   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3694
3695   switch (IntNo) {
3696   default:
3697     // Don't do anything for most intrinsics.
3698     break;
3699
3700   case Intrinsic::arm_neon_vqshifts:
3701   case Intrinsic::arm_neon_vqshiftu:
3702     EVT VT = N->getOperand(1).getValueType();
3703     int64_t Cnt;
3704     if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
3705       break;
3706     unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
3707                              ? AArch64ISD::NEON_QSHLs
3708                              : AArch64ISD::NEON_QSHLu;
3709     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
3710                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3711   }
3712
3713   return SDValue();
3714 }
3715
3716 /// Target-specific DAG combine function for NEON load/store intrinsics
3717 /// to merge base address updates.
3718 static SDValue CombineBaseUpdate(SDNode *N,
3719                                  TargetLowering::DAGCombinerInfo &DCI) {
3720   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
3721     return SDValue();
3722
3723   SelectionDAG &DAG = DCI.DAG;
3724   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
3725                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
3726   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
3727   SDValue Addr = N->getOperand(AddrOpIdx);
3728
3729   // Search for a use of the address operand that is an increment.
3730   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
3731        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
3732     SDNode *User = *UI;
3733     if (User->getOpcode() != ISD::ADD ||
3734         UI.getUse().getResNo() != Addr.getResNo())
3735       continue;
3736
3737     // Check that the add is independent of the load/store.  Otherwise, folding
3738     // it would create a cycle.
3739     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
3740       continue;
3741
3742     // Find the new opcode for the updating load/store.
3743     bool isLoad = true;
3744     bool isLaneOp = false;
3745     unsigned NewOpc = 0;
3746     unsigned NumVecs = 0;
3747     if (isIntrinsic) {
3748       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3749       switch (IntNo) {
3750       default: llvm_unreachable("unexpected intrinsic for Neon base update");
3751       case Intrinsic::arm_neon_vld1:       NewOpc = AArch64ISD::NEON_LD1_UPD;
3752         NumVecs = 1; break;
3753       case Intrinsic::arm_neon_vld2:       NewOpc = AArch64ISD::NEON_LD2_UPD;
3754         NumVecs = 2; break;
3755       case Intrinsic::arm_neon_vld3:       NewOpc = AArch64ISD::NEON_LD3_UPD;
3756         NumVecs = 3; break;
3757       case Intrinsic::arm_neon_vld4:       NewOpc = AArch64ISD::NEON_LD4_UPD;
3758         NumVecs = 4; break;
3759       case Intrinsic::arm_neon_vst1:       NewOpc = AArch64ISD::NEON_ST1_UPD;
3760         NumVecs = 1; isLoad = false; break;
3761       case Intrinsic::arm_neon_vst2:       NewOpc = AArch64ISD::NEON_ST2_UPD;
3762         NumVecs = 2; isLoad = false; break;
3763       case Intrinsic::arm_neon_vst3:       NewOpc = AArch64ISD::NEON_ST3_UPD;
3764         NumVecs = 3; isLoad = false; break;
3765       case Intrinsic::arm_neon_vst4:       NewOpc = AArch64ISD::NEON_ST4_UPD;
3766         NumVecs = 4; isLoad = false; break;
3767       case Intrinsic::aarch64_neon_vld1x2: NewOpc = AArch64ISD::NEON_LD1x2_UPD;
3768         NumVecs = 2; break;
3769       case Intrinsic::aarch64_neon_vld1x3: NewOpc = AArch64ISD::NEON_LD1x3_UPD;
3770         NumVecs = 3; break;
3771       case Intrinsic::aarch64_neon_vld1x4: NewOpc = AArch64ISD::NEON_LD1x4_UPD;
3772         NumVecs = 4; break;
3773       case Intrinsic::aarch64_neon_vst1x2: NewOpc = AArch64ISD::NEON_ST1x2_UPD;
3774         NumVecs = 2; isLoad = false; break;
3775       case Intrinsic::aarch64_neon_vst1x3: NewOpc = AArch64ISD::NEON_ST1x3_UPD;
3776         NumVecs = 3; isLoad = false; break;
3777       case Intrinsic::aarch64_neon_vst1x4: NewOpc = AArch64ISD::NEON_ST1x4_UPD;
3778         NumVecs = 4; isLoad = false; break;
3779       case Intrinsic::arm_neon_vld2lane:   NewOpc = AArch64ISD::NEON_LD2LN_UPD;
3780         NumVecs = 2; isLaneOp = true; break;
3781       case Intrinsic::arm_neon_vld3lane:   NewOpc = AArch64ISD::NEON_LD3LN_UPD;
3782         NumVecs = 3; isLaneOp = true; break;
3783       case Intrinsic::arm_neon_vld4lane:   NewOpc = AArch64ISD::NEON_LD4LN_UPD;
3784         NumVecs = 4; isLaneOp = true; break;
3785       case Intrinsic::arm_neon_vst2lane:   NewOpc = AArch64ISD::NEON_ST2LN_UPD;
3786         NumVecs = 2; isLoad = false; isLaneOp = true; break;
3787       case Intrinsic::arm_neon_vst3lane:   NewOpc = AArch64ISD::NEON_ST3LN_UPD;
3788         NumVecs = 3; isLoad = false; isLaneOp = true; break;
3789       case Intrinsic::arm_neon_vst4lane:   NewOpc = AArch64ISD::NEON_ST4LN_UPD;
3790         NumVecs = 4; isLoad = false; isLaneOp = true; break;
3791       }
3792     } else {
3793       isLaneOp = true;
3794       switch (N->getOpcode()) {
3795       default: llvm_unreachable("unexpected opcode for Neon base update");
3796       case AArch64ISD::NEON_LD2DUP: NewOpc = AArch64ISD::NEON_LD2DUP_UPD;
3797         NumVecs = 2; break;
3798       case AArch64ISD::NEON_LD3DUP: NewOpc = AArch64ISD::NEON_LD3DUP_UPD;
3799         NumVecs = 3; break;
3800       case AArch64ISD::NEON_LD4DUP: NewOpc = AArch64ISD::NEON_LD4DUP_UPD;
3801         NumVecs = 4; break;
3802       }
3803     }
3804
3805     // Find the size of memory referenced by the load/store.
3806     EVT VecTy;
3807     if (isLoad)
3808       VecTy = N->getValueType(0);
3809     else
3810       VecTy = N->getOperand(AddrOpIdx + 1).getValueType();
3811     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
3812     if (isLaneOp)
3813       NumBytes /= VecTy.getVectorNumElements();
3814
3815     // If the increment is a constant, it must match the memory ref size.
3816     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
3817     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
3818       uint32_t IncVal = CInc->getZExtValue();
3819       if (IncVal != NumBytes)
3820         continue;
3821       Inc = DAG.getTargetConstant(IncVal, MVT::i32);
3822     }
3823
3824     // Create the new updating load/store node.
3825     EVT Tys[6];
3826     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
3827     unsigned n;
3828     for (n = 0; n < NumResultVecs; ++n)
3829       Tys[n] = VecTy;
3830     Tys[n++] = MVT::i64;
3831     Tys[n] = MVT::Other;
3832     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs + 2);
3833     SmallVector<SDValue, 8> Ops;
3834     Ops.push_back(N->getOperand(0)); // incoming chain
3835     Ops.push_back(N->getOperand(AddrOpIdx));
3836     Ops.push_back(Inc);
3837     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
3838       Ops.push_back(N->getOperand(i));
3839     }
3840     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
3841     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
3842                                            Ops.data(), Ops.size(),
3843                                            MemInt->getMemoryVT(),
3844                                            MemInt->getMemOperand());
3845
3846     // Update the uses.
3847     std::vector<SDValue> NewResults;
3848     for (unsigned i = 0; i < NumResultVecs; ++i) {
3849       NewResults.push_back(SDValue(UpdN.getNode(), i));
3850     }
3851     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
3852     DCI.CombineTo(N, NewResults);
3853     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
3854
3855     break;
3856   }
3857   return SDValue();
3858 }
3859
3860 /// For a VDUPLANE node N, check if its source operand is a vldN-lane (N > 1)
3861 /// intrinsic, and if all the other uses of that intrinsic are also VDUPLANEs.
3862 /// If so, combine them to a vldN-dup operation and return true.
3863 static SDValue CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
3864   SelectionDAG &DAG = DCI.DAG;
3865   EVT VT = N->getValueType(0);
3866
3867   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
3868   SDNode *VLD = N->getOperand(0).getNode();
3869   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
3870     return SDValue();
3871   unsigned NumVecs = 0;
3872   unsigned NewOpc = 0;
3873   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
3874   if (IntNo == Intrinsic::arm_neon_vld2lane) {
3875     NumVecs = 2;
3876     NewOpc = AArch64ISD::NEON_LD2DUP;
3877   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
3878     NumVecs = 3;
3879     NewOpc = AArch64ISD::NEON_LD3DUP;
3880   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
3881     NumVecs = 4;
3882     NewOpc = AArch64ISD::NEON_LD4DUP;
3883   } else {
3884     return SDValue();
3885   }
3886
3887   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
3888   // numbers match the load.
3889   unsigned VLDLaneNo =
3890       cast<ConstantSDNode>(VLD->getOperand(NumVecs + 3))->getZExtValue();
3891   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
3892        UI != UE; ++UI) {
3893     // Ignore uses of the chain result.
3894     if (UI.getUse().getResNo() == NumVecs)
3895       continue;
3896     SDNode *User = *UI;
3897     if (User->getOpcode() != AArch64ISD::NEON_VDUPLANE ||
3898         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
3899       return SDValue();
3900   }
3901
3902   // Create the vldN-dup node.
3903   EVT Tys[5];
3904   unsigned n;
3905   for (n = 0; n < NumVecs; ++n)
3906     Tys[n] = VT;
3907   Tys[n] = MVT::Other;
3908   SDVTList SDTys = DAG.getVTList(Tys, NumVecs + 1);
3909   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
3910   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
3911   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, Ops, 2,
3912                                            VLDMemInt->getMemoryVT(),
3913                                            VLDMemInt->getMemOperand());
3914
3915   // Update the uses.
3916   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
3917        UI != UE; ++UI) {
3918     unsigned ResNo = UI.getUse().getResNo();
3919     // Ignore uses of the chain result.
3920     if (ResNo == NumVecs)
3921       continue;
3922     SDNode *User = *UI;
3923     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
3924   }
3925
3926   // Now the vldN-lane intrinsic is dead except for its chain result.
3927   // Update uses of the chain.
3928   std::vector<SDValue> VLDDupResults;
3929   for (unsigned n = 0; n < NumVecs; ++n)
3930     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
3931   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
3932   DCI.CombineTo(VLD, VLDDupResults);
3933
3934   return SDValue(N, 0);
3935 }
3936
3937 SDValue
3938 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
3939                                          DAGCombinerInfo &DCI) const {
3940   switch (N->getOpcode()) {
3941   default: break;
3942   case ISD::AND: return PerformANDCombine(N, DCI);
3943   case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
3944   case ISD::SHL:
3945   case ISD::SRA:
3946   case ISD::SRL:
3947     return PerformShiftCombine(N, DCI, getSubtarget());
3948   case ISD::INTRINSIC_WO_CHAIN:
3949     return PerformIntrinsicCombine(N, DCI.DAG);
3950   case AArch64ISD::NEON_VDUPLANE:
3951     return CombineVLDDUP(N, DCI);
3952   case AArch64ISD::NEON_LD2DUP:
3953   case AArch64ISD::NEON_LD3DUP:
3954   case AArch64ISD::NEON_LD4DUP:
3955     return CombineBaseUpdate(N, DCI);
3956   case ISD::INTRINSIC_VOID:
3957   case ISD::INTRINSIC_W_CHAIN:
3958     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
3959     case Intrinsic::arm_neon_vld1:
3960     case Intrinsic::arm_neon_vld2:
3961     case Intrinsic::arm_neon_vld3:
3962     case Intrinsic::arm_neon_vld4:
3963     case Intrinsic::arm_neon_vst1:
3964     case Intrinsic::arm_neon_vst2:
3965     case Intrinsic::arm_neon_vst3:
3966     case Intrinsic::arm_neon_vst4:
3967     case Intrinsic::arm_neon_vld2lane:
3968     case Intrinsic::arm_neon_vld3lane:
3969     case Intrinsic::arm_neon_vld4lane:
3970     case Intrinsic::aarch64_neon_vld1x2:
3971     case Intrinsic::aarch64_neon_vld1x3:
3972     case Intrinsic::aarch64_neon_vld1x4:
3973     case Intrinsic::aarch64_neon_vst1x2:
3974     case Intrinsic::aarch64_neon_vst1x3:
3975     case Intrinsic::aarch64_neon_vst1x4:
3976     case Intrinsic::arm_neon_vst2lane:
3977     case Intrinsic::arm_neon_vst3lane:
3978     case Intrinsic::arm_neon_vst4lane:
3979       return CombineBaseUpdate(N, DCI);
3980     default:
3981       break;
3982     }
3983   }
3984   return SDValue();
3985 }
3986
3987 bool
3988 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3989   VT = VT.getScalarType();
3990
3991   if (!VT.isSimple())
3992     return false;
3993
3994   switch (VT.getSimpleVT().SimpleTy) {
3995   case MVT::f16:
3996   case MVT::f32:
3997   case MVT::f64:
3998     return true;
3999   case MVT::f128:
4000     return false;
4001   default:
4002     break;
4003   }
4004
4005   return false;
4006 }
4007
4008 // Check whether a Build Vector could be presented as Shuffle Vector. If yes,
4009 // try to call LowerVECTOR_SHUFFLE to lower it.
4010 bool AArch64TargetLowering::isKnownShuffleVector(SDValue Op, SelectionDAG &DAG,
4011                                                  SDValue &Res) const {
4012   SDLoc DL(Op);
4013   EVT VT = Op.getValueType();
4014   unsigned NumElts = VT.getVectorNumElements();
4015   unsigned V0NumElts = 0;
4016   int Mask[16];
4017   SDValue V0, V1;
4018
4019   // Check if all elements are extracted from less than 3 vectors.
4020   for (unsigned i = 0; i < NumElts; ++i) {
4021     SDValue Elt = Op.getOperand(i);
4022     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
4023       return false;
4024
4025     if (V0.getNode() == 0) {
4026       V0 = Elt.getOperand(0);
4027       V0NumElts = V0.getValueType().getVectorNumElements();
4028     }
4029     if (Elt.getOperand(0) == V0) {
4030       Mask[i] = (cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue());
4031       continue;
4032     } else if (V1.getNode() == 0) {
4033       V1 = Elt.getOperand(0);
4034     }
4035     if (Elt.getOperand(0) == V1) {
4036       unsigned Lane = cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue();
4037       Mask[i] = (Lane + V0NumElts);
4038       continue;
4039     } else {
4040       return false;
4041     }
4042   }
4043
4044   if (!V1.getNode() && V0NumElts == NumElts * 2) {
4045     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
4046                      DAG.getConstant(NumElts, MVT::i64));
4047     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
4048                      DAG.getConstant(0, MVT::i64));
4049     V0NumElts = V0.getValueType().getVectorNumElements();
4050   }
4051
4052   if (V1.getNode() && NumElts == V0NumElts &&
4053       V0NumElts == V1.getValueType().getVectorNumElements()) {
4054     SDValue Shuffle = DAG.getVectorShuffle(VT, DL, V0, V1, Mask);
4055     if(Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
4056       Res = Shuffle;
4057     else
4058       Res = LowerVECTOR_SHUFFLE(Shuffle, DAG);
4059     return true;
4060   } else
4061     return false;
4062 }
4063
4064 // If this is a case we can't handle, return null and let the default
4065 // expansion code take care of it.
4066 SDValue
4067 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4068                                          const AArch64Subtarget *ST) const {
4069
4070   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4071   SDLoc DL(Op);
4072   EVT VT = Op.getValueType();
4073
4074   APInt SplatBits, SplatUndef;
4075   unsigned SplatBitSize;
4076   bool HasAnyUndefs;
4077
4078   unsigned UseNeonMov = VT.getSizeInBits() >= 64;
4079
4080   // Note we favor lowering MOVI over MVNI.
4081   // This has implications on the definition of patterns in TableGen to select
4082   // BIC immediate instructions but not ORR immediate instructions.
4083   // If this lowering order is changed, TableGen patterns for BIC immediate and
4084   // ORR immediate instructions have to be updated.
4085   if (UseNeonMov &&
4086       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4087     if (SplatBitSize <= 64) {
4088       // First attempt to use vector immediate-form MOVI
4089       EVT NeonMovVT;
4090       unsigned Imm = 0;
4091       unsigned OpCmode = 0;
4092
4093       if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
4094                             SplatBitSize, DAG, VT.is128BitVector(),
4095                             Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
4096         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4097         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4098
4099         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4100           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
4101                                         ImmVal, OpCmodeVal);
4102           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4103         }
4104       }
4105
4106       // Then attempt to use vector immediate-form MVNI
4107       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4108       if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
4109                             DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
4110                             Imm, OpCmode)) {
4111         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4112         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4113         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4114           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
4115                                         ImmVal, OpCmodeVal);
4116           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4117         }
4118       }
4119
4120       // Attempt to use vector immediate-form FMOV
4121       if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
4122           (VT == MVT::v2f64 && SplatBitSize == 64)) {
4123         APFloat RealVal(
4124             SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
4125             SplatBits);
4126         uint32_t ImmVal;
4127         if (A64Imms::isFPImm(RealVal, ImmVal)) {
4128           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4129           return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
4130         }
4131       }
4132     }
4133   }
4134
4135   unsigned NumElts = VT.getVectorNumElements();
4136   bool isOnlyLowElement = true;
4137   bool usesOnlyOneValue = true;
4138   bool hasDominantValue = false;
4139   bool isConstant = true;
4140
4141   // Map of the number of times a particular SDValue appears in the
4142   // element list.
4143   DenseMap<SDValue, unsigned> ValueCounts;
4144   SDValue Value;
4145   for (unsigned i = 0; i < NumElts; ++i) {
4146     SDValue V = Op.getOperand(i);
4147     if (V.getOpcode() == ISD::UNDEF)
4148       continue;
4149     if (i > 0)
4150       isOnlyLowElement = false;
4151     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4152       isConstant = false;
4153
4154     ValueCounts.insert(std::make_pair(V, 0));
4155     unsigned &Count = ValueCounts[V];
4156
4157     // Is this value dominant? (takes up more than half of the lanes)
4158     if (++Count > (NumElts / 2)) {
4159       hasDominantValue = true;
4160       Value = V;
4161     }
4162   }
4163   if (ValueCounts.size() != 1)
4164     usesOnlyOneValue = false;
4165   if (!Value.getNode() && ValueCounts.size() > 0)
4166     Value = ValueCounts.begin()->first;
4167
4168   if (ValueCounts.size() == 0)
4169     return DAG.getUNDEF(VT);
4170
4171   if (isOnlyLowElement)
4172     return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4173
4174   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4175   if (hasDominantValue && EltSize <= 64) {
4176     // Use VDUP for non-constant splats.
4177     if (!isConstant) {
4178       SDValue N;
4179
4180       // If we are DUPing a value that comes directly from a vector, we could
4181       // just use DUPLANE. We can only do this if the lane being extracted
4182       // is at a constant index, as the DUP from lane instructions only have
4183       // constant-index forms.
4184       //
4185       // If there is a TRUNCATE between EXTRACT_VECTOR_ELT and DUP, we can
4186       // remove TRUNCATE for DUPLANE by apdating the source vector to
4187       // appropriate vector type and lane index.
4188       //
4189       // FIXME: for now we have v1i8, v1i16, v1i32 legal vector types, if they
4190       // are not legal any more, no need to check the type size in bits should
4191       // be large than 64.
4192       SDValue V = Value;
4193       if (Value->getOpcode() == ISD::TRUNCATE)
4194         V = Value->getOperand(0);
4195       if (V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4196           isa<ConstantSDNode>(V->getOperand(1)) &&
4197           V->getOperand(0).getValueType().getSizeInBits() >= 64) {
4198
4199         // If the element size of source vector is larger than DUPLANE
4200         // element size, we can do transformation by,
4201         // 1) bitcasting source register to smaller element vector
4202         // 2) mutiplying the lane index by SrcEltSize/ResEltSize
4203         // For example, we can lower
4204         //     "v8i16 vdup_lane(v4i32, 1)"
4205         // to be
4206         //     "v8i16 vdup_lane(v8i16 bitcast(v4i32), 2)".
4207         SDValue SrcVec = V->getOperand(0);
4208         unsigned SrcEltSize =
4209             SrcVec.getValueType().getVectorElementType().getSizeInBits();
4210         unsigned ResEltSize = VT.getVectorElementType().getSizeInBits();
4211         if (SrcEltSize > ResEltSize) {
4212           assert((SrcEltSize % ResEltSize == 0) && "Invalid element size");
4213           SDValue BitCast;
4214           unsigned SrcSize = SrcVec.getValueType().getSizeInBits();
4215           unsigned ResSize = VT.getSizeInBits();
4216
4217           if (SrcSize > ResSize) {
4218             assert((SrcSize % ResSize == 0) && "Invalid vector size");
4219             EVT CastVT =
4220                 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4221                                  SrcSize / ResEltSize);
4222             BitCast = DAG.getNode(ISD::BITCAST, DL, CastVT, SrcVec);
4223           } else {
4224             assert((SrcSize == ResSize) && "Invalid vector size of source vec");
4225             BitCast = DAG.getNode(ISD::BITCAST, DL, VT, SrcVec);
4226           }
4227
4228           unsigned LaneIdx = V->getConstantOperandVal(1);
4229           SDValue Lane =
4230               DAG.getConstant((SrcEltSize / ResEltSize) * LaneIdx, MVT::i64);
4231           N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT, BitCast, Lane);
4232         } else {
4233           assert((SrcEltSize == ResEltSize) &&
4234                  "Invalid element size of source vec");
4235           N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT, V->getOperand(0),
4236                           V->getOperand(1));
4237         }
4238       } else
4239         N = DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4240
4241       if (!usesOnlyOneValue) {
4242         // The dominant value was splatted as 'N', but we now have to insert
4243         // all differing elements.
4244         for (unsigned I = 0; I < NumElts; ++I) {
4245           if (Op.getOperand(I) == Value)
4246             continue;
4247           SmallVector<SDValue, 3> Ops;
4248           Ops.push_back(N);
4249           Ops.push_back(Op.getOperand(I));
4250           Ops.push_back(DAG.getConstant(I, MVT::i64));
4251           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, &Ops[0], 3);
4252         }
4253       }
4254       return N;
4255     }
4256     if (usesOnlyOneValue && isConstant) {
4257       return DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4258     }
4259   }
4260   // If all elements are constants and the case above didn't get hit, fall back
4261   // to the default expansion, which will generate a load from the constant
4262   // pool.
4263   if (isConstant)
4264     return SDValue();
4265
4266   // Try to lower this in lowering ShuffleVector way.
4267   SDValue Shuf;
4268   if (isKnownShuffleVector(Op, DAG, Shuf))
4269     return Shuf;
4270
4271   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4272   // know the default expansion would otherwise fall back on something even
4273   // worse. For a vector with one or two non-undef values, that's
4274   // scalar_to_vector for the elements followed by a shuffle (provided the
4275   // shuffle is valid for the target) and materialization element by element
4276   // on the stack followed by a load for everything else.
4277   if (!isConstant && !usesOnlyOneValue) {
4278     SDValue Vec = DAG.getUNDEF(VT);
4279     for (unsigned i = 0 ; i < NumElts; ++i) {
4280       SDValue V = Op.getOperand(i);
4281       if (V.getOpcode() == ISD::UNDEF)
4282         continue;
4283       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
4284       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, LaneIdx);
4285     }
4286     return Vec;
4287   }
4288   return SDValue();
4289 }
4290
4291 /// isREVMask - Check if a vector shuffle corresponds to a REV
4292 /// instruction with the specified blocksize.  (The order of the elements
4293 /// within each block of the vector is reversed.)
4294 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4295   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4296          "Only possible block sizes for REV are: 16, 32, 64");
4297
4298   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4299   if (EltSz == 64)
4300     return false;
4301
4302   unsigned NumElts = VT.getVectorNumElements();
4303   unsigned BlockElts = M[0] + 1;
4304   // If the first shuffle index is UNDEF, be optimistic.
4305   if (M[0] < 0)
4306     BlockElts = BlockSize / EltSz;
4307
4308   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4309     return false;
4310
4311   for (unsigned i = 0; i < NumElts; ++i) {
4312     if (M[i] < 0)
4313       continue; // ignore UNDEF indices
4314     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4315       return false;
4316   }
4317
4318   return true;
4319 }
4320
4321 // isPermuteMask - Check whether the vector shuffle matches to UZP, ZIP and
4322 // TRN instruction.
4323 static unsigned isPermuteMask(ArrayRef<int> M, EVT VT, bool isV2undef) {
4324   unsigned NumElts = VT.getVectorNumElements();
4325   if (NumElts < 4)
4326     return 0;
4327
4328   bool ismatch = true;
4329
4330   // Check UZP1
4331   for (unsigned i = 0; i < NumElts; ++i) {
4332     unsigned answer = i * 2;
4333     if (isV2undef && answer >= NumElts)
4334       answer -= NumElts;
4335     if (M[i] != -1 && (unsigned)M[i] != answer) {
4336       ismatch = false;
4337       break;
4338     }
4339   }
4340   if (ismatch)
4341     return AArch64ISD::NEON_UZP1;
4342
4343   // Check UZP2
4344   ismatch = true;
4345   for (unsigned i = 0; i < NumElts; ++i) {
4346     unsigned answer = i * 2 + 1;
4347     if (isV2undef && answer >= NumElts)
4348       answer -= NumElts;
4349     if (M[i] != -1 && (unsigned)M[i] != answer) {
4350       ismatch = false;
4351       break;
4352     }
4353   }
4354   if (ismatch)
4355     return AArch64ISD::NEON_UZP2;
4356
4357   // Check ZIP1
4358   ismatch = true;
4359   for (unsigned i = 0; i < NumElts; ++i) {
4360     unsigned answer = i / 2 + NumElts * (i % 2);
4361     if (isV2undef && answer >= NumElts)
4362       answer -= NumElts;
4363     if (M[i] != -1 && (unsigned)M[i] != answer) {
4364       ismatch = false;
4365       break;
4366     }
4367   }
4368   if (ismatch)
4369     return AArch64ISD::NEON_ZIP1;
4370
4371   // Check ZIP2
4372   ismatch = true;
4373   for (unsigned i = 0; i < NumElts; ++i) {
4374     unsigned answer = (NumElts + i) / 2 + NumElts * (i % 2);
4375     if (isV2undef && answer >= NumElts)
4376       answer -= NumElts;
4377     if (M[i] != -1 && (unsigned)M[i] != answer) {
4378       ismatch = false;
4379       break;
4380     }
4381   }
4382   if (ismatch)
4383     return AArch64ISD::NEON_ZIP2;
4384
4385   // Check TRN1
4386   ismatch = true;
4387   for (unsigned i = 0; i < NumElts; ++i) {
4388     unsigned answer = i + (NumElts - 1) * (i % 2);
4389     if (isV2undef && answer >= NumElts)
4390       answer -= NumElts;
4391     if (M[i] != -1 && (unsigned)M[i] != answer) {
4392       ismatch = false;
4393       break;
4394     }
4395   }
4396   if (ismatch)
4397     return AArch64ISD::NEON_TRN1;
4398
4399   // Check TRN2
4400   ismatch = true;
4401   for (unsigned i = 0; i < NumElts; ++i) {
4402     unsigned answer = 1 + i + (NumElts - 1) * (i % 2);
4403     if (isV2undef && answer >= NumElts)
4404       answer -= NumElts;
4405     if (M[i] != -1 && (unsigned)M[i] != answer) {
4406       ismatch = false;
4407       break;
4408     }
4409   }
4410   if (ismatch)
4411     return AArch64ISD::NEON_TRN2;
4412
4413   return 0;
4414 }
4415
4416 SDValue
4417 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4418                                            SelectionDAG &DAG) const {
4419   SDValue V1 = Op.getOperand(0);
4420   SDValue V2 = Op.getOperand(1);
4421   SDLoc dl(Op);
4422   EVT VT = Op.getValueType();
4423   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4424
4425   // Convert shuffles that are directly supported on NEON to target-specific
4426   // DAG nodes, instead of keeping them as shuffles and matching them again
4427   // during code selection.  This is more efficient and avoids the possibility
4428   // of inconsistencies between legalization and selection.
4429   ArrayRef<int> ShuffleMask = SVN->getMask();
4430
4431   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4432   if (EltSize > 64)
4433     return SDValue();
4434
4435   if (isREVMask(ShuffleMask, VT, 64))
4436     return DAG.getNode(AArch64ISD::NEON_REV64, dl, VT, V1);
4437   if (isREVMask(ShuffleMask, VT, 32))
4438     return DAG.getNode(AArch64ISD::NEON_REV32, dl, VT, V1);
4439   if (isREVMask(ShuffleMask, VT, 16))
4440     return DAG.getNode(AArch64ISD::NEON_REV16, dl, VT, V1);
4441
4442   unsigned ISDNo;
4443   if (V2.getOpcode() == ISD::UNDEF)
4444     ISDNo = isPermuteMask(ShuffleMask, VT, true);
4445   else
4446     ISDNo = isPermuteMask(ShuffleMask, VT, false);
4447
4448   if (ISDNo) {
4449     if (V2.getOpcode() == ISD::UNDEF)
4450       return DAG.getNode(ISDNo, dl, VT, V1, V1);
4451     else
4452       return DAG.getNode(ISDNo, dl, VT, V1, V2);
4453   }
4454
4455   // If the element of shuffle mask are all the same constant, we can
4456   // transform it into either NEON_VDUP or NEON_VDUPLANE
4457   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4458     int Lane = SVN->getSplatIndex();
4459     // If this is undef splat, generate it via "just" vdup, if possible.
4460     if (Lane == -1) Lane = 0;
4461
4462     // Test if V1 is a SCALAR_TO_VECTOR.
4463     if (V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4464       return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT, V1.getOperand(0));
4465     }
4466     // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR.
4467     if (V1.getOpcode() == ISD::BUILD_VECTOR) {
4468       bool IsScalarToVector = true;
4469       for (unsigned i = 0, e = V1.getNumOperands(); i != e; ++i)
4470         if (V1.getOperand(i).getOpcode() != ISD::UNDEF &&
4471             i != (unsigned)Lane) {
4472           IsScalarToVector = false;
4473           break;
4474         }
4475       if (IsScalarToVector)
4476         return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT,
4477                            V1.getOperand(Lane));
4478     }
4479
4480     // Test if V1 is a EXTRACT_SUBVECTOR.
4481     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4482       int ExtLane = cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4483       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1.getOperand(0),
4484                          DAG.getConstant(Lane + ExtLane, MVT::i64));
4485     }
4486     // Test if V1 is a CONCAT_VECTORS.
4487     if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
4488         V1.getOperand(1).getOpcode() == ISD::UNDEF) {
4489       SDValue Op0 = V1.getOperand(0);
4490       assert((unsigned)Lane < Op0.getValueType().getVectorNumElements() &&
4491              "Invalid vector lane access");
4492       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, Op0,
4493                          DAG.getConstant(Lane, MVT::i64));
4494     }
4495
4496     return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
4497                        DAG.getConstant(Lane, MVT::i64));
4498   }
4499
4500   int Length = ShuffleMask.size();
4501   int V1EltNum = V1.getValueType().getVectorNumElements();
4502
4503   // If the number of v1 elements is the same as the number of shuffle mask
4504   // element and the shuffle masks are sequential values, we can transform
4505   // it into NEON_VEXTRACT.
4506   if (V1EltNum == Length) {
4507     // Check if the shuffle mask is sequential.
4508     bool IsSequential = true;
4509     int CurMask = ShuffleMask[0];
4510     for (int I = 0; I < Length; ++I) {
4511       if (ShuffleMask[I] != CurMask) {
4512         IsSequential = false;
4513         break;
4514       }
4515       CurMask++;
4516     }
4517     if (IsSequential) {
4518       assert((EltSize % 8 == 0) && "Bitsize of vector element is incorrect");
4519       unsigned VecSize = EltSize * V1EltNum;
4520       unsigned Index = (EltSize/8) * ShuffleMask[0];
4521       if (VecSize == 64 || VecSize == 128)
4522         return DAG.getNode(AArch64ISD::NEON_VEXTRACT, dl, VT, V1, V2,
4523                            DAG.getConstant(Index, MVT::i64));
4524     }
4525   }
4526
4527   // For shuffle mask like "0, 1, 2, 3, 4, 5, 13, 7", try to generate insert
4528   // by element from V2 to V1 .
4529   // If shuffle mask is like "0, 1, 10, 11, 12, 13, 14, 15", V2 would be a
4530   // better choice to be inserted than V1 as less insert needed, so we count
4531   // element to be inserted for both V1 and V2, and select less one as insert
4532   // target.
4533
4534   // Collect elements need to be inserted and their index.
4535   SmallVector<int, 8> NV1Elt;
4536   SmallVector<int, 8> N1Index;
4537   SmallVector<int, 8> NV2Elt;
4538   SmallVector<int, 8> N2Index;
4539   for (int I = 0; I != Length; ++I) {
4540     if (ShuffleMask[I] != I) {
4541       NV1Elt.push_back(ShuffleMask[I]);
4542       N1Index.push_back(I);
4543     }
4544   }
4545   for (int I = 0; I != Length; ++I) {
4546     if (ShuffleMask[I] != (I + V1EltNum)) {
4547       NV2Elt.push_back(ShuffleMask[I]);
4548       N2Index.push_back(I);
4549     }
4550   }
4551
4552   // Decide which to be inserted. If all lanes mismatch, neither V1 nor V2
4553   // will be inserted.
4554   SDValue InsV = V1;
4555   SmallVector<int, 8> InsMasks = NV1Elt;
4556   SmallVector<int, 8> InsIndex = N1Index;
4557   if ((int)NV1Elt.size() != Length || (int)NV2Elt.size() != Length) {
4558     if (NV1Elt.size() > NV2Elt.size()) {
4559       InsV = V2;
4560       InsMasks = NV2Elt;
4561       InsIndex = N2Index;
4562     }
4563   } else {
4564     InsV = DAG.getNode(ISD::UNDEF, dl, VT);
4565   }
4566
4567   for (int I = 0, E = InsMasks.size(); I != E; ++I) {
4568     SDValue ExtV = V1;
4569     int Mask = InsMasks[I];
4570     if (Mask >= V1EltNum) {
4571       ExtV = V2;
4572       Mask -= V1EltNum;
4573     }
4574     // Any value type smaller than i32 is illegal in AArch64, and this lower
4575     // function is called after legalize pass, so we need to legalize
4576     // the result here.
4577     EVT EltVT;
4578     if (VT.getVectorElementType().isFloatingPoint())
4579       EltVT = (EltSize == 64) ? MVT::f64 : MVT::f32;
4580     else
4581       EltVT = (EltSize == 64) ? MVT::i64 : MVT::i32;
4582
4583     if (Mask >= 0) {
4584       ExtV = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ExtV,
4585                          DAG.getConstant(Mask, MVT::i64));
4586       InsV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, InsV, ExtV,
4587                          DAG.getConstant(InsIndex[I], MVT::i64));
4588     }
4589   }
4590   return InsV;
4591 }
4592
4593 AArch64TargetLowering::ConstraintType
4594 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4595   if (Constraint.size() == 1) {
4596     switch (Constraint[0]) {
4597     default: break;
4598     case 'w': // An FP/SIMD vector register
4599       return C_RegisterClass;
4600     case 'I': // Constant that can be used with an ADD instruction
4601     case 'J': // Constant that can be used with a SUB instruction
4602     case 'K': // Constant that can be used with a 32-bit logical instruction
4603     case 'L': // Constant that can be used with a 64-bit logical instruction
4604     case 'M': // Constant that can be used as a 32-bit MOV immediate
4605     case 'N': // Constant that can be used as a 64-bit MOV immediate
4606     case 'Y': // Floating point constant zero
4607     case 'Z': // Integer constant zero
4608       return C_Other;
4609     case 'Q': // A memory reference with base register and no offset
4610       return C_Memory;
4611     case 'S': // A symbolic address
4612       return C_Other;
4613     }
4614   }
4615
4616   // FIXME: Ump, Utf, Usa, Ush
4617   // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
4618   //      whatever they may be
4619   // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
4620   // Usa: An absolute symbolic address
4621   // Ush: The high part (bits 32:12) of a pc-relative symbolic address
4622   assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
4623          && Constraint != "Ush" && "Unimplemented constraints");
4624
4625   return TargetLowering::getConstraintType(Constraint);
4626 }
4627
4628 TargetLowering::ConstraintWeight
4629 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
4630                                                 const char *Constraint) const {
4631
4632   llvm_unreachable("Constraint weight unimplemented");
4633 }
4634
4635 void
4636 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4637                                                     std::string &Constraint,
4638                                                     std::vector<SDValue> &Ops,
4639                                                     SelectionDAG &DAG) const {
4640   SDValue Result(0, 0);
4641
4642   // Only length 1 constraints are C_Other.
4643   if (Constraint.size() != 1) return;
4644
4645   // Only C_Other constraints get lowered like this. That means constants for us
4646   // so return early if there's no hope the constraint can be lowered.
4647
4648   switch(Constraint[0]) {
4649   default: break;
4650   case 'I': case 'J': case 'K': case 'L':
4651   case 'M': case 'N': case 'Z': {
4652     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4653     if (!C)
4654       return;
4655
4656     uint64_t CVal = C->getZExtValue();
4657     uint32_t Bits;
4658
4659     switch (Constraint[0]) {
4660     default:
4661       // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
4662       // is a peculiarly useless SUB constraint.
4663       llvm_unreachable("Unimplemented C_Other constraint");
4664     case 'I':
4665       if (CVal <= 0xfff)
4666         break;
4667       return;
4668     case 'K':
4669       if (A64Imms::isLogicalImm(32, CVal, Bits))
4670         break;
4671       return;
4672     case 'L':
4673       if (A64Imms::isLogicalImm(64, CVal, Bits))
4674         break;
4675       return;
4676     case 'Z':
4677       if (CVal == 0)
4678         break;
4679       return;
4680     }
4681
4682     Result = DAG.getTargetConstant(CVal, Op.getValueType());
4683     break;
4684   }
4685   case 'S': {
4686     // An absolute symbolic address or label reference.
4687     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4688       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4689                                           GA->getValueType(0));
4690     } else if (const BlockAddressSDNode *BA
4691                  = dyn_cast<BlockAddressSDNode>(Op)) {
4692       Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
4693                                          BA->getValueType(0));
4694     } else if (const ExternalSymbolSDNode *ES
4695                  = dyn_cast<ExternalSymbolSDNode>(Op)) {
4696       Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
4697                                            ES->getValueType(0));
4698     } else
4699       return;
4700     break;
4701   }
4702   case 'Y':
4703     if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
4704       if (CFP->isExactlyValue(0.0)) {
4705         Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
4706         break;
4707       }
4708     }
4709     return;
4710   }
4711
4712   if (Result.getNode()) {
4713     Ops.push_back(Result);
4714     return;
4715   }
4716
4717   // It's an unknown constraint for us. Let generic code have a go.
4718   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4719 }
4720
4721 std::pair<unsigned, const TargetRegisterClass*>
4722 AArch64TargetLowering::getRegForInlineAsmConstraint(
4723                                                   const std::string &Constraint,
4724                                                   MVT VT) const {
4725   if (Constraint.size() == 1) {
4726     switch (Constraint[0]) {
4727     case 'r':
4728       if (VT.getSizeInBits() <= 32)
4729         return std::make_pair(0U, &AArch64::GPR32RegClass);
4730       else if (VT == MVT::i64)
4731         return std::make_pair(0U, &AArch64::GPR64RegClass);
4732       break;
4733     case 'w':
4734       if (VT == MVT::f16)
4735         return std::make_pair(0U, &AArch64::FPR16RegClass);
4736       else if (VT == MVT::f32)
4737         return std::make_pair(0U, &AArch64::FPR32RegClass);
4738       else if (VT.getSizeInBits() == 64)
4739         return std::make_pair(0U, &AArch64::FPR64RegClass);
4740       else if (VT.getSizeInBits() == 128)
4741         return std::make_pair(0U, &AArch64::FPR128RegClass);
4742       break;
4743     }
4744   }
4745
4746   // Use the default implementation in TargetLowering to convert the register
4747   // constraint into a member of a register class.
4748   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4749 }
4750
4751 /// Represent NEON load and store intrinsics as MemIntrinsicNodes.
4752 /// The associated MachineMemOperands record the alignment specified
4753 /// in the intrinsic calls.
4754 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4755                                                const CallInst &I,
4756                                                unsigned Intrinsic) const {
4757   switch (Intrinsic) {
4758   case Intrinsic::arm_neon_vld1:
4759   case Intrinsic::arm_neon_vld2:
4760   case Intrinsic::arm_neon_vld3:
4761   case Intrinsic::arm_neon_vld4:
4762   case Intrinsic::aarch64_neon_vld1x2:
4763   case Intrinsic::aarch64_neon_vld1x3:
4764   case Intrinsic::aarch64_neon_vld1x4:
4765   case Intrinsic::arm_neon_vld2lane:
4766   case Intrinsic::arm_neon_vld3lane:
4767   case Intrinsic::arm_neon_vld4lane: {
4768     Info.opc = ISD::INTRINSIC_W_CHAIN;
4769     // Conservatively set memVT to the entire set of vectors loaded.
4770     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
4771     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
4772     Info.ptrVal = I.getArgOperand(0);
4773     Info.offset = 0;
4774     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
4775     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
4776     Info.vol = false; // volatile loads with NEON intrinsics not supported
4777     Info.readMem = true;
4778     Info.writeMem = false;
4779     return true;
4780   }
4781   case Intrinsic::arm_neon_vst1:
4782   case Intrinsic::arm_neon_vst2:
4783   case Intrinsic::arm_neon_vst3:
4784   case Intrinsic::arm_neon_vst4:
4785   case Intrinsic::aarch64_neon_vst1x2:
4786   case Intrinsic::aarch64_neon_vst1x3:
4787   case Intrinsic::aarch64_neon_vst1x4:
4788   case Intrinsic::arm_neon_vst2lane:
4789   case Intrinsic::arm_neon_vst3lane:
4790   case Intrinsic::arm_neon_vst4lane: {
4791     Info.opc = ISD::INTRINSIC_VOID;
4792     // Conservatively set memVT to the entire set of vectors stored.
4793     unsigned NumElts = 0;
4794     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
4795       Type *ArgTy = I.getArgOperand(ArgI)->getType();
4796       if (!ArgTy->isVectorTy())
4797         break;
4798       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
4799     }
4800     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
4801     Info.ptrVal = I.getArgOperand(0);
4802     Info.offset = 0;
4803     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
4804     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
4805     Info.vol = false; // volatile stores with NEON intrinsics not supported
4806     Info.readMem = false;
4807     Info.writeMem = true;
4808     return true;
4809   }
4810   default:
4811     break;
4812   }
4813
4814   return false;
4815 }