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