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