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