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