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