548e76e52189ff00aa84f9ef7dd4482b41222607
[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 SDValue
1350 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1351                                  SmallVectorImpl<SDValue> &InVals) const {
1352   SelectionDAG &DAG                     = CLI.DAG;
1353   SDLoc &dl                             = CLI.DL;
1354   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1355   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1356   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1357   SDValue Chain                         = CLI.Chain;
1358   SDValue Callee                        = CLI.Callee;
1359   bool &IsTailCall                      = CLI.IsTailCall;
1360   CallingConv::ID CallConv              = CLI.CallConv;
1361   bool IsVarArg                         = CLI.IsVarArg;
1362
1363   MachineFunction &MF = DAG.getMachineFunction();
1364   AArch64MachineFunctionInfo *FuncInfo
1365     = MF.getInfo<AArch64MachineFunctionInfo>();
1366   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1367   bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1368   bool IsSibCall = false;
1369
1370   if (IsTailCall) {
1371     IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1372                     IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1373                                                    Outs, OutVals, Ins, DAG);
1374
1375     // A sibling call is one where we're under the usual C ABI and not planning
1376     // to change that but can still do a tail call:
1377     if (!TailCallOpt && IsTailCall)
1378       IsSibCall = true;
1379   }
1380
1381   SmallVector<CCValAssign, 16> ArgLocs;
1382   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1383                  getTargetMachine(), ArgLocs, *DAG.getContext());
1384   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1385
1386   // On AArch64 (and all other architectures I'm aware of) the most this has to
1387   // do is adjust the stack pointer.
1388   unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1389   if (IsSibCall) {
1390     // Since we're not changing the ABI to make this a tail call, the memory
1391     // operands are already available in the caller's incoming argument space.
1392     NumBytes = 0;
1393   }
1394
1395   // FPDiff is the byte offset of the call's argument area from the callee's.
1396   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1397   // by this amount for a tail call. In a sibling call it must be 0 because the
1398   // caller will deallocate the entire stack and the callee still expects its
1399   // arguments to begin at SP+0. Completely unused for non-tail calls.
1400   int FPDiff = 0;
1401
1402   if (IsTailCall && !IsSibCall) {
1403     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1404
1405     // FPDiff will be negative if this tail call requires more space than we
1406     // would automatically have in our incoming argument space. Positive if we
1407     // can actually shrink the stack.
1408     FPDiff = NumReusableBytes - NumBytes;
1409
1410     // The stack pointer must be 16-byte aligned at all times it's used for a
1411     // memory operation, which in practice means at *all* times and in
1412     // particular across call boundaries. Therefore our own arguments started at
1413     // a 16-byte aligned SP and the delta applied for the tail call should
1414     // satisfy the same constraint.
1415     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1416   }
1417
1418   if (!IsSibCall)
1419     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1420                                  dl);
1421
1422   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1423                                         getPointerTy());
1424
1425   SmallVector<SDValue, 8> MemOpChains;
1426   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1427
1428   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1429     CCValAssign &VA = ArgLocs[i];
1430     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1431     SDValue Arg = OutVals[i];
1432
1433     // Callee does the actual widening, so all extensions just use an implicit
1434     // definition of the rest of the Loc. Aesthetically, this would be nicer as
1435     // an ANY_EXTEND, but that isn't valid for floating-point types and this
1436     // alternative works on integer types too.
1437     switch (VA.getLocInfo()) {
1438     default: llvm_unreachable("Unknown loc info!");
1439     case CCValAssign::Full: break;
1440     case CCValAssign::SExt:
1441     case CCValAssign::ZExt:
1442     case CCValAssign::AExt: {
1443       unsigned SrcSize = VA.getValVT().getSizeInBits();
1444       unsigned SrcSubReg;
1445
1446       switch (SrcSize) {
1447       case 8: SrcSubReg = AArch64::sub_8; break;
1448       case 16: SrcSubReg = AArch64::sub_16; break;
1449       case 32: SrcSubReg = AArch64::sub_32; break;
1450       case 64: SrcSubReg = AArch64::sub_64; break;
1451       default: llvm_unreachable("Unexpected argument promotion");
1452       }
1453
1454       Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1455                                     VA.getLocVT(),
1456                                     DAG.getUNDEF(VA.getLocVT()),
1457                                     Arg,
1458                                     DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1459                     0);
1460
1461       break;
1462     }
1463     case CCValAssign::BCvt:
1464       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1465       break;
1466     }
1467
1468     if (VA.isRegLoc()) {
1469       // A normal register (sub-) argument. For now we just note it down because
1470       // we want to copy things into registers as late as possible to avoid
1471       // register-pressure (and possibly worse).
1472       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1473       continue;
1474     }
1475
1476     assert(VA.isMemLoc() && "unexpected argument location");
1477
1478     SDValue DstAddr;
1479     MachinePointerInfo DstInfo;
1480     if (IsTailCall) {
1481       uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1482                                           VA.getLocVT().getSizeInBits();
1483       OpSize = (OpSize + 7) / 8;
1484       int32_t Offset = VA.getLocMemOffset() + FPDiff;
1485       int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1486
1487       DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1488       DstInfo = MachinePointerInfo::getFixedStack(FI);
1489
1490       // Make sure any stack arguments overlapping with where we're storing are
1491       // loaded before this eventual operation. Otherwise they'll be clobbered.
1492       Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1493     } else {
1494       SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1495
1496       DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1497       DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1498     }
1499
1500     if (Flags.isByVal()) {
1501       SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1502       SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1503                                   Flags.getByValAlign(),
1504                                   /*isVolatile = */ false,
1505                                   /*alwaysInline = */ false,
1506                                   DstInfo, MachinePointerInfo(0));
1507       MemOpChains.push_back(Cpy);
1508     } else {
1509       // Normal stack argument, put it where it's needed.
1510       SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1511                                    false, false, 0);
1512       MemOpChains.push_back(Store);
1513     }
1514   }
1515
1516   // The loads and stores generated above shouldn't clash with each
1517   // other. Combining them with this TokenFactor notes that fact for the rest of
1518   // the backend.
1519   if (!MemOpChains.empty())
1520     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1521                         &MemOpChains[0], MemOpChains.size());
1522
1523   // Most of the rest of the instructions need to be glued together; we don't
1524   // want assignments to actual registers used by a call to be rearranged by a
1525   // well-meaning scheduler.
1526   SDValue InFlag;
1527
1528   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1529     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1530                              RegsToPass[i].second, InFlag);
1531     InFlag = Chain.getValue(1);
1532   }
1533
1534   // The linker is responsible for inserting veneers when necessary to put a
1535   // function call destination in range, so we don't need to bother with a
1536   // wrapper here.
1537   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1538     const GlobalValue *GV = G->getGlobal();
1539     Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1540   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1541     const char *Sym = S->getSymbol();
1542     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1543   }
1544
1545   // We don't usually want to end the call-sequence here because we would tidy
1546   // the frame up *after* the call, however in the ABI-changing tail-call case
1547   // we've carefully laid out the parameters so that when sp is reset they'll be
1548   // in the correct location.
1549   if (IsTailCall && !IsSibCall) {
1550     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1551                                DAG.getIntPtrConstant(0, true), InFlag, dl);
1552     InFlag = Chain.getValue(1);
1553   }
1554
1555   // We produce the following DAG scheme for the actual call instruction:
1556   //     (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1557   //
1558   // Most arguments aren't going to be used and just keep the values live as
1559   // far as LLVM is concerned. It's expected to be selected as simply "bl
1560   // callee" (for a direct, non-tail call).
1561   std::vector<SDValue> Ops;
1562   Ops.push_back(Chain);
1563   Ops.push_back(Callee);
1564
1565   if (IsTailCall) {
1566     // Each tail call may have to adjust the stack by a different amount, so
1567     // this information must travel along with the operation for eventual
1568     // consumption by emitEpilogue.
1569     Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1570   }
1571
1572   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1573     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1574                                   RegsToPass[i].second.getValueType()));
1575
1576
1577   // Add a register mask operand representing the call-preserved registers. This
1578   // is used later in codegen to constrain register-allocation.
1579   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1580   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1581   assert(Mask && "Missing call preserved mask for calling convention");
1582   Ops.push_back(DAG.getRegisterMask(Mask));
1583
1584   // If we needed glue, put it in as the last argument.
1585   if (InFlag.getNode())
1586     Ops.push_back(InFlag);
1587
1588   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1589
1590   if (IsTailCall) {
1591     return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1592   }
1593
1594   Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1595   InFlag = Chain.getValue(1);
1596
1597   // Now we can reclaim the stack, just as well do it before working out where
1598   // our return value is.
1599   if (!IsSibCall) {
1600     uint64_t CalleePopBytes
1601       = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1602
1603     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1604                                DAG.getIntPtrConstant(CalleePopBytes, true),
1605                                InFlag, dl);
1606     InFlag = Chain.getValue(1);
1607   }
1608
1609   return LowerCallResult(Chain, InFlag, CallConv,
1610                          IsVarArg, Ins, dl, DAG, InVals);
1611 }
1612
1613 SDValue
1614 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1615                                       CallingConv::ID CallConv, bool IsVarArg,
1616                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1617                                       SDLoc dl, SelectionDAG &DAG,
1618                                       SmallVectorImpl<SDValue> &InVals) const {
1619   // Assign locations to each value returned by this call.
1620   SmallVector<CCValAssign, 16> RVLocs;
1621   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1622                  getTargetMachine(), RVLocs, *DAG.getContext());
1623   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1624
1625   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1626     CCValAssign VA = RVLocs[i];
1627
1628     // Return values that are too big to fit into registers should use an sret
1629     // pointer, so this can be a lot simpler than the main argument code.
1630     assert(VA.isRegLoc() && "Memory locations not expected for call return");
1631
1632     SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1633                                      InFlag);
1634     Chain = Val.getValue(1);
1635     InFlag = Val.getValue(2);
1636
1637     switch (VA.getLocInfo()) {
1638     default: llvm_unreachable("Unknown loc info!");
1639     case CCValAssign::Full: break;
1640     case CCValAssign::BCvt:
1641       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1642       break;
1643     case CCValAssign::ZExt:
1644     case CCValAssign::SExt:
1645     case CCValAssign::AExt:
1646       // Floating-point arguments only get extended/truncated if they're going
1647       // in memory, so using the integer operation is acceptable here.
1648       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1649       break;
1650     }
1651
1652     InVals.push_back(Val);
1653   }
1654
1655   return Chain;
1656 }
1657
1658 bool
1659 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1660                                     CallingConv::ID CalleeCC,
1661                                     bool IsVarArg,
1662                                     bool IsCalleeStructRet,
1663                                     bool IsCallerStructRet,
1664                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1665                                     const SmallVectorImpl<SDValue> &OutVals,
1666                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1667                                     SelectionDAG& DAG) const {
1668
1669   // For CallingConv::C this function knows whether the ABI needs
1670   // changing. That's not true for other conventions so they will have to opt in
1671   // manually.
1672   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1673     return false;
1674
1675   const MachineFunction &MF = DAG.getMachineFunction();
1676   const Function *CallerF = MF.getFunction();
1677   CallingConv::ID CallerCC = CallerF->getCallingConv();
1678   bool CCMatch = CallerCC == CalleeCC;
1679
1680   // Byval parameters hand the function a pointer directly into the stack area
1681   // we want to reuse during a tail call. Working around this *is* possible (see
1682   // X86) but less efficient and uglier in LowerCall.
1683   for (Function::const_arg_iterator i = CallerF->arg_begin(),
1684          e = CallerF->arg_end(); i != e; ++i)
1685     if (i->hasByValAttr())
1686       return false;
1687
1688   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1689     if (IsTailCallConvention(CalleeCC) && CCMatch)
1690       return true;
1691     return false;
1692   }
1693
1694   // Now we search for cases where we can use a tail call without changing the
1695   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1696   // concept.
1697
1698   // I want anyone implementing a new calling convention to think long and hard
1699   // about this assert.
1700   assert((!IsVarArg || CalleeCC == CallingConv::C)
1701          && "Unexpected variadic calling convention");
1702
1703   if (IsVarArg && !Outs.empty()) {
1704     // At least two cases here: if caller is fastcc then we can't have any
1705     // memory arguments (we'd be expected to clean up the stack afterwards). If
1706     // caller is C then we could potentially use its argument area.
1707
1708     // FIXME: for now we take the most conservative of these in both cases:
1709     // disallow all variadic memory operands.
1710     SmallVector<CCValAssign, 16> ArgLocs;
1711     CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1712                    getTargetMachine(), ArgLocs, *DAG.getContext());
1713
1714     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1715     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1716       if (!ArgLocs[i].isRegLoc())
1717         return false;
1718   }
1719
1720   // If the calling conventions do not match, then we'd better make sure the
1721   // results are returned in the same way as what the caller expects.
1722   if (!CCMatch) {
1723     SmallVector<CCValAssign, 16> RVLocs1;
1724     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1725                     getTargetMachine(), RVLocs1, *DAG.getContext());
1726     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1727
1728     SmallVector<CCValAssign, 16> RVLocs2;
1729     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1730                     getTargetMachine(), RVLocs2, *DAG.getContext());
1731     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1732
1733     if (RVLocs1.size() != RVLocs2.size())
1734       return false;
1735     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1736       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1737         return false;
1738       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1739         return false;
1740       if (RVLocs1[i].isRegLoc()) {
1741         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1742           return false;
1743       } else {
1744         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1745           return false;
1746       }
1747     }
1748   }
1749
1750   // Nothing more to check if the callee is taking no arguments
1751   if (Outs.empty())
1752     return true;
1753
1754   SmallVector<CCValAssign, 16> ArgLocs;
1755   CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1756                  getTargetMachine(), ArgLocs, *DAG.getContext());
1757
1758   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1759
1760   const AArch64MachineFunctionInfo *FuncInfo
1761     = MF.getInfo<AArch64MachineFunctionInfo>();
1762
1763   // If the stack arguments for this call would fit into our own save area then
1764   // the call can be made tail.
1765   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1766 }
1767
1768 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1769                                                    bool TailCallOpt) const {
1770   return CallCC == CallingConv::Fast && TailCallOpt;
1771 }
1772
1773 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1774   return CallCC == CallingConv::Fast;
1775 }
1776
1777 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1778                                                    SelectionDAG &DAG,
1779                                                    MachineFrameInfo *MFI,
1780                                                    int ClobberedFI) const {
1781   SmallVector<SDValue, 8> ArgChains;
1782   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1783   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1784
1785   // Include the original chain at the beginning of the list. When this is
1786   // used by target LowerCall hooks, this helps legalize find the
1787   // CALLSEQ_BEGIN node.
1788   ArgChains.push_back(Chain);
1789
1790   // Add a chain value for each stack argument corresponding
1791   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1792          UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1793     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1794       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1795         if (FI->getIndex() < 0) {
1796           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1797           int64_t InLastByte = InFirstByte;
1798           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1799
1800           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1801               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1802             ArgChains.push_back(SDValue(L, 1));
1803         }
1804
1805    // Build a tokenfactor for all the chains.
1806    return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1807                       &ArgChains[0], ArgChains.size());
1808 }
1809
1810 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1811   switch (CC) {
1812   case ISD::SETEQ:  return A64CC::EQ;
1813   case ISD::SETGT:  return A64CC::GT;
1814   case ISD::SETGE:  return A64CC::GE;
1815   case ISD::SETLT:  return A64CC::LT;
1816   case ISD::SETLE:  return A64CC::LE;
1817   case ISD::SETNE:  return A64CC::NE;
1818   case ISD::SETUGT: return A64CC::HI;
1819   case ISD::SETUGE: return A64CC::HS;
1820   case ISD::SETULT: return A64CC::LO;
1821   case ISD::SETULE: return A64CC::LS;
1822   default: llvm_unreachable("Unexpected condition code");
1823   }
1824 }
1825
1826 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1827   // icmp is implemented using adds/subs immediate, which take an unsigned
1828   // 12-bit immediate, optionally shifted left by 12 bits.
1829
1830   // Symmetric by using adds/subs
1831   if (Val < 0)
1832     Val = -Val;
1833
1834   return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1835 }
1836
1837 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1838                                         ISD::CondCode CC, SDValue &A64cc,
1839                                         SelectionDAG &DAG, SDLoc &dl) const {
1840   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1841     int64_t C = 0;
1842     EVT VT = RHSC->getValueType(0);
1843     bool knownInvalid = false;
1844
1845     // I'm not convinced the rest of LLVM handles these edge cases properly, but
1846     // we can at least get it right.
1847     if (isSignedIntSetCC(CC)) {
1848       C = RHSC->getSExtValue();
1849     } else if (RHSC->getZExtValue() > INT64_MAX) {
1850       // A 64-bit constant not representable by a signed 64-bit integer is far
1851       // too big to fit into a SUBS immediate anyway.
1852       knownInvalid = true;
1853     } else {
1854       C = RHSC->getZExtValue();
1855     }
1856
1857     if (!knownInvalid && !isLegalICmpImmediate(C)) {
1858       // Constant does not fit, try adjusting it by one?
1859       switch (CC) {
1860       default: break;
1861       case ISD::SETLT:
1862       case ISD::SETGE:
1863         if (isLegalICmpImmediate(C-1)) {
1864           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1865           RHS = DAG.getConstant(C-1, VT);
1866         }
1867         break;
1868       case ISD::SETULT:
1869       case ISD::SETUGE:
1870         if (isLegalICmpImmediate(C-1)) {
1871           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1872           RHS = DAG.getConstant(C-1, VT);
1873         }
1874         break;
1875       case ISD::SETLE:
1876       case ISD::SETGT:
1877         if (isLegalICmpImmediate(C+1)) {
1878           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1879           RHS = DAG.getConstant(C+1, VT);
1880         }
1881         break;
1882       case ISD::SETULE:
1883       case ISD::SETUGT:
1884         if (isLegalICmpImmediate(C+1)) {
1885           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1886           RHS = DAG.getConstant(C+1, VT);
1887         }
1888         break;
1889       }
1890     }
1891   }
1892
1893   A64CC::CondCodes CondCode = IntCCToA64CC(CC);
1894   A64cc = DAG.getConstant(CondCode, MVT::i32);
1895   return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1896                      DAG.getCondCode(CC));
1897 }
1898
1899 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
1900                                     A64CC::CondCodes &Alternative) {
1901   A64CC::CondCodes CondCode = A64CC::Invalid;
1902   Alternative = A64CC::Invalid;
1903
1904   switch (CC) {
1905   default: llvm_unreachable("Unknown FP condition!");
1906   case ISD::SETEQ:
1907   case ISD::SETOEQ: CondCode = A64CC::EQ; break;
1908   case ISD::SETGT:
1909   case ISD::SETOGT: CondCode = A64CC::GT; break;
1910   case ISD::SETGE:
1911   case ISD::SETOGE: CondCode = A64CC::GE; break;
1912   case ISD::SETOLT: CondCode = A64CC::MI; break;
1913   case ISD::SETOLE: CondCode = A64CC::LS; break;
1914   case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
1915   case ISD::SETO:   CondCode = A64CC::VC; break;
1916   case ISD::SETUO:  CondCode = A64CC::VS; break;
1917   case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
1918   case ISD::SETUGT: CondCode = A64CC::HI; break;
1919   case ISD::SETUGE: CondCode = A64CC::PL; break;
1920   case ISD::SETLT:
1921   case ISD::SETULT: CondCode = A64CC::LT; break;
1922   case ISD::SETLE:
1923   case ISD::SETULE: CondCode = A64CC::LE; break;
1924   case ISD::SETNE:
1925   case ISD::SETUNE: CondCode = A64CC::NE; break;
1926   }
1927   return CondCode;
1928 }
1929
1930 SDValue
1931 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1932   SDLoc DL(Op);
1933   EVT PtrVT = getPointerTy();
1934   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1935
1936   switch(getTargetMachine().getCodeModel()) {
1937   case CodeModel::Small:
1938     // The most efficient code is PC-relative anyway for the small memory model,
1939     // so we don't need to worry about relocation model.
1940     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
1941                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
1942                                                  AArch64II::MO_NO_FLAG),
1943                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
1944                                                  AArch64II::MO_LO12),
1945                        DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
1946   case CodeModel::Large:
1947     return DAG.getNode(
1948       AArch64ISD::WrapperLarge, DL, PtrVT,
1949       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
1950       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1951       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1952       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1953   default:
1954     llvm_unreachable("Only small and large code models supported now");
1955   }
1956 }
1957
1958
1959 // (BRCOND chain, val, dest)
1960 SDValue
1961 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1962   SDLoc dl(Op);
1963   SDValue Chain = Op.getOperand(0);
1964   SDValue TheBit = Op.getOperand(1);
1965   SDValue DestBB = Op.getOperand(2);
1966
1967   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
1968   // that as the consumer we are responsible for ignoring rubbish in higher
1969   // bits.
1970   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
1971                        DAG.getConstant(1, MVT::i32));
1972
1973   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
1974                                DAG.getConstant(0, TheBit.getValueType()),
1975                                DAG.getCondCode(ISD::SETNE));
1976
1977   return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
1978                      A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
1979                      DestBB);
1980 }
1981
1982 // (BR_CC chain, condcode, lhs, rhs, dest)
1983 SDValue
1984 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1985   SDLoc dl(Op);
1986   SDValue Chain = Op.getOperand(0);
1987   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1988   SDValue LHS = Op.getOperand(2);
1989   SDValue RHS = Op.getOperand(3);
1990   SDValue DestBB = Op.getOperand(4);
1991
1992   if (LHS.getValueType() == MVT::f128) {
1993     // f128 comparisons are lowered to runtime calls by a routine which sets
1994     // LHS, RHS and CC appropriately for the rest of this function to continue.
1995     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
1996
1997     // If softenSetCCOperands returned a scalar, we need to compare the result
1998     // against zero to select between true and false values.
1999     if (RHS.getNode() == 0) {
2000       RHS = DAG.getConstant(0, LHS.getValueType());
2001       CC = ISD::SETNE;
2002     }
2003   }
2004
2005   if (LHS.getValueType().isInteger()) {
2006     SDValue A64cc;
2007
2008     // Integers are handled in a separate function because the combinations of
2009     // immediates and tests can get hairy and we may want to fiddle things.
2010     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2011
2012     return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2013                        Chain, CmpOp, A64cc, DestBB);
2014   }
2015
2016   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2017   // conditional branch, hence FPCCToA64CC can set a second test, where either
2018   // passing is sufficient.
2019   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2020   CondCode = FPCCToA64CC(CC, Alternative);
2021   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2022   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2023                               DAG.getCondCode(CC));
2024   SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2025                                  Chain, SetCC, A64cc, DestBB);
2026
2027   if (Alternative != A64CC::Invalid) {
2028     A64cc = DAG.getConstant(Alternative, MVT::i32);
2029     A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
2030                            A64BR_CC, SetCC, A64cc, DestBB);
2031
2032   }
2033
2034   return A64BR_CC;
2035 }
2036
2037 SDValue
2038 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
2039                                        RTLIB::Libcall Call) const {
2040   ArgListTy Args;
2041   ArgListEntry Entry;
2042   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
2043     EVT ArgVT = Op.getOperand(i).getValueType();
2044     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2045     Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
2046     Entry.isSExt = false;
2047     Entry.isZExt = false;
2048     Args.push_back(Entry);
2049   }
2050   SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
2051
2052   Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
2053
2054   // By default, the input chain to this libcall is the entry node of the
2055   // function. If the libcall is going to be emitted as a tail call then
2056   // isUsedByReturnOnly will change it to the right chain if the return
2057   // node which is being folded has a non-entry input chain.
2058   SDValue InChain = DAG.getEntryNode();
2059
2060   // isTailCall may be true since the callee does not reference caller stack
2061   // frame. Check if it's in the right position.
2062   SDValue TCChain = InChain;
2063   bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
2064   if (isTailCall)
2065     InChain = TCChain;
2066
2067   TargetLowering::
2068   CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
2069                     0, getLibcallCallingConv(Call), isTailCall,
2070                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
2071                     Callee, Args, DAG, SDLoc(Op));
2072   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2073
2074   if (!CallInfo.second.getNode())
2075     // It's a tailcall, return the chain (which is the DAG root).
2076     return DAG.getRoot();
2077
2078   return CallInfo.first;
2079 }
2080
2081 SDValue
2082 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2083   if (Op.getOperand(0).getValueType() != MVT::f128) {
2084     // It's legal except when f128 is involved
2085     return Op;
2086   }
2087
2088   RTLIB::Libcall LC;
2089   LC  = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2090
2091   SDValue SrcVal = Op.getOperand(0);
2092   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
2093                      /*isSigned*/ false, SDLoc(Op)).first;
2094 }
2095
2096 SDValue
2097 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
2098   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2099
2100   RTLIB::Libcall LC;
2101   LC  = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2102
2103   return LowerF128ToCall(Op, DAG, LC);
2104 }
2105
2106 SDValue
2107 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
2108                                       bool IsSigned) const {
2109   if (Op.getOperand(0).getValueType() != MVT::f128) {
2110     // It's legal except when f128 is involved
2111     return Op;
2112   }
2113
2114   RTLIB::Libcall LC;
2115   if (IsSigned)
2116     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2117   else
2118     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2119
2120   return LowerF128ToCall(Op, DAG, LC);
2121 }
2122
2123 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
2124   MachineFunction &MF = DAG.getMachineFunction();
2125   MachineFrameInfo *MFI = MF.getFrameInfo();
2126   MFI->setReturnAddressIsTaken(true);
2127
2128   EVT VT = Op.getValueType();
2129   SDLoc dl(Op);
2130   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2131   if (Depth) {
2132     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
2133     SDValue Offset = DAG.getConstant(8, MVT::i64);
2134     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
2135                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
2136                        MachinePointerInfo(), false, false, false, 0);
2137   }
2138
2139   // Return X30, which contains the return address. Mark it an implicit live-in.
2140   unsigned Reg = MF.addLiveIn(AArch64::X30, getRegClassFor(MVT::i64));
2141   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, MVT::i64);
2142 }
2143
2144
2145 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG)
2146                                               const {
2147   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2148   MFI->setFrameAddressIsTaken(true);
2149
2150   EVT VT = Op.getValueType();
2151   SDLoc dl(Op);
2152   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2153   unsigned FrameReg = AArch64::X29;
2154   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2155   while (Depth--)
2156     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
2157                             MachinePointerInfo(),
2158                             false, false, false, 0);
2159   return FrameAddr;
2160 }
2161
2162 SDValue
2163 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
2164                                                   SelectionDAG &DAG) const {
2165   assert(getTargetMachine().getCodeModel() == CodeModel::Large);
2166   assert(getTargetMachine().getRelocationModel() == Reloc::Static);
2167
2168   EVT PtrVT = getPointerTy();
2169   SDLoc dl(Op);
2170   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2171   const GlobalValue *GV = GN->getGlobal();
2172
2173   SDValue GlobalAddr = DAG.getNode(
2174       AArch64ISD::WrapperLarge, dl, PtrVT,
2175       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
2176       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
2177       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
2178       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
2179
2180   if (GN->getOffset() != 0)
2181     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2182                        DAG.getConstant(GN->getOffset(), PtrVT));
2183
2184   return GlobalAddr;
2185 }
2186
2187 SDValue
2188 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
2189                                                   SelectionDAG &DAG) const {
2190   assert(getTargetMachine().getCodeModel() == CodeModel::Small);
2191
2192   EVT PtrVT = getPointerTy();
2193   SDLoc dl(Op);
2194   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2195   const GlobalValue *GV = GN->getGlobal();
2196   unsigned Alignment = GV->getAlignment();
2197   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2198   if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
2199     // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
2200     // to zero when they remain undefined. In PIC mode the GOT can take care of
2201     // this, but in absolute mode we use a constant pool load.
2202     SDValue PoolAddr;
2203     PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2204                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2205                                                      AArch64II::MO_NO_FLAG),
2206                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2207                                                      AArch64II::MO_LO12),
2208                            DAG.getConstant(8, MVT::i32));
2209     SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
2210                                      MachinePointerInfo::getConstantPool(),
2211                                      /*isVolatile=*/ false,
2212                                      /*isNonTemporal=*/ true,
2213                                      /*isInvariant=*/ true, 8);
2214     if (GN->getOffset() != 0)
2215       return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2216                          DAG.getConstant(GN->getOffset(), PtrVT));
2217
2218     return GlobalAddr;
2219   }
2220
2221   if (Alignment == 0) {
2222     const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2223     if (GVPtrTy->getElementType()->isSized()) {
2224       Alignment
2225         = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2226     } else {
2227       // Be conservative if we can't guess, not that it really matters:
2228       // functions and labels aren't valid for loads, and the methods used to
2229       // actually calculate an address work with any alignment.
2230       Alignment = 1;
2231     }
2232   }
2233
2234   unsigned char HiFixup, LoFixup;
2235   bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2236
2237   if (UseGOT) {
2238     HiFixup = AArch64II::MO_GOT;
2239     LoFixup = AArch64II::MO_GOT_LO12;
2240     Alignment = 8;
2241   } else {
2242     HiFixup = AArch64II::MO_NO_FLAG;
2243     LoFixup = AArch64II::MO_LO12;
2244   }
2245
2246   // AArch64's small model demands the following sequence:
2247   // ADRP x0, somewhere
2248   // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2249   SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2250                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2251                                                              HiFixup),
2252                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2253                                                              LoFixup),
2254                                   DAG.getConstant(Alignment, MVT::i32));
2255
2256   if (UseGOT) {
2257     GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2258                             GlobalRef);
2259   }
2260
2261   if (GN->getOffset() != 0)
2262     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2263                        DAG.getConstant(GN->getOffset(), PtrVT));
2264
2265   return GlobalRef;
2266 }
2267
2268 SDValue
2269 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2270                                              SelectionDAG &DAG) const {
2271   // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2272   // we make those distinctions here.
2273
2274   switch (getTargetMachine().getCodeModel()) {
2275   case CodeModel::Small:
2276     return LowerGlobalAddressELFSmall(Op, DAG);
2277   case CodeModel::Large:
2278     return LowerGlobalAddressELFLarge(Op, DAG);
2279   default:
2280     llvm_unreachable("Only small and large code models supported now");
2281   }
2282 }
2283
2284 SDValue
2285 AArch64TargetLowering::LowerConstantPool(SDValue Op,
2286                                          SelectionDAG &DAG) const {
2287   SDLoc DL(Op);
2288   EVT PtrVT = getPointerTy();
2289   ConstantPoolSDNode *CN = cast<ConstantPoolSDNode>(Op);
2290   const Constant *C = CN->getConstVal();
2291
2292   switch(getTargetMachine().getCodeModel()) {
2293   case CodeModel::Small:
2294     // The most efficient code is PC-relative anyway for the small memory model,
2295     // so we don't need to worry about relocation model.
2296     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2297                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2298                                                  AArch64II::MO_NO_FLAG),
2299                        DAG.getTargetConstantPool(C, PtrVT, 0, 0,
2300                                                  AArch64II::MO_LO12),
2301                        DAG.getConstant(CN->getAlignment(), MVT::i32));
2302   case CodeModel::Large:
2303     return DAG.getNode(
2304       AArch64ISD::WrapperLarge, DL, PtrVT,
2305       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G3),
2306       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G2_NC),
2307       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G1_NC),
2308       DAG.getTargetConstantPool(C, PtrVT, 0, 0, AArch64II::MO_ABS_G0_NC));
2309   default:
2310     llvm_unreachable("Only small and large code models supported now");
2311   }
2312 }
2313
2314 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2315                                                 SDValue DescAddr,
2316                                                 SDLoc DL,
2317                                                 SelectionDAG &DAG) const {
2318   EVT PtrVT = getPointerTy();
2319
2320   // The function we need to call is simply the first entry in the GOT for this
2321   // descriptor, load it in preparation.
2322   SDValue Func, Chain;
2323   Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2324                      DescAddr);
2325
2326   // The function takes only one argument: the address of the descriptor itself
2327   // in X0.
2328   SDValue Glue;
2329   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2330   Glue = Chain.getValue(1);
2331
2332   // Finally, there's a special calling-convention which means that the lookup
2333   // must preserve all registers (except X0, obviously).
2334   const TargetRegisterInfo *TRI  = getTargetMachine().getRegisterInfo();
2335   const AArch64RegisterInfo *A64RI
2336     = static_cast<const AArch64RegisterInfo *>(TRI);
2337   const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2338
2339   // We're now ready to populate the argument list, as with a normal call:
2340   std::vector<SDValue> Ops;
2341   Ops.push_back(Chain);
2342   Ops.push_back(Func);
2343   Ops.push_back(SymAddr);
2344   Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2345   Ops.push_back(DAG.getRegisterMask(Mask));
2346   Ops.push_back(Glue);
2347
2348   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2349   Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2350                       Ops.size());
2351   Glue = Chain.getValue(1);
2352
2353   // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2354   // back to the generic handling code.
2355   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2356 }
2357
2358 SDValue
2359 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2360                                              SelectionDAG &DAG) const {
2361   assert(getSubtarget()->isTargetELF() &&
2362          "TLS not implemented for non-ELF targets");
2363   assert(getTargetMachine().getCodeModel() == CodeModel::Small
2364          && "TLS only supported in small memory model");
2365   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2366
2367   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2368
2369   SDValue TPOff;
2370   EVT PtrVT = getPointerTy();
2371   SDLoc DL(Op);
2372   const GlobalValue *GV = GA->getGlobal();
2373
2374   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2375
2376   if (Model == TLSModel::InitialExec) {
2377     TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2378                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2379                                                    AArch64II::MO_GOTTPREL),
2380                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2381                                                    AArch64II::MO_GOTTPREL_LO12),
2382                         DAG.getConstant(8, MVT::i32));
2383     TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2384                         TPOff);
2385   } else if (Model == TLSModel::LocalExec) {
2386     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2387                                                AArch64II::MO_TPREL_G1);
2388     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2389                                                AArch64II::MO_TPREL_G0_NC);
2390
2391     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2392                                        DAG.getTargetConstant(1, MVT::i32)), 0);
2393     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2394                                        TPOff, LoVar,
2395                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2396   } else if (Model == TLSModel::GeneralDynamic) {
2397     // Accesses used in this sequence go via the TLS descriptor which lives in
2398     // the GOT. Prepare an address we can use to handle this.
2399     SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2400                                                 AArch64II::MO_TLSDESC);
2401     SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2402                                                 AArch64II::MO_TLSDESC_LO12);
2403     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2404                                    HiDesc, LoDesc,
2405                                    DAG.getConstant(8, MVT::i32));
2406     SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2407
2408     TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2409   } else if (Model == TLSModel::LocalDynamic) {
2410     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2411     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2412     // the beginning of the module's TLS region, followed by a DTPREL offset
2413     // calculation.
2414
2415     // These accesses will need deduplicating if there's more than one.
2416     AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2417       .getInfo<AArch64MachineFunctionInfo>();
2418     MFI->incNumLocalDynamicTLSAccesses();
2419
2420
2421     // Get the location of _TLS_MODULE_BASE_:
2422     SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2423                                                 AArch64II::MO_TLSDESC);
2424     SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2425                                                 AArch64II::MO_TLSDESC_LO12);
2426     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2427                                    HiDesc, LoDesc,
2428                                    DAG.getConstant(8, MVT::i32));
2429     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2430
2431     ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2432
2433     // Get the variable's offset from _TLS_MODULE_BASE_
2434     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2435                                                AArch64II::MO_DTPREL_G1);
2436     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2437                                                AArch64II::MO_DTPREL_G0_NC);
2438
2439     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2440                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2441     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2442                                        TPOff, LoVar,
2443                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2444   } else
2445       llvm_unreachable("Unsupported TLS access model");
2446
2447
2448   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2449 }
2450
2451 SDValue
2452 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2453                                       bool IsSigned) const {
2454   if (Op.getValueType() != MVT::f128) {
2455     // Legal for everything except f128.
2456     return Op;
2457   }
2458
2459   RTLIB::Libcall LC;
2460   if (IsSigned)
2461     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2462   else
2463     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2464
2465   return LowerF128ToCall(Op, DAG, LC);
2466 }
2467
2468
2469 SDValue
2470 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2471   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2472   SDLoc dl(JT);
2473   EVT PtrVT = getPointerTy();
2474
2475   // When compiling PIC, jump tables get put in the code section so a static
2476   // relocation-style is acceptable for both cases.
2477   switch (getTargetMachine().getCodeModel()) {
2478   case CodeModel::Small:
2479     return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2480                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2481                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2482                                               AArch64II::MO_LO12),
2483                        DAG.getConstant(1, MVT::i32));
2484   case CodeModel::Large:
2485     return DAG.getNode(
2486       AArch64ISD::WrapperLarge, dl, PtrVT,
2487       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2488       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2489       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2490       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2491   default:
2492     llvm_unreachable("Only small and large code models supported now");
2493   }
2494 }
2495
2496 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
2497 SDValue
2498 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2499   SDLoc dl(Op);
2500   SDValue LHS = Op.getOperand(0);
2501   SDValue RHS = Op.getOperand(1);
2502   SDValue IfTrue = Op.getOperand(2);
2503   SDValue IfFalse = Op.getOperand(3);
2504   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2505
2506   if (LHS.getValueType() == MVT::f128) {
2507     // f128 comparisons are lowered to libcalls, but slot in nicely here
2508     // afterwards.
2509     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2510
2511     // If softenSetCCOperands returned a scalar, we need to compare the result
2512     // against zero to select between true and false values.
2513     if (RHS.getNode() == 0) {
2514       RHS = DAG.getConstant(0, LHS.getValueType());
2515       CC = ISD::SETNE;
2516     }
2517   }
2518
2519   if (LHS.getValueType().isInteger()) {
2520     SDValue A64cc;
2521
2522     // Integers are handled in a separate function because the combinations of
2523     // immediates and tests can get hairy and we may want to fiddle things.
2524     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2525
2526     return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2527                        CmpOp, IfTrue, IfFalse, A64cc);
2528   }
2529
2530   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2531   // conditional branch, hence FPCCToA64CC can set a second test, where either
2532   // passing is sufficient.
2533   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2534   CondCode = FPCCToA64CC(CC, Alternative);
2535   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2536   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2537                               DAG.getCondCode(CC));
2538   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
2539                                      Op.getValueType(),
2540                                      SetCC, IfTrue, IfFalse, A64cc);
2541
2542   if (Alternative != A64CC::Invalid) {
2543     A64cc = DAG.getConstant(Alternative, MVT::i32);
2544     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2545                                SetCC, IfTrue, A64SELECT_CC, A64cc);
2546
2547   }
2548
2549   return A64SELECT_CC;
2550 }
2551
2552 // (SELECT testbit, iftrue, iffalse)
2553 SDValue
2554 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2555   SDLoc dl(Op);
2556   SDValue TheBit = Op.getOperand(0);
2557   SDValue IfTrue = Op.getOperand(1);
2558   SDValue IfFalse = Op.getOperand(2);
2559
2560   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2561   // that as the consumer we are responsible for ignoring rubbish in higher
2562   // bits.
2563   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2564                        DAG.getConstant(1, MVT::i32));
2565   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2566                                DAG.getConstant(0, TheBit.getValueType()),
2567                                DAG.getCondCode(ISD::SETNE));
2568
2569   return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2570                      A64CMP, IfTrue, IfFalse,
2571                      DAG.getConstant(A64CC::NE, MVT::i32));
2572 }
2573
2574 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2575   SDLoc DL(Op);
2576   SDValue LHS = Op.getOperand(0);
2577   SDValue RHS = Op.getOperand(1);
2578   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2579   EVT VT = Op.getValueType();
2580   bool Invert = false;
2581   SDValue Op0, Op1;
2582   unsigned Opcode;
2583
2584   if (LHS.getValueType().isInteger()) {
2585
2586     // Attempt to use Vector Integer Compare Mask Test instruction.
2587     // TST = icmp ne (and (op0, op1), zero).
2588     if (CC == ISD::SETNE) {
2589       if (((LHS.getOpcode() == ISD::AND) &&
2590            ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2591           ((RHS.getOpcode() == ISD::AND) &&
2592            ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2593
2594         SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2595         SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2596         SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2597         return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2598       }
2599     }
2600
2601     // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2602     // Note: Compare against Zero does not support unsigned predicates.
2603     if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2604          ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2605         !isUnsignedIntSetCC(CC)) {
2606
2607       // If LHS is the zero value, swap operands and CondCode.
2608       if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2609         CC = getSetCCSwappedOperands(CC);
2610         Op0 = RHS;
2611       } else
2612         Op0 = LHS;
2613
2614       // Ensure valid CondCode for Compare Mask against Zero instruction:
2615       // EQ, GE, GT, LE, LT.
2616       if (ISD::SETNE == CC) {
2617         Invert = true;
2618         CC = ISD::SETEQ;
2619       }
2620
2621       // Using constant type to differentiate integer and FP compares with zero.
2622       Op1 = DAG.getConstant(0, MVT::i32);
2623       Opcode = AArch64ISD::NEON_CMPZ;
2624
2625     } else {
2626       // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2627       // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2628       bool Swap = false;
2629       switch (CC) {
2630       default:
2631         llvm_unreachable("Illegal integer comparison.");
2632       case ISD::SETEQ:
2633       case ISD::SETGT:
2634       case ISD::SETGE:
2635       case ISD::SETUGT:
2636       case ISD::SETUGE:
2637         break;
2638       case ISD::SETNE:
2639         Invert = true;
2640         CC = ISD::SETEQ;
2641         break;
2642       case ISD::SETULT:
2643       case ISD::SETULE:
2644       case ISD::SETLT:
2645       case ISD::SETLE:
2646         Swap = true;
2647         CC = getSetCCSwappedOperands(CC);
2648       }
2649
2650       if (Swap)
2651         std::swap(LHS, RHS);
2652
2653       Opcode = AArch64ISD::NEON_CMP;
2654       Op0 = LHS;
2655       Op1 = RHS;
2656     }
2657
2658     // Generate Compare Mask instr or Compare Mask against Zero instr.
2659     SDValue NeonCmp =
2660         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2661
2662     if (Invert)
2663       NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2664
2665     return NeonCmp;
2666   }
2667
2668   // Now handle Floating Point cases.
2669   // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2670   if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2671       ISD::isBuildVectorAllZeros(LHS.getNode())) {
2672
2673     // If LHS is the zero value, swap operands and CondCode.
2674     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2675       CC = getSetCCSwappedOperands(CC);
2676       Op0 = RHS;
2677     } else
2678       Op0 = LHS;
2679
2680     // Using constant type to differentiate integer and FP compares with zero.
2681     Op1 = DAG.getConstantFP(0, MVT::f32);
2682     Opcode = AArch64ISD::NEON_CMPZ;
2683   } else {
2684     // Attempt to use Vector Floating Point Compare Mask instruction.
2685     Op0 = LHS;
2686     Op1 = RHS;
2687     Opcode = AArch64ISD::NEON_CMP;
2688   }
2689
2690   SDValue NeonCmpAlt;
2691   // Some register compares have to be implemented with swapped CC and operands,
2692   // e.g.: OLT implemented as OGT with swapped operands.
2693   bool SwapIfRegArgs = false;
2694
2695   // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2696   // EQ, GE, GT, LE, LT.
2697   // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2698   switch (CC) {
2699   default:
2700     llvm_unreachable("Illegal FP comparison");
2701   case ISD::SETUNE:
2702   case ISD::SETNE:
2703     Invert = true; // Fallthrough
2704   case ISD::SETOEQ:
2705   case ISD::SETEQ:
2706     CC = ISD::SETEQ;
2707     break;
2708   case ISD::SETOLT:
2709   case ISD::SETLT:
2710     CC = ISD::SETLT;
2711     SwapIfRegArgs = true;
2712     break;
2713   case ISD::SETOGT:
2714   case ISD::SETGT:
2715     CC = ISD::SETGT;
2716     break;
2717   case ISD::SETOLE:
2718   case ISD::SETLE:
2719     CC = ISD::SETLE;
2720     SwapIfRegArgs = true;
2721     break;
2722   case ISD::SETOGE:
2723   case ISD::SETGE:
2724     CC = ISD::SETGE;
2725     break;
2726   case ISD::SETUGE:
2727     Invert = true;
2728     CC = ISD::SETLT;
2729     SwapIfRegArgs = true;
2730     break;
2731   case ISD::SETULE:
2732     Invert = true;
2733     CC = ISD::SETGT;
2734     break;
2735   case ISD::SETUGT:
2736     Invert = true;
2737     CC = ISD::SETLE;
2738     SwapIfRegArgs = true;
2739     break;
2740   case ISD::SETULT:
2741     Invert = true;
2742     CC = ISD::SETGE;
2743     break;
2744   case ISD::SETUEQ:
2745     Invert = true; // Fallthrough
2746   case ISD::SETONE:
2747     // Expand this to (OGT |OLT).
2748     NeonCmpAlt =
2749         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2750     CC = ISD::SETLT;
2751     SwapIfRegArgs = true;
2752     break;
2753   case ISD::SETUO:
2754     Invert = true; // Fallthrough
2755   case ISD::SETO:
2756     // Expand this to (OGE | OLT).
2757     NeonCmpAlt =
2758         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2759     CC = ISD::SETLT;
2760     SwapIfRegArgs = true;
2761     break;
2762   }
2763
2764   if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2765     CC = getSetCCSwappedOperands(CC);
2766     std::swap(Op0, Op1);
2767   }
2768
2769   // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2770   SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2771
2772   if (NeonCmpAlt.getNode())
2773     NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2774
2775   if (Invert)
2776     NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2777
2778   return NeonCmp;
2779 }
2780
2781 // (SETCC lhs, rhs, condcode)
2782 SDValue
2783 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2784   SDLoc dl(Op);
2785   SDValue LHS = Op.getOperand(0);
2786   SDValue RHS = Op.getOperand(1);
2787   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2788   EVT VT = Op.getValueType();
2789
2790   if (VT.isVector())
2791     return LowerVectorSETCC(Op, DAG);
2792
2793   if (LHS.getValueType() == MVT::f128) {
2794     // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2795     // for the rest of the function (some i32 or i64 values).
2796     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2797
2798     // If softenSetCCOperands returned a scalar, use it.
2799     if (RHS.getNode() == 0) {
2800       assert(LHS.getValueType() == Op.getValueType() &&
2801              "Unexpected setcc expansion!");
2802       return LHS;
2803     }
2804   }
2805
2806   if (LHS.getValueType().isInteger()) {
2807     SDValue A64cc;
2808
2809     // Integers are handled in a separate function because the combinations of
2810     // immediates and tests can get hairy and we may want to fiddle things.
2811     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2812
2813     return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2814                        CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2815                        A64cc);
2816   }
2817
2818   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2819   // conditional branch, hence FPCCToA64CC can set a second test, where either
2820   // passing is sufficient.
2821   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2822   CondCode = FPCCToA64CC(CC, Alternative);
2823   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2824   SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2825                               DAG.getCondCode(CC));
2826   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2827                                      CmpOp, DAG.getConstant(1, VT),
2828                                      DAG.getConstant(0, VT), A64cc);
2829
2830   if (Alternative != A64CC::Invalid) {
2831     A64cc = DAG.getConstant(Alternative, MVT::i32);
2832     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
2833                                DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
2834   }
2835
2836   return A64SELECT_CC;
2837 }
2838
2839 SDValue
2840 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2841   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2842   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2843
2844   // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
2845   // rather than just 8.
2846   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
2847                        Op.getOperand(1), Op.getOperand(2),
2848                        DAG.getConstant(32, MVT::i32), 8, false, false,
2849                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
2850 }
2851
2852 SDValue
2853 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2854   // The layout of the va_list struct is specified in the AArch64 Procedure Call
2855   // Standard, section B.3.
2856   MachineFunction &MF = DAG.getMachineFunction();
2857   AArch64MachineFunctionInfo *FuncInfo
2858     = MF.getInfo<AArch64MachineFunctionInfo>();
2859   SDLoc DL(Op);
2860
2861   SDValue Chain = Op.getOperand(0);
2862   SDValue VAList = Op.getOperand(1);
2863   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2864   SmallVector<SDValue, 4> MemOps;
2865
2866   // void *__stack at offset 0
2867   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
2868                                     getPointerTy());
2869   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
2870                                 MachinePointerInfo(SV), false, false, 0));
2871
2872   // void *__gr_top at offset 8
2873   int GPRSize = FuncInfo->getVariadicGPRSize();
2874   if (GPRSize > 0) {
2875     SDValue GRTop, GRTopAddr;
2876
2877     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2878                             DAG.getConstant(8, getPointerTy()));
2879
2880     GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
2881     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
2882                         DAG.getConstant(GPRSize, getPointerTy()));
2883
2884     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
2885                                   MachinePointerInfo(SV, 8),
2886                                   false, false, 0));
2887   }
2888
2889   // void *__vr_top at offset 16
2890   int FPRSize = FuncInfo->getVariadicFPRSize();
2891   if (FPRSize > 0) {
2892     SDValue VRTop, VRTopAddr;
2893     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2894                             DAG.getConstant(16, getPointerTy()));
2895
2896     VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
2897     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
2898                         DAG.getConstant(FPRSize, getPointerTy()));
2899
2900     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
2901                                   MachinePointerInfo(SV, 16),
2902                                   false, false, 0));
2903   }
2904
2905   // int __gr_offs at offset 24
2906   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2907                                    DAG.getConstant(24, getPointerTy()));
2908   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
2909                                 GROffsAddr, MachinePointerInfo(SV, 24),
2910                                 false, false, 0));
2911
2912   // int __vr_offs at offset 28
2913   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2914                                    DAG.getConstant(28, getPointerTy()));
2915   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
2916                                 VROffsAddr, MachinePointerInfo(SV, 28),
2917                                 false, false, 0));
2918
2919   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2920                      MemOps.size());
2921 }
2922
2923 SDValue
2924 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2925   switch (Op.getOpcode()) {
2926   default: llvm_unreachable("Don't know how to custom lower this!");
2927   case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
2928   case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
2929   case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
2930   case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
2931   case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
2932   case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
2933   case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
2934   case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
2935   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
2936   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
2937   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
2938   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2939
2940   case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
2941   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2942   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
2943   case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
2944   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
2945   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
2946   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
2947   case ISD::SELECT: return LowerSELECT(Op, DAG);
2948   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
2949   case ISD::SETCC: return LowerSETCC(Op, DAG);
2950   case ISD::VACOPY: return LowerVACOPY(Op, DAG);
2951   case ISD::VASTART: return LowerVASTART(Op, DAG);
2952   case ISD::BUILD_VECTOR:
2953     return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
2954   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2955   }
2956
2957   return SDValue();
2958 }
2959
2960 /// Check if the specified splat value corresponds to a valid vector constant
2961 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI).  If
2962 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
2963 /// values.
2964 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2965                               unsigned SplatBitSize, SelectionDAG &DAG,
2966                               bool is128Bits, NeonModImmType type, EVT &VT,
2967                               unsigned &Imm, unsigned &OpCmode) {
2968   switch (SplatBitSize) {
2969   default:
2970     llvm_unreachable("unexpected size for isNeonModifiedImm");
2971   case 8: {
2972     if (type != Neon_Mov_Imm)
2973       return false;
2974     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2975     // Neon movi per byte: Op=0, Cmode=1110.
2976     OpCmode = 0xe;
2977     Imm = SplatBits;
2978     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
2979     break;
2980   }
2981   case 16: {
2982     // Neon move inst per halfword
2983     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
2984     if ((SplatBits & ~0xff) == 0) {
2985       // Value = 0x00nn is 0x00nn LSL 0
2986       // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
2987       // bic:  Op=1, Cmode=1001;  orr:  Op=0, Cmode=1001
2988       // Op=x, Cmode=100y
2989       Imm = SplatBits;
2990       OpCmode = 0x8;
2991       break;
2992     }
2993     if ((SplatBits & ~0xff00) == 0) {
2994       // Value = 0xnn00 is 0x00nn LSL 8
2995       // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
2996       // bic:  Op=1, Cmode=1011;  orr:  Op=0, Cmode=1011
2997       // Op=x, Cmode=101x
2998       Imm = SplatBits >> 8;
2999       OpCmode = 0xa;
3000       break;
3001     }
3002     // can't handle any other
3003     return false;
3004   }
3005
3006   case 32: {
3007     // First the LSL variants (MSL is unusable by some interested instructions).
3008
3009     // Neon move instr per word, shift zeros
3010     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3011     if ((SplatBits & ~0xff) == 0) {
3012       // Value = 0x000000nn is 0x000000nn LSL 0
3013       // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
3014       // bic:  Op=1, Cmode= 0001; orr:  Op=0, Cmode= 0001
3015       // Op=x, Cmode=000x
3016       Imm = SplatBits;
3017       OpCmode = 0;
3018       break;
3019     }
3020     if ((SplatBits & ~0xff00) == 0) {
3021       // Value = 0x0000nn00 is 0x000000nn LSL 8
3022       // movi: Op=0, Cmode= 0010;  mvni: Op=1, Cmode= 0010
3023       // bic:  Op=1, Cmode= 0011;  orr : Op=0, Cmode= 0011
3024       // Op=x, Cmode=001x
3025       Imm = SplatBits >> 8;
3026       OpCmode = 0x2;
3027       break;
3028     }
3029     if ((SplatBits & ~0xff0000) == 0) {
3030       // Value = 0x00nn0000 is 0x000000nn LSL 16
3031       // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
3032       // bic:  Op=1, Cmode= 0101; orr:  Op=0, Cmode= 0101
3033       // Op=x, Cmode=010x
3034       Imm = SplatBits >> 16;
3035       OpCmode = 0x4;
3036       break;
3037     }
3038     if ((SplatBits & ~0xff000000) == 0) {
3039       // Value = 0xnn000000 is 0x000000nn LSL 24
3040       // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
3041       // bic:  Op=1, Cmode= 0111; orr:  Op=0, Cmode= 0111
3042       // Op=x, Cmode=011x
3043       Imm = SplatBits >> 24;
3044       OpCmode = 0x6;
3045       break;
3046     }
3047
3048     // Now the MSL immediates.
3049
3050     // Neon move instr per word, shift ones
3051     if ((SplatBits & ~0xffff) == 0 &&
3052         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3053       // Value = 0x0000nnff is 0x000000nn MSL 8
3054       // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
3055       // Op=x, Cmode=1100
3056       Imm = SplatBits >> 8;
3057       OpCmode = 0xc;
3058       break;
3059     }
3060     if ((SplatBits & ~0xffffff) == 0 &&
3061         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3062       // Value = 0x00nnffff is 0x000000nn MSL 16
3063       // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
3064       // Op=x, Cmode=1101
3065       Imm = SplatBits >> 16;
3066       OpCmode = 0xd;
3067       break;
3068     }
3069     // can't handle any other
3070     return false;
3071   }
3072
3073   case 64: {
3074     if (type != Neon_Mov_Imm)
3075       return false;
3076     // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
3077     // movi Op=1, Cmode=1110.
3078     OpCmode = 0x1e;
3079     uint64_t BitMask = 0xff;
3080     uint64_t Val = 0;
3081     unsigned ImmMask = 1;
3082     Imm = 0;
3083     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3084       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3085         Val |= BitMask;
3086         Imm |= ImmMask;
3087       } else if ((SplatBits & BitMask) != 0) {
3088         return false;
3089       }
3090       BitMask <<= 8;
3091       ImmMask <<= 1;
3092     }
3093     SplatBits = Val;
3094     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3095     break;
3096   }
3097   }
3098
3099   return true;
3100 }
3101
3102 static SDValue PerformANDCombine(SDNode *N,
3103                                  TargetLowering::DAGCombinerInfo &DCI) {
3104
3105   SelectionDAG &DAG = DCI.DAG;
3106   SDLoc DL(N);
3107   EVT VT = N->getValueType(0);
3108
3109   // We're looking for an SRA/SHL pair which form an SBFX.
3110
3111   if (VT != MVT::i32 && VT != MVT::i64)
3112     return SDValue();
3113
3114   if (!isa<ConstantSDNode>(N->getOperand(1)))
3115     return SDValue();
3116
3117   uint64_t TruncMask = N->getConstantOperandVal(1);
3118   if (!isMask_64(TruncMask))
3119     return SDValue();
3120
3121   uint64_t Width = CountPopulation_64(TruncMask);
3122   SDValue Shift = N->getOperand(0);
3123
3124   if (Shift.getOpcode() != ISD::SRL)
3125     return SDValue();
3126
3127   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3128     return SDValue();
3129   uint64_t LSB = Shift->getConstantOperandVal(1);
3130
3131   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3132     return SDValue();
3133
3134   return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
3135                      DAG.getConstant(LSB, MVT::i64),
3136                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3137 }
3138
3139 /// For a true bitfield insert, the bits getting into that contiguous mask
3140 /// should come from the low part of an existing value: they must be formed from
3141 /// a compatible SHL operation (unless they're already low). This function
3142 /// checks that condition and returns the least-significant bit that's
3143 /// intended. If the operation not a field preparation, -1 is returned.
3144 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
3145                             SDValue &MaskedVal, uint64_t Mask) {
3146   if (!isShiftedMask_64(Mask))
3147     return -1;
3148
3149   // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
3150   // instruction. BFI will do a left-shift by LSB before applying the mask we've
3151   // spotted, so in general we should pre-emptively "undo" that by making sure
3152   // the incoming bits have had a right-shift applied to them.
3153   //
3154   // This right shift, however, will combine with existing left/right shifts. In
3155   // the simplest case of a completely straight bitfield operation, it will be
3156   // expected to completely cancel out with an existing SHL. More complicated
3157   // cases (e.g. bitfield to bitfield copy) may still need a real shift before
3158   // the BFI.
3159
3160   uint64_t LSB = countTrailingZeros(Mask);
3161   int64_t ShiftRightRequired = LSB;
3162   if (MaskedVal.getOpcode() == ISD::SHL &&
3163       isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3164     ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
3165     MaskedVal = MaskedVal.getOperand(0);
3166   } else if (MaskedVal.getOpcode() == ISD::SRL &&
3167              isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
3168     ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
3169     MaskedVal = MaskedVal.getOperand(0);
3170   }
3171
3172   if (ShiftRightRequired > 0)
3173     MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
3174                             DAG.getConstant(ShiftRightRequired, MVT::i64));
3175   else if (ShiftRightRequired < 0) {
3176     // We could actually end up with a residual left shift, for example with
3177     // "struc.bitfield = val << 1".
3178     MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
3179                             DAG.getConstant(-ShiftRightRequired, MVT::i64));
3180   }
3181
3182   return LSB;
3183 }
3184
3185 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
3186 /// a mask and an extension. Returns true if a BFI was found and provides
3187 /// information on its surroundings.
3188 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
3189                           bool &Extended) {
3190   Extended = false;
3191   if (N.getOpcode() == ISD::ZERO_EXTEND) {
3192     Extended = true;
3193     N = N.getOperand(0);
3194   }
3195
3196   if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
3197     Mask = N->getConstantOperandVal(1);
3198     N = N.getOperand(0);
3199   } else {
3200     // Mask is the whole width.
3201     Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
3202   }
3203
3204   if (N.getOpcode() == AArch64ISD::BFI) {
3205     BFI = N;
3206     return true;
3207   }
3208
3209   return false;
3210 }
3211
3212 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
3213 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
3214 /// can often be further combined with a larger mask. Ultimately, we want mask
3215 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
3216 static SDValue tryCombineToBFI(SDNode *N,
3217                                TargetLowering::DAGCombinerInfo &DCI,
3218                                const AArch64Subtarget *Subtarget) {
3219   SelectionDAG &DAG = DCI.DAG;
3220   SDLoc DL(N);
3221   EVT VT = N->getValueType(0);
3222
3223   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3224
3225   // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
3226   // abandon the effort.
3227   SDValue LHS = N->getOperand(0);
3228   if (LHS.getOpcode() != ISD::AND)
3229     return SDValue();
3230
3231   uint64_t LHSMask;
3232   if (isa<ConstantSDNode>(LHS.getOperand(1)))
3233     LHSMask = LHS->getConstantOperandVal(1);
3234   else
3235     return SDValue();
3236
3237   // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
3238   // is or abandon the effort.
3239   SDValue RHS = N->getOperand(1);
3240   if (RHS.getOpcode() != ISD::AND)
3241     return SDValue();
3242
3243   uint64_t RHSMask;
3244   if (isa<ConstantSDNode>(RHS.getOperand(1)))
3245     RHSMask = RHS->getConstantOperandVal(1);
3246   else
3247     return SDValue();
3248
3249   // Can't do anything if the masks are incompatible.
3250   if (LHSMask & RHSMask)
3251     return SDValue();
3252
3253   // Now we need one of the masks to be a contiguous field. Without loss of
3254   // generality that should be the RHS one.
3255   SDValue Bitfield = LHS.getOperand(0);
3256   if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3257     // We know that LHS is a candidate new value, and RHS isn't already a better
3258     // one.
3259     std::swap(LHS, RHS);
3260     std::swap(LHSMask, RHSMask);
3261   }
3262
3263   // We've done our best to put the right operands in the right places, all we
3264   // can do now is check whether a BFI exists.
3265   Bitfield = RHS.getOperand(0);
3266   int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3267   if (LSB == -1)
3268     return SDValue();
3269
3270   uint32_t Width = CountPopulation_64(RHSMask);
3271   assert(Width && "Expected non-zero bitfield width");
3272
3273   SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3274                             LHS.getOperand(0), Bitfield,
3275                             DAG.getConstant(LSB, MVT::i64),
3276                             DAG.getConstant(Width, MVT::i64));
3277
3278   // Mask is trivial
3279   if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3280     return BFI;
3281
3282   return DAG.getNode(ISD::AND, DL, VT, BFI,
3283                      DAG.getConstant(LHSMask | RHSMask, VT));
3284 }
3285
3286 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3287 /// original input. This is surprisingly common because SROA splits things up
3288 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3289 /// on the low (say) byte of a word. This is then orred into the rest of the
3290 /// word afterwards.
3291 ///
3292 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3293 ///
3294 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3295 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3296 /// involved.
3297 static SDValue tryCombineToLargerBFI(SDNode *N,
3298                                      TargetLowering::DAGCombinerInfo &DCI,
3299                                      const AArch64Subtarget *Subtarget) {
3300   SelectionDAG &DAG = DCI.DAG;
3301   SDLoc DL(N);
3302   EVT VT = N->getValueType(0);
3303
3304   // First job is to hunt for a MaskedBFI on either the left or right. Swap
3305   // operands if it's actually on the right.
3306   SDValue BFI;
3307   SDValue PossExtraMask;
3308   uint64_t ExistingMask = 0;
3309   bool Extended = false;
3310   if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3311     PossExtraMask = N->getOperand(1);
3312   else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3313     PossExtraMask = N->getOperand(0);
3314   else
3315     return SDValue();
3316
3317   // We can only combine a BFI with another compatible mask.
3318   if (PossExtraMask.getOpcode() != ISD::AND ||
3319       !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3320     return SDValue();
3321
3322   uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3323
3324   // Masks must be compatible.
3325   if (ExtraMask & ExistingMask)
3326     return SDValue();
3327
3328   SDValue OldBFIVal = BFI.getOperand(0);
3329   SDValue NewBFIVal = BFI.getOperand(1);
3330   if (Extended) {
3331     // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3332     // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3333     // need to be made compatible.
3334     assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3335            && "Invalid types for BFI");
3336     OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3337     NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3338   }
3339
3340   // We need the MaskedBFI to be combined with a mask of the *same* value.
3341   if (PossExtraMask.getOperand(0) != OldBFIVal)
3342     return SDValue();
3343
3344   BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3345                     OldBFIVal, NewBFIVal,
3346                     BFI.getOperand(2), BFI.getOperand(3));
3347
3348   // If the masking is trivial, we don't need to create it.
3349   if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3350     return BFI;
3351
3352   return DAG.getNode(ISD::AND, DL, VT, BFI,
3353                      DAG.getConstant(ExtraMask | ExistingMask, VT));
3354 }
3355
3356 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3357 /// searches for and classifies those shifts.
3358 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3359                          bool &FromHi) {
3360   if (N.getOpcode() == ISD::SHL)
3361     FromHi = false;
3362   else if (N.getOpcode() == ISD::SRL)
3363     FromHi = true;
3364   else
3365     return false;
3366
3367   if (!isa<ConstantSDNode>(N.getOperand(1)))
3368     return false;
3369
3370   ShiftAmount = N->getConstantOperandVal(1);
3371   Src = N->getOperand(0);
3372   return true;
3373 }
3374
3375 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3376 /// registers viewed as a high/low pair. This function looks for the pattern:
3377 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3378 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3379 /// independent.
3380 static SDValue tryCombineToEXTR(SDNode *N,
3381                                 TargetLowering::DAGCombinerInfo &DCI) {
3382   SelectionDAG &DAG = DCI.DAG;
3383   SDLoc DL(N);
3384   EVT VT = N->getValueType(0);
3385
3386   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3387
3388   if (VT != MVT::i32 && VT != MVT::i64)
3389     return SDValue();
3390
3391   SDValue LHS;
3392   uint32_t ShiftLHS = 0;
3393   bool LHSFromHi = 0;
3394   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3395     return SDValue();
3396
3397   SDValue RHS;
3398   uint32_t ShiftRHS = 0;
3399   bool RHSFromHi = 0;
3400   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3401     return SDValue();
3402
3403   // If they're both trying to come from the high part of the register, they're
3404   // not really an EXTR.
3405   if (LHSFromHi == RHSFromHi)
3406     return SDValue();
3407
3408   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3409     return SDValue();
3410
3411   if (LHSFromHi) {
3412     std::swap(LHS, RHS);
3413     std::swap(ShiftLHS, ShiftRHS);
3414   }
3415
3416   return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3417                      LHS, RHS,
3418                      DAG.getConstant(ShiftRHS, MVT::i64));
3419 }
3420
3421 /// Target-specific dag combine xforms for ISD::OR
3422 static SDValue PerformORCombine(SDNode *N,
3423                                 TargetLowering::DAGCombinerInfo &DCI,
3424                                 const AArch64Subtarget *Subtarget) {
3425
3426   SelectionDAG &DAG = DCI.DAG;
3427   SDLoc DL(N);
3428   EVT VT = N->getValueType(0);
3429
3430   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3431     return SDValue();
3432
3433   // Attempt to recognise bitfield-insert operations.
3434   SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3435   if (Res.getNode())
3436     return Res;
3437
3438   // Attempt to combine an existing MaskedBFI operation into one with a larger
3439   // mask.
3440   Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3441   if (Res.getNode())
3442     return Res;
3443
3444   Res = tryCombineToEXTR(N, DCI);
3445   if (Res.getNode())
3446     return Res;
3447
3448   if (!Subtarget->hasNEON())
3449     return SDValue();
3450
3451   // Attempt to use vector immediate-form BSL
3452   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3453
3454   SDValue N0 = N->getOperand(0);
3455   if (N0.getOpcode() != ISD::AND)
3456     return SDValue();
3457
3458   SDValue N1 = N->getOperand(1);
3459   if (N1.getOpcode() != ISD::AND)
3460     return SDValue();
3461
3462   if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3463     APInt SplatUndef;
3464     unsigned SplatBitSize;
3465     bool HasAnyUndefs;
3466     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3467     APInt SplatBits0;
3468     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3469                                       HasAnyUndefs) &&
3470         !HasAnyUndefs) {
3471       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3472       APInt SplatBits1;
3473       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3474                                         HasAnyUndefs) &&
3475           !HasAnyUndefs && SplatBits0 == ~SplatBits1) {
3476
3477         return DAG.getNode(ISD::VSELECT, DL, VT, N0->getOperand(1),
3478                            N0->getOperand(0), N1->getOperand(0));
3479       }
3480     }
3481   }
3482
3483   return SDValue();
3484 }
3485
3486 /// Target-specific dag combine xforms for ISD::SRA
3487 static SDValue PerformSRACombine(SDNode *N,
3488                                  TargetLowering::DAGCombinerInfo &DCI) {
3489
3490   SelectionDAG &DAG = DCI.DAG;
3491   SDLoc DL(N);
3492   EVT VT = N->getValueType(0);
3493
3494   // We're looking for an SRA/SHL pair which form an SBFX.
3495
3496   if (VT != MVT::i32 && VT != MVT::i64)
3497     return SDValue();
3498
3499   if (!isa<ConstantSDNode>(N->getOperand(1)))
3500     return SDValue();
3501
3502   uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3503   SDValue Shift = N->getOperand(0);
3504
3505   if (Shift.getOpcode() != ISD::SHL)
3506     return SDValue();
3507
3508   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3509     return SDValue();
3510
3511   uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3512   uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3513   uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3514
3515   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3516     return SDValue();
3517
3518   return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3519                      DAG.getConstant(LSB, MVT::i64),
3520                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3521 }
3522
3523 /// Check if this is a valid build_vector for the immediate operand of
3524 /// a vector shift operation, where all the elements of the build_vector
3525 /// must have the same constant integer value.
3526 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3527   // Ignore bit_converts.
3528   while (Op.getOpcode() == ISD::BITCAST)
3529     Op = Op.getOperand(0);
3530   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3531   APInt SplatBits, SplatUndef;
3532   unsigned SplatBitSize;
3533   bool HasAnyUndefs;
3534   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3535                                       HasAnyUndefs, ElementBits) ||
3536       SplatBitSize > ElementBits)
3537     return false;
3538   Cnt = SplatBits.getSExtValue();
3539   return true;
3540 }
3541
3542 /// Check if this is a valid build_vector for the immediate operand of
3543 /// a vector shift left operation.  That value must be in the range:
3544 /// 0 <= Value < ElementBits
3545 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3546   assert(VT.isVector() && "vector shift count is not a vector type");
3547   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3548   if (!getVShiftImm(Op, ElementBits, Cnt))
3549     return false;
3550   return (Cnt >= 0 && Cnt < ElementBits);
3551 }
3552
3553 /// Check if this is a valid build_vector for the immediate operand of a
3554 /// vector shift right operation. The value must be in the range:
3555 ///   1 <= Value <= ElementBits
3556 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3557   assert(VT.isVector() && "vector shift count is not a vector type");
3558   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3559   if (!getVShiftImm(Op, ElementBits, Cnt))
3560     return false;
3561   return (Cnt >= 1 && Cnt <= ElementBits);
3562 }
3563
3564 /// Checks for immediate versions of vector shifts and lowers them.
3565 static SDValue PerformShiftCombine(SDNode *N,
3566                                    TargetLowering::DAGCombinerInfo &DCI,
3567                                    const AArch64Subtarget *ST) {
3568   SelectionDAG &DAG = DCI.DAG;
3569   EVT VT = N->getValueType(0);
3570   if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3571     return PerformSRACombine(N, DCI);
3572
3573   // Nothing to be done for scalar shifts.
3574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3575   if (!VT.isVector() || !TLI.isTypeLegal(VT))
3576     return SDValue();
3577
3578   assert(ST->hasNEON() && "unexpected vector shift");
3579   int64_t Cnt;
3580
3581   switch (N->getOpcode()) {
3582   default:
3583     llvm_unreachable("unexpected shift opcode");
3584
3585   case ISD::SHL:
3586     if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3587       SDValue RHS =
3588           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
3589                       DAG.getConstant(Cnt, MVT::i32));
3590       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3591     }
3592     break;
3593
3594   case ISD::SRA:
3595   case ISD::SRL:
3596     if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
3597       SDValue RHS =
3598           DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
3599                       DAG.getConstant(Cnt, MVT::i32));
3600       return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
3601     }
3602     break;
3603   }
3604
3605   return SDValue();
3606 }
3607
3608 /// ARM-specific DAG combining for intrinsics.
3609 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3610   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3611
3612   switch (IntNo) {
3613   default:
3614     // Don't do anything for most intrinsics.
3615     break;
3616
3617   case Intrinsic::arm_neon_vqshifts:
3618   case Intrinsic::arm_neon_vqshiftu:
3619     EVT VT = N->getOperand(1).getValueType();
3620     int64_t Cnt;
3621     if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
3622       break;
3623     unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
3624                              ? AArch64ISD::NEON_QSHLs
3625                              : AArch64ISD::NEON_QSHLu;
3626     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
3627                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3628   }
3629
3630   return SDValue();
3631 }
3632
3633 /// Target-specific DAG combine function for NEON load/store intrinsics
3634 /// to merge base address updates.
3635 static SDValue CombineBaseUpdate(SDNode *N,
3636                                  TargetLowering::DAGCombinerInfo &DCI) {
3637   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
3638     return SDValue();
3639
3640   SelectionDAG &DAG = DCI.DAG;
3641   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
3642                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
3643   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
3644   SDValue Addr = N->getOperand(AddrOpIdx);
3645
3646   // Search for a use of the address operand that is an increment.
3647   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
3648        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
3649     SDNode *User = *UI;
3650     if (User->getOpcode() != ISD::ADD ||
3651         UI.getUse().getResNo() != Addr.getResNo())
3652       continue;
3653
3654     // Check that the add is independent of the load/store.  Otherwise, folding
3655     // it would create a cycle.
3656     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
3657       continue;
3658
3659     // Find the new opcode for the updating load/store.
3660     bool isLoad = true;
3661     bool isLaneOp = false;
3662     unsigned NewOpc = 0;
3663     unsigned NumVecs = 0;
3664     if (isIntrinsic) {
3665       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3666       switch (IntNo) {
3667       default: llvm_unreachable("unexpected intrinsic for Neon base update");
3668       case Intrinsic::arm_neon_vld1:       NewOpc = AArch64ISD::NEON_LD1_UPD;
3669         NumVecs = 1; break;
3670       case Intrinsic::arm_neon_vld2:       NewOpc = AArch64ISD::NEON_LD2_UPD;
3671         NumVecs = 2; break;
3672       case Intrinsic::arm_neon_vld3:       NewOpc = AArch64ISD::NEON_LD3_UPD;
3673         NumVecs = 3; break;
3674       case Intrinsic::arm_neon_vld4:       NewOpc = AArch64ISD::NEON_LD4_UPD;
3675         NumVecs = 4; break;
3676       case Intrinsic::arm_neon_vst1:       NewOpc = AArch64ISD::NEON_ST1_UPD;
3677         NumVecs = 1; isLoad = false; break;
3678       case Intrinsic::arm_neon_vst2:       NewOpc = AArch64ISD::NEON_ST2_UPD;
3679         NumVecs = 2; isLoad = false; break;
3680       case Intrinsic::arm_neon_vst3:       NewOpc = AArch64ISD::NEON_ST3_UPD;
3681         NumVecs = 3; isLoad = false; break;
3682       case Intrinsic::arm_neon_vst4:       NewOpc = AArch64ISD::NEON_ST4_UPD;
3683         NumVecs = 4; isLoad = false; break;
3684       case Intrinsic::aarch64_neon_vld1x2: NewOpc = AArch64ISD::NEON_LD1x2_UPD;
3685         NumVecs = 2; break;
3686       case Intrinsic::aarch64_neon_vld1x3: NewOpc = AArch64ISD::NEON_LD1x3_UPD;
3687         NumVecs = 3; break;
3688       case Intrinsic::aarch64_neon_vld1x4: NewOpc = AArch64ISD::NEON_LD1x4_UPD;
3689         NumVecs = 4; break;
3690       case Intrinsic::aarch64_neon_vst1x2: NewOpc = AArch64ISD::NEON_ST1x2_UPD;
3691         NumVecs = 2; isLoad = false; break;
3692       case Intrinsic::aarch64_neon_vst1x3: NewOpc = AArch64ISD::NEON_ST1x3_UPD;
3693         NumVecs = 3; isLoad = false; break;
3694       case Intrinsic::aarch64_neon_vst1x4: NewOpc = AArch64ISD::NEON_ST1x4_UPD;
3695         NumVecs = 4; isLoad = false; break;
3696       case Intrinsic::arm_neon_vld2lane:   NewOpc = AArch64ISD::NEON_LD2LN_UPD;
3697         NumVecs = 2; isLaneOp = true; break;
3698       case Intrinsic::arm_neon_vld3lane:   NewOpc = AArch64ISD::NEON_LD3LN_UPD;
3699         NumVecs = 3; isLaneOp = true; break;
3700       case Intrinsic::arm_neon_vld4lane:   NewOpc = AArch64ISD::NEON_LD4LN_UPD;
3701         NumVecs = 4; isLaneOp = true; break;
3702       case Intrinsic::arm_neon_vst2lane:   NewOpc = AArch64ISD::NEON_ST2LN_UPD;
3703         NumVecs = 2; isLoad = false; isLaneOp = true; break;
3704       case Intrinsic::arm_neon_vst3lane:   NewOpc = AArch64ISD::NEON_ST3LN_UPD;
3705         NumVecs = 3; isLoad = false; isLaneOp = true; break;
3706       case Intrinsic::arm_neon_vst4lane:   NewOpc = AArch64ISD::NEON_ST4LN_UPD;
3707         NumVecs = 4; isLoad = false; isLaneOp = true; break;
3708       }
3709     } else {
3710       isLaneOp = true;
3711       switch (N->getOpcode()) {
3712       default: llvm_unreachable("unexpected opcode for Neon base update");
3713       case AArch64ISD::NEON_LD2DUP: NewOpc = AArch64ISD::NEON_LD2DUP_UPD;
3714         NumVecs = 2; break;
3715       case AArch64ISD::NEON_LD3DUP: NewOpc = AArch64ISD::NEON_LD3DUP_UPD;
3716         NumVecs = 3; break;
3717       case AArch64ISD::NEON_LD4DUP: NewOpc = AArch64ISD::NEON_LD4DUP_UPD;
3718         NumVecs = 4; break;
3719       }
3720     }
3721
3722     // Find the size of memory referenced by the load/store.
3723     EVT VecTy;
3724     if (isLoad)
3725       VecTy = N->getValueType(0);
3726     else
3727       VecTy = N->getOperand(AddrOpIdx + 1).getValueType();
3728     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
3729     if (isLaneOp)
3730       NumBytes /= VecTy.getVectorNumElements();
3731
3732     // If the increment is a constant, it must match the memory ref size.
3733     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
3734     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
3735       uint32_t IncVal = CInc->getZExtValue();
3736       if (IncVal != NumBytes)
3737         continue;
3738       Inc = DAG.getTargetConstant(IncVal, MVT::i32);
3739     }
3740
3741     // Create the new updating load/store node.
3742     EVT Tys[6];
3743     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
3744     unsigned n;
3745     for (n = 0; n < NumResultVecs; ++n)
3746       Tys[n] = VecTy;
3747     Tys[n++] = MVT::i64;
3748     Tys[n] = MVT::Other;
3749     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs + 2);
3750     SmallVector<SDValue, 8> Ops;
3751     Ops.push_back(N->getOperand(0)); // incoming chain
3752     Ops.push_back(N->getOperand(AddrOpIdx));
3753     Ops.push_back(Inc);
3754     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
3755       Ops.push_back(N->getOperand(i));
3756     }
3757     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
3758     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
3759                                            Ops.data(), Ops.size(),
3760                                            MemInt->getMemoryVT(),
3761                                            MemInt->getMemOperand());
3762
3763     // Update the uses.
3764     std::vector<SDValue> NewResults;
3765     for (unsigned i = 0; i < NumResultVecs; ++i) {
3766       NewResults.push_back(SDValue(UpdN.getNode(), i));
3767     }
3768     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
3769     DCI.CombineTo(N, NewResults);
3770     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
3771
3772     break;
3773   }
3774   return SDValue();
3775 }
3776
3777 /// For a VDUPLANE node N, check if its source operand is a vldN-lane (N > 1)
3778 /// intrinsic, and if all the other uses of that intrinsic are also VDUPLANEs.
3779 /// If so, combine them to a vldN-dup operation and return true.
3780 static SDValue CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
3781   SelectionDAG &DAG = DCI.DAG;
3782   EVT VT = N->getValueType(0);
3783
3784   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
3785   SDNode *VLD = N->getOperand(0).getNode();
3786   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
3787     return SDValue();
3788   unsigned NumVecs = 0;
3789   unsigned NewOpc = 0;
3790   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
3791   if (IntNo == Intrinsic::arm_neon_vld2lane) {
3792     NumVecs = 2;
3793     NewOpc = AArch64ISD::NEON_LD2DUP;
3794   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
3795     NumVecs = 3;
3796     NewOpc = AArch64ISD::NEON_LD3DUP;
3797   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
3798     NumVecs = 4;
3799     NewOpc = AArch64ISD::NEON_LD4DUP;
3800   } else {
3801     return SDValue();
3802   }
3803
3804   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
3805   // numbers match the load.
3806   unsigned VLDLaneNo =
3807       cast<ConstantSDNode>(VLD->getOperand(NumVecs + 3))->getZExtValue();
3808   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
3809        UI != UE; ++UI) {
3810     // Ignore uses of the chain result.
3811     if (UI.getUse().getResNo() == NumVecs)
3812       continue;
3813     SDNode *User = *UI;
3814     if (User->getOpcode() != AArch64ISD::NEON_VDUPLANE ||
3815         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
3816       return SDValue();
3817   }
3818
3819   // Create the vldN-dup node.
3820   EVT Tys[5];
3821   unsigned n;
3822   for (n = 0; n < NumVecs; ++n)
3823     Tys[n] = VT;
3824   Tys[n] = MVT::Other;
3825   SDVTList SDTys = DAG.getVTList(Tys, NumVecs + 1);
3826   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
3827   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
3828   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, Ops, 2,
3829                                            VLDMemInt->getMemoryVT(),
3830                                            VLDMemInt->getMemOperand());
3831
3832   // Update the uses.
3833   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
3834        UI != UE; ++UI) {
3835     unsigned ResNo = UI.getUse().getResNo();
3836     // Ignore uses of the chain result.
3837     if (ResNo == NumVecs)
3838       continue;
3839     SDNode *User = *UI;
3840     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
3841   }
3842
3843   // Now the vldN-lane intrinsic is dead except for its chain result.
3844   // Update uses of the chain.
3845   std::vector<SDValue> VLDDupResults;
3846   for (unsigned n = 0; n < NumVecs; ++n)
3847     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
3848   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
3849   DCI.CombineTo(VLD, VLDDupResults);
3850
3851   return SDValue(N, 0);
3852 }
3853
3854 SDValue
3855 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
3856                                          DAGCombinerInfo &DCI) const {
3857   switch (N->getOpcode()) {
3858   default: break;
3859   case ISD::AND: return PerformANDCombine(N, DCI);
3860   case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
3861   case ISD::SHL:
3862   case ISD::SRA:
3863   case ISD::SRL:
3864     return PerformShiftCombine(N, DCI, getSubtarget());
3865   case ISD::INTRINSIC_WO_CHAIN:
3866     return PerformIntrinsicCombine(N, DCI.DAG);
3867   case AArch64ISD::NEON_VDUPLANE:
3868     return CombineVLDDUP(N, DCI);
3869   case AArch64ISD::NEON_LD2DUP:
3870   case AArch64ISD::NEON_LD3DUP:
3871   case AArch64ISD::NEON_LD4DUP:
3872     return CombineBaseUpdate(N, DCI);
3873   case ISD::INTRINSIC_VOID:
3874   case ISD::INTRINSIC_W_CHAIN:
3875     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
3876     case Intrinsic::arm_neon_vld1:
3877     case Intrinsic::arm_neon_vld2:
3878     case Intrinsic::arm_neon_vld3:
3879     case Intrinsic::arm_neon_vld4:
3880     case Intrinsic::arm_neon_vst1:
3881     case Intrinsic::arm_neon_vst2:
3882     case Intrinsic::arm_neon_vst3:
3883     case Intrinsic::arm_neon_vst4:
3884     case Intrinsic::arm_neon_vld2lane:
3885     case Intrinsic::arm_neon_vld3lane:
3886     case Intrinsic::arm_neon_vld4lane:
3887     case Intrinsic::aarch64_neon_vld1x2:
3888     case Intrinsic::aarch64_neon_vld1x3:
3889     case Intrinsic::aarch64_neon_vld1x4:
3890     case Intrinsic::aarch64_neon_vst1x2:
3891     case Intrinsic::aarch64_neon_vst1x3:
3892     case Intrinsic::aarch64_neon_vst1x4:
3893     case Intrinsic::arm_neon_vst2lane:
3894     case Intrinsic::arm_neon_vst3lane:
3895     case Intrinsic::arm_neon_vst4lane:
3896       return CombineBaseUpdate(N, DCI);
3897     default:
3898       break;
3899     }
3900   }
3901   return SDValue();
3902 }
3903
3904 bool
3905 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3906   VT = VT.getScalarType();
3907
3908   if (!VT.isSimple())
3909     return false;
3910
3911   switch (VT.getSimpleVT().SimpleTy) {
3912   case MVT::f16:
3913   case MVT::f32:
3914   case MVT::f64:
3915     return true;
3916   case MVT::f128:
3917     return false;
3918   default:
3919     break;
3920   }
3921
3922   return false;
3923 }
3924
3925 // Check whether a Build Vector could be presented as Shuffle Vector. If yes,
3926 // try to call LowerVECTOR_SHUFFLE to lower it.
3927 bool AArch64TargetLowering::isKnownShuffleVector(SDValue Op, SelectionDAG &DAG,
3928                                                  SDValue &Res) const {
3929   SDLoc DL(Op);
3930   EVT VT = Op.getValueType();
3931   unsigned NumElts = VT.getVectorNumElements();
3932   unsigned V0NumElts = 0;
3933   int Mask[16];
3934   SDValue V0, V1;
3935
3936   // Check if all elements are extracted from less than 3 vectors.
3937   for (unsigned i = 0; i < NumElts; ++i) {
3938     SDValue Elt = Op.getOperand(i);
3939     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
3940       return false;
3941
3942     if (V0.getNode() == 0) {
3943       V0 = Elt.getOperand(0);
3944       V0NumElts = V0.getValueType().getVectorNumElements();
3945     }
3946     if (Elt.getOperand(0) == V0) {
3947       Mask[i] = (cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue());
3948       continue;
3949     } else if (V1.getNode() == 0) {
3950       V1 = Elt.getOperand(0);
3951     }
3952     if (Elt.getOperand(0) == V1) {
3953       unsigned Lane = cast<ConstantSDNode>(Elt->getOperand(1))->getZExtValue();
3954       Mask[i] = (Lane + V0NumElts);
3955       continue;
3956     } else {
3957       return false;
3958     }
3959   }
3960
3961   if (!V1.getNode() && V0NumElts == NumElts * 2) {
3962     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
3963                      DAG.getConstant(NumElts, MVT::i64));
3964     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V0,
3965                      DAG.getConstant(0, MVT::i64));
3966     V0NumElts = V0.getValueType().getVectorNumElements();
3967   }
3968
3969   if (V1.getNode() && NumElts == V0NumElts &&
3970       V0NumElts == V1.getValueType().getVectorNumElements()) {
3971     SDValue Shuffle = DAG.getVectorShuffle(VT, DL, V0, V1, Mask);
3972     if(Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
3973       Res = Shuffle;
3974     else
3975       Res = LowerVECTOR_SHUFFLE(Shuffle, DAG);
3976     return true;
3977   } else
3978     return false;
3979 }
3980
3981 // If this is a case we can't handle, return null and let the default
3982 // expansion code take care of it.
3983 SDValue
3984 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3985                                          const AArch64Subtarget *ST) const {
3986
3987   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3988   SDLoc DL(Op);
3989   EVT VT = Op.getValueType();
3990
3991   APInt SplatBits, SplatUndef;
3992   unsigned SplatBitSize;
3993   bool HasAnyUndefs;
3994
3995   unsigned UseNeonMov = VT.getSizeInBits() >= 64;
3996
3997   // Note we favor lowering MOVI over MVNI.
3998   // This has implications on the definition of patterns in TableGen to select
3999   // BIC immediate instructions but not ORR immediate instructions.
4000   // If this lowering order is changed, TableGen patterns for BIC immediate and
4001   // ORR immediate instructions have to be updated.
4002   if (UseNeonMov &&
4003       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4004     if (SplatBitSize <= 64) {
4005       // First attempt to use vector immediate-form MOVI
4006       EVT NeonMovVT;
4007       unsigned Imm = 0;
4008       unsigned OpCmode = 0;
4009
4010       if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
4011                             SplatBitSize, DAG, VT.is128BitVector(),
4012                             Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
4013         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4014         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4015
4016         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4017           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
4018                                         ImmVal, OpCmodeVal);
4019           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4020         }
4021       }
4022
4023       // Then attempt to use vector immediate-form MVNI
4024       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4025       if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
4026                             DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
4027                             Imm, OpCmode)) {
4028         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
4029         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
4030         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
4031           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
4032                                         ImmVal, OpCmodeVal);
4033           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
4034         }
4035       }
4036
4037       // Attempt to use vector immediate-form FMOV
4038       if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
4039           (VT == MVT::v2f64 && SplatBitSize == 64)) {
4040         APFloat RealVal(
4041             SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
4042             SplatBits);
4043         uint32_t ImmVal;
4044         if (A64Imms::isFPImm(RealVal, ImmVal)) {
4045           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4046           return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
4047         }
4048       }
4049     }
4050   }
4051
4052   unsigned NumElts = VT.getVectorNumElements();
4053   bool isOnlyLowElement = true;
4054   bool usesOnlyOneValue = true;
4055   bool hasDominantValue = false;
4056   bool isConstant = true;
4057
4058   // Map of the number of times a particular SDValue appears in the
4059   // element list.
4060   DenseMap<SDValue, unsigned> ValueCounts;
4061   SDValue Value;
4062   for (unsigned i = 0; i < NumElts; ++i) {
4063     SDValue V = Op.getOperand(i);
4064     if (V.getOpcode() == ISD::UNDEF)
4065       continue;
4066     if (i > 0)
4067       isOnlyLowElement = false;
4068     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4069       isConstant = false;
4070
4071     ValueCounts.insert(std::make_pair(V, 0));
4072     unsigned &Count = ValueCounts[V];
4073
4074     // Is this value dominant? (takes up more than half of the lanes)
4075     if (++Count > (NumElts / 2)) {
4076       hasDominantValue = true;
4077       Value = V;
4078     }
4079   }
4080   if (ValueCounts.size() != 1)
4081     usesOnlyOneValue = false;
4082   if (!Value.getNode() && ValueCounts.size() > 0)
4083     Value = ValueCounts.begin()->first;
4084
4085   if (ValueCounts.size() == 0)
4086     return DAG.getUNDEF(VT);
4087
4088   if (isOnlyLowElement)
4089     return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4090
4091   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4092   if (hasDominantValue && EltSize <= 64) {
4093     // Use VDUP for non-constant splats.
4094     if (!isConstant) {
4095       SDValue N;
4096
4097       // If we are DUPing a value that comes directly from a vector, we could
4098       // just use DUPLANE. We can only do this if the lane being extracted
4099       // is at a constant index, as the DUP from lane instructions only have
4100       // constant-index forms.
4101       // FIXME: for now we have v1i8, v1i16, v1i32 legal vector types, if they
4102       // are not legal any more, no need to check the type size in bits should
4103       // be large than 64.
4104       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4105           isa<ConstantSDNode>(Value->getOperand(1)) &&
4106           Value->getOperand(0).getValueType().getSizeInBits() >= 64) {
4107           N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT,
4108                         Value->getOperand(0), Value->getOperand(1));
4109       } else
4110         N = DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4111
4112       if (!usesOnlyOneValue) {
4113         // The dominant value was splatted as 'N', but we now have to insert
4114         // all differing elements.
4115         for (unsigned I = 0; I < NumElts; ++I) {
4116           if (Op.getOperand(I) == Value)
4117             continue;
4118           SmallVector<SDValue, 3> Ops;
4119           Ops.push_back(N);
4120           Ops.push_back(Op.getOperand(I));
4121           Ops.push_back(DAG.getConstant(I, MVT::i64));
4122           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, &Ops[0], 3);
4123         }
4124       }
4125       return N;
4126     }
4127     if (usesOnlyOneValue && isConstant) {
4128       return DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
4129     }
4130   }
4131   // If all elements are constants and the case above didn't get hit, fall back
4132   // to the default expansion, which will generate a load from the constant
4133   // pool.
4134   if (isConstant)
4135     return SDValue();
4136
4137   // Try to lower this in lowering ShuffleVector way.
4138   SDValue Shuf;
4139   if (isKnownShuffleVector(Op, DAG, Shuf))
4140     return Shuf;
4141
4142   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4143   // know the default expansion would otherwise fall back on something even
4144   // worse. For a vector with one or two non-undef values, that's
4145   // scalar_to_vector for the elements followed by a shuffle (provided the
4146   // shuffle is valid for the target) and materialization element by element
4147   // on the stack followed by a load for everything else.
4148   if (!isConstant && !usesOnlyOneValue) {
4149     SDValue Vec = DAG.getUNDEF(VT);
4150     for (unsigned i = 0 ; i < NumElts; ++i) {
4151       SDValue V = Op.getOperand(i);
4152       if (V.getOpcode() == ISD::UNDEF)
4153         continue;
4154       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
4155       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, LaneIdx);
4156     }
4157     return Vec;
4158   }
4159   return SDValue();
4160 }
4161
4162 /// isREVMask - Check if a vector shuffle corresponds to a REV
4163 /// instruction with the specified blocksize.  (The order of the elements
4164 /// within each block of the vector is reversed.)
4165 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4166   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4167          "Only possible block sizes for REV are: 16, 32, 64");
4168
4169   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4170   if (EltSz == 64)
4171     return false;
4172
4173   unsigned NumElts = VT.getVectorNumElements();
4174   unsigned BlockElts = M[0] + 1;
4175   // If the first shuffle index is UNDEF, be optimistic.
4176   if (M[0] < 0)
4177     BlockElts = BlockSize / EltSz;
4178
4179   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4180     return false;
4181
4182   for (unsigned i = 0; i < NumElts; ++i) {
4183     if (M[i] < 0)
4184       continue; // ignore UNDEF indices
4185     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4186       return false;
4187   }
4188
4189   return true;
4190 }
4191
4192 // isPermuteMask - Check whether the vector shuffle matches to UZP, ZIP and
4193 // TRN instruction.
4194 static unsigned isPermuteMask(ArrayRef<int> M, EVT VT) {
4195   unsigned NumElts = VT.getVectorNumElements();
4196   if (NumElts < 4)
4197     return 0;
4198
4199   bool ismatch = true;
4200
4201   // Check UZP1
4202   for (unsigned i = 0; i < NumElts; ++i) {
4203     if ((unsigned)M[i] != i * 2) {
4204       ismatch = false;
4205       break;
4206     }
4207   }
4208   if (ismatch)
4209     return AArch64ISD::NEON_UZP1;
4210
4211   // Check UZP2
4212   ismatch = true;
4213   for (unsigned i = 0; i < NumElts; ++i) {
4214     if ((unsigned)M[i] != i * 2 + 1) {
4215       ismatch = false;
4216       break;
4217     }
4218   }
4219   if (ismatch)
4220     return AArch64ISD::NEON_UZP2;
4221
4222   // Check ZIP1
4223   ismatch = true;
4224   for (unsigned i = 0; i < NumElts; ++i) {
4225     if ((unsigned)M[i] != i / 2 + NumElts * (i % 2)) {
4226       ismatch = false;
4227       break;
4228     }
4229   }
4230   if (ismatch)
4231     return AArch64ISD::NEON_ZIP1;
4232
4233   // Check ZIP2
4234   ismatch = true;
4235   for (unsigned i = 0; i < NumElts; ++i) {
4236     if ((unsigned)M[i] != (NumElts + i) / 2 + NumElts * (i % 2)) {
4237       ismatch = false;
4238       break;
4239     }
4240   }
4241   if (ismatch)
4242     return AArch64ISD::NEON_ZIP2;
4243
4244   // Check TRN1
4245   ismatch = true;
4246   for (unsigned i = 0; i < NumElts; ++i) {
4247     if ((unsigned)M[i] != i + (NumElts - 1) * (i % 2)) {
4248       ismatch = false;
4249       break;
4250     }
4251   }
4252   if (ismatch)
4253     return AArch64ISD::NEON_TRN1;
4254
4255   // Check TRN2
4256   ismatch = true;
4257   for (unsigned i = 0; i < NumElts; ++i) {
4258     if ((unsigned)M[i] != 1 + i + (NumElts - 1) * (i % 2)) {
4259       ismatch = false;
4260       break;
4261     }
4262   }
4263   if (ismatch)
4264     return AArch64ISD::NEON_TRN2;
4265
4266   return 0;
4267 }
4268
4269 SDValue
4270 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4271                                            SelectionDAG &DAG) const {
4272   SDValue V1 = Op.getOperand(0);
4273   SDValue V2 = Op.getOperand(1);
4274   SDLoc dl(Op);
4275   EVT VT = Op.getValueType();
4276   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4277
4278   // Convert shuffles that are directly supported on NEON to target-specific
4279   // DAG nodes, instead of keeping them as shuffles and matching them again
4280   // during code selection.  This is more efficient and avoids the possibility
4281   // of inconsistencies between legalization and selection.
4282   ArrayRef<int> ShuffleMask = SVN->getMask();
4283
4284   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4285   if (EltSize > 64)
4286     return SDValue();
4287
4288   if (isREVMask(ShuffleMask, VT, 64))
4289     return DAG.getNode(AArch64ISD::NEON_REV64, dl, VT, V1);
4290   if (isREVMask(ShuffleMask, VT, 32))
4291     return DAG.getNode(AArch64ISD::NEON_REV32, dl, VT, V1);
4292   if (isREVMask(ShuffleMask, VT, 16))
4293     return DAG.getNode(AArch64ISD::NEON_REV16, dl, VT, V1);
4294
4295   unsigned ISDNo = isPermuteMask(ShuffleMask, VT);
4296   if (ISDNo)
4297     return DAG.getNode(ISDNo, dl, VT, V1, V2);
4298
4299   // If the element of shuffle mask are all the same constant, we can
4300   // transform it into either NEON_VDUP or NEON_VDUPLANE
4301   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4302     int Lane = SVN->getSplatIndex();
4303     // If this is undef splat, generate it via "just" vdup, if possible.
4304     if (Lane == -1) Lane = 0;
4305
4306     // Test if V1 is a SCALAR_TO_VECTOR.
4307     if (V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4308       return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT, V1.getOperand(0));
4309     }
4310     // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR.
4311     if (V1.getOpcode() == ISD::BUILD_VECTOR) {
4312       bool IsScalarToVector = true;
4313       for (unsigned i = 0, e = V1.getNumOperands(); i != e; ++i)
4314         if (V1.getOperand(i).getOpcode() != ISD::UNDEF &&
4315             i != (unsigned)Lane) {
4316           IsScalarToVector = false;
4317           break;
4318         }
4319       if (IsScalarToVector)
4320         return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT,
4321                            V1.getOperand(Lane));
4322     }
4323
4324     // Test if V1 is a EXTRACT_SUBVECTOR.
4325     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4326       int ExtLane = cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4327       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1.getOperand(0),
4328                          DAG.getConstant(Lane + ExtLane, MVT::i64));
4329     }
4330     // Test if V1 is a CONCAT_VECTORS.
4331     if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
4332         V1.getOperand(1).getOpcode() == ISD::UNDEF) {
4333       SDValue Op0 = V1.getOperand(0);
4334       assert((unsigned)Lane < Op0.getValueType().getVectorNumElements() &&
4335              "Invalid vector lane access");
4336       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, Op0,
4337                          DAG.getConstant(Lane, MVT::i64));
4338     }
4339
4340     return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
4341                        DAG.getConstant(Lane, MVT::i64));
4342   }
4343
4344   int Length = ShuffleMask.size();
4345   int V1EltNum = V1.getValueType().getVectorNumElements();
4346
4347   // If the number of v1 elements is the same as the number of shuffle mask
4348   // element and the shuffle masks are sequential values, we can transform
4349   // it into NEON_VEXTRACT.
4350   if (V1EltNum == Length) {
4351     // Check if the shuffle mask is sequential.
4352     bool IsSequential = true;
4353     int CurMask = ShuffleMask[0];
4354     for (int I = 0; I < Length; ++I) {
4355       if (ShuffleMask[I] != CurMask) {
4356         IsSequential = false;
4357         break;
4358       }
4359       CurMask++;
4360     }
4361     if (IsSequential) {
4362       assert((EltSize % 8 == 0) && "Bitsize of vector element is incorrect");
4363       unsigned VecSize = EltSize * V1EltNum;
4364       unsigned Index = (EltSize/8) * ShuffleMask[0];
4365       if (VecSize == 64 || VecSize == 128)
4366         return DAG.getNode(AArch64ISD::NEON_VEXTRACT, dl, VT, V1, V2,
4367                            DAG.getConstant(Index, MVT::i64));
4368     }
4369   }
4370
4371   // For shuffle mask like "0, 1, 2, 3, 4, 5, 13, 7", try to generate insert
4372   // by element from V2 to V1 .
4373   // If shuffle mask is like "0, 1, 10, 11, 12, 13, 14, 15", V2 would be a
4374   // better choice to be inserted than V1 as less insert needed, so we count
4375   // element to be inserted for both V1 and V2, and select less one as insert
4376   // target.
4377
4378   // Collect elements need to be inserted and their index.
4379   SmallVector<int, 8> NV1Elt;
4380   SmallVector<int, 8> N1Index;
4381   SmallVector<int, 8> NV2Elt;
4382   SmallVector<int, 8> N2Index;
4383   for (int I = 0; I != Length; ++I) {
4384     if (ShuffleMask[I] != I) {
4385       NV1Elt.push_back(ShuffleMask[I]);
4386       N1Index.push_back(I);
4387     }
4388   }
4389   for (int I = 0; I != Length; ++I) {
4390     if (ShuffleMask[I] != (I + V1EltNum)) {
4391       NV2Elt.push_back(ShuffleMask[I]);
4392       N2Index.push_back(I);
4393     }
4394   }
4395
4396   // Decide which to be inserted. If all lanes mismatch, neither V1 nor V2
4397   // will be inserted.
4398   SDValue InsV = V1;
4399   SmallVector<int, 8> InsMasks = NV1Elt;
4400   SmallVector<int, 8> InsIndex = N1Index;
4401   if ((int)NV1Elt.size() != Length || (int)NV2Elt.size() != Length) {
4402     if (NV1Elt.size() > NV2Elt.size()) {
4403       InsV = V2;
4404       InsMasks = NV2Elt;
4405       InsIndex = N2Index;
4406     }
4407   } else {
4408     InsV = DAG.getNode(ISD::UNDEF, dl, VT);
4409   }
4410
4411   for (int I = 0, E = InsMasks.size(); I != E; ++I) {
4412     SDValue ExtV = V1;
4413     int Mask = InsMasks[I];
4414     if (Mask >= V1EltNum) {
4415       ExtV = V2;
4416       Mask -= V1EltNum;
4417     }
4418     // Any value type smaller than i32 is illegal in AArch64, and this lower
4419     // function is called after legalize pass, so we need to legalize
4420     // the result here.
4421     EVT EltVT;
4422     if (VT.getVectorElementType().isFloatingPoint())
4423       EltVT = (EltSize == 64) ? MVT::f64 : MVT::f32;
4424     else
4425       EltVT = (EltSize == 64) ? MVT::i64 : MVT::i32;
4426
4427     if (Mask >= 0) {
4428       ExtV = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ExtV,
4429                          DAG.getConstant(Mask, MVT::i64));
4430       InsV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, InsV, ExtV,
4431                          DAG.getConstant(InsIndex[I], MVT::i64));
4432     }
4433   }
4434   return InsV;
4435 }
4436
4437 AArch64TargetLowering::ConstraintType
4438 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4439   if (Constraint.size() == 1) {
4440     switch (Constraint[0]) {
4441     default: break;
4442     case 'w': // An FP/SIMD vector register
4443       return C_RegisterClass;
4444     case 'I': // Constant that can be used with an ADD instruction
4445     case 'J': // Constant that can be used with a SUB instruction
4446     case 'K': // Constant that can be used with a 32-bit logical instruction
4447     case 'L': // Constant that can be used with a 64-bit logical instruction
4448     case 'M': // Constant that can be used as a 32-bit MOV immediate
4449     case 'N': // Constant that can be used as a 64-bit MOV immediate
4450     case 'Y': // Floating point constant zero
4451     case 'Z': // Integer constant zero
4452       return C_Other;
4453     case 'Q': // A memory reference with base register and no offset
4454       return C_Memory;
4455     case 'S': // A symbolic address
4456       return C_Other;
4457     }
4458   }
4459
4460   // FIXME: Ump, Utf, Usa, Ush
4461   // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
4462   //      whatever they may be
4463   // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
4464   // Usa: An absolute symbolic address
4465   // Ush: The high part (bits 32:12) of a pc-relative symbolic address
4466   assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
4467          && Constraint != "Ush" && "Unimplemented constraints");
4468
4469   return TargetLowering::getConstraintType(Constraint);
4470 }
4471
4472 TargetLowering::ConstraintWeight
4473 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
4474                                                 const char *Constraint) const {
4475
4476   llvm_unreachable("Constraint weight unimplemented");
4477 }
4478
4479 void
4480 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4481                                                     std::string &Constraint,
4482                                                     std::vector<SDValue> &Ops,
4483                                                     SelectionDAG &DAG) const {
4484   SDValue Result(0, 0);
4485
4486   // Only length 1 constraints are C_Other.
4487   if (Constraint.size() != 1) return;
4488
4489   // Only C_Other constraints get lowered like this. That means constants for us
4490   // so return early if there's no hope the constraint can be lowered.
4491
4492   switch(Constraint[0]) {
4493   default: break;
4494   case 'I': case 'J': case 'K': case 'L':
4495   case 'M': case 'N': case 'Z': {
4496     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4497     if (!C)
4498       return;
4499
4500     uint64_t CVal = C->getZExtValue();
4501     uint32_t Bits;
4502
4503     switch (Constraint[0]) {
4504     default:
4505       // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
4506       // is a peculiarly useless SUB constraint.
4507       llvm_unreachable("Unimplemented C_Other constraint");
4508     case 'I':
4509       if (CVal <= 0xfff)
4510         break;
4511       return;
4512     case 'K':
4513       if (A64Imms::isLogicalImm(32, CVal, Bits))
4514         break;
4515       return;
4516     case 'L':
4517       if (A64Imms::isLogicalImm(64, CVal, Bits))
4518         break;
4519       return;
4520     case 'Z':
4521       if (CVal == 0)
4522         break;
4523       return;
4524     }
4525
4526     Result = DAG.getTargetConstant(CVal, Op.getValueType());
4527     break;
4528   }
4529   case 'S': {
4530     // An absolute symbolic address or label reference.
4531     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4532       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4533                                           GA->getValueType(0));
4534     } else if (const BlockAddressSDNode *BA
4535                  = dyn_cast<BlockAddressSDNode>(Op)) {
4536       Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
4537                                          BA->getValueType(0));
4538     } else if (const ExternalSymbolSDNode *ES
4539                  = dyn_cast<ExternalSymbolSDNode>(Op)) {
4540       Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
4541                                            ES->getValueType(0));
4542     } else
4543       return;
4544     break;
4545   }
4546   case 'Y':
4547     if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
4548       if (CFP->isExactlyValue(0.0)) {
4549         Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
4550         break;
4551       }
4552     }
4553     return;
4554   }
4555
4556   if (Result.getNode()) {
4557     Ops.push_back(Result);
4558     return;
4559   }
4560
4561   // It's an unknown constraint for us. Let generic code have a go.
4562   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4563 }
4564
4565 std::pair<unsigned, const TargetRegisterClass*>
4566 AArch64TargetLowering::getRegForInlineAsmConstraint(
4567                                                   const std::string &Constraint,
4568                                                   MVT VT) const {
4569   if (Constraint.size() == 1) {
4570     switch (Constraint[0]) {
4571     case 'r':
4572       if (VT.getSizeInBits() <= 32)
4573         return std::make_pair(0U, &AArch64::GPR32RegClass);
4574       else if (VT == MVT::i64)
4575         return std::make_pair(0U, &AArch64::GPR64RegClass);
4576       break;
4577     case 'w':
4578       if (VT == MVT::f16)
4579         return std::make_pair(0U, &AArch64::FPR16RegClass);
4580       else if (VT == MVT::f32)
4581         return std::make_pair(0U, &AArch64::FPR32RegClass);
4582       else if (VT.getSizeInBits() == 64)
4583         return std::make_pair(0U, &AArch64::FPR64RegClass);
4584       else if (VT.getSizeInBits() == 128)
4585         return std::make_pair(0U, &AArch64::FPR128RegClass);
4586       break;
4587     }
4588   }
4589
4590   // Use the default implementation in TargetLowering to convert the register
4591   // constraint into a member of a register class.
4592   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4593 }
4594
4595 /// Represent NEON load and store intrinsics as MemIntrinsicNodes.
4596 /// The associated MachineMemOperands record the alignment specified
4597 /// in the intrinsic calls.
4598 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4599                                                const CallInst &I,
4600                                                unsigned Intrinsic) const {
4601   switch (Intrinsic) {
4602   case Intrinsic::arm_neon_vld1:
4603   case Intrinsic::arm_neon_vld2:
4604   case Intrinsic::arm_neon_vld3:
4605   case Intrinsic::arm_neon_vld4:
4606   case Intrinsic::aarch64_neon_vld1x2:
4607   case Intrinsic::aarch64_neon_vld1x3:
4608   case Intrinsic::aarch64_neon_vld1x4:
4609   case Intrinsic::arm_neon_vld2lane:
4610   case Intrinsic::arm_neon_vld3lane:
4611   case Intrinsic::arm_neon_vld4lane: {
4612     Info.opc = ISD::INTRINSIC_W_CHAIN;
4613     // Conservatively set memVT to the entire set of vectors loaded.
4614     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
4615     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
4616     Info.ptrVal = I.getArgOperand(0);
4617     Info.offset = 0;
4618     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
4619     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
4620     Info.vol = false; // volatile loads with NEON intrinsics not supported
4621     Info.readMem = true;
4622     Info.writeMem = false;
4623     return true;
4624   }
4625   case Intrinsic::arm_neon_vst1:
4626   case Intrinsic::arm_neon_vst2:
4627   case Intrinsic::arm_neon_vst3:
4628   case Intrinsic::arm_neon_vst4:
4629   case Intrinsic::aarch64_neon_vst1x2:
4630   case Intrinsic::aarch64_neon_vst1x3:
4631   case Intrinsic::aarch64_neon_vst1x4:
4632   case Intrinsic::arm_neon_vst2lane:
4633   case Intrinsic::arm_neon_vst3lane:
4634   case Intrinsic::arm_neon_vst4lane: {
4635     Info.opc = ISD::INTRINSIC_VOID;
4636     // Conservatively set memVT to the entire set of vectors stored.
4637     unsigned NumElts = 0;
4638     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
4639       Type *ArgTy = I.getArgOperand(ArgI)->getType();
4640       if (!ArgTy->isVectorTy())
4641         break;
4642       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
4643     }
4644     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
4645     Info.ptrVal = I.getArgOperand(0);
4646     Info.offset = 0;
4647     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
4648     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
4649     Info.vol = false; // volatile stores with NEON intrinsics not supported
4650     Info.readMem = false;
4651     Info.writeMem = true;
4652     return true;
4653   }
4654   default:
4655     break;
4656   }
4657
4658   return false;
4659 }