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