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