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