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