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