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