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