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