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