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