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