1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that AArch64 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "aarch64-isel"
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"
32 static TargetLoweringObjectFile *createTLOF(AArch64TargetMachine &TM) {
33 const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
35 if (Subtarget->isTargetLinux())
36 return new AArch64LinuxTargetObjectFile();
37 if (Subtarget->isTargetELF())
38 return new TargetLoweringObjectFileELF();
39 llvm_unreachable("unknown subtarget type");
42 AArch64TargetLowering::AArch64TargetLowering(AArch64TargetMachine &TM)
43 : TargetLowering(TM, createTLOF(TM)), Itins(TM.getInstrItineraryData()) {
45 const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
47 // SIMD compares set the entire lane's bits to 1
48 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
50 // Scalar register <-> type mapping
51 addRegisterClass(MVT::i32, &AArch64::GPR32RegClass);
52 addRegisterClass(MVT::i64, &AArch64::GPR64RegClass);
53 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
54 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
55 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
56 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
58 if (Subtarget->hasNEON()) {
60 addRegisterClass(MVT::v1i8, &AArch64::FPR8RegClass);
61 addRegisterClass(MVT::v1i16, &AArch64::FPR16RegClass);
62 addRegisterClass(MVT::v1i32, &AArch64::FPR32RegClass);
63 addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
64 addRegisterClass(MVT::v1f32, &AArch64::FPR32RegClass);
65 addRegisterClass(MVT::v1f64, &AArch64::FPR64RegClass);
66 addRegisterClass(MVT::v8i8, &AArch64::FPR64RegClass);
67 addRegisterClass(MVT::v4i16, &AArch64::FPR64RegClass);
68 addRegisterClass(MVT::v2i32, &AArch64::FPR64RegClass);
69 addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
70 addRegisterClass(MVT::v2f32, &AArch64::FPR64RegClass);
71 addRegisterClass(MVT::v16i8, &AArch64::FPR128RegClass);
72 addRegisterClass(MVT::v8i16, &AArch64::FPR128RegClass);
73 addRegisterClass(MVT::v4i32, &AArch64::FPR128RegClass);
74 addRegisterClass(MVT::v2i64, &AArch64::FPR128RegClass);
75 addRegisterClass(MVT::v4f32, &AArch64::FPR128RegClass);
76 addRegisterClass(MVT::v2f64, &AArch64::FPR128RegClass);
79 computeRegisterProperties();
81 // We combine OR nodes for bitfield and NEON BSL operations.
82 setTargetDAGCombine(ISD::OR);
84 setTargetDAGCombine(ISD::AND);
85 setTargetDAGCombine(ISD::SRA);
86 setTargetDAGCombine(ISD::SRL);
87 setTargetDAGCombine(ISD::SHL);
89 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
91 // AArch64 does not have i1 loads, or much of anything for i1 really.
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
94 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
96 setStackPointerRegisterToSaveRestore(AArch64::XSP);
97 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
98 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
99 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
101 // We'll lower globals to wrappers for selection.
102 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
103 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
105 // A64 instructions have the comparison predicate attached to the user of the
106 // result, but having a separate comparison is valuable for matching.
107 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
108 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
109 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
110 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
112 setOperationAction(ISD::SELECT, MVT::i32, Custom);
113 setOperationAction(ISD::SELECT, MVT::i64, Custom);
114 setOperationAction(ISD::SELECT, MVT::f32, Custom);
115 setOperationAction(ISD::SELECT, MVT::f64, Custom);
117 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
118 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
119 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
120 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
122 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
124 setOperationAction(ISD::SETCC, MVT::i32, Custom);
125 setOperationAction(ISD::SETCC, MVT::i64, Custom);
126 setOperationAction(ISD::SETCC, MVT::f32, Custom);
127 setOperationAction(ISD::SETCC, MVT::f64, Custom);
129 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
130 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133 setOperationAction(ISD::VASTART, MVT::Other, Custom);
134 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
135 setOperationAction(ISD::VAEND, MVT::Other, Expand);
136 setOperationAction(ISD::VAARG, MVT::Other, Expand);
138 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
140 setOperationAction(ISD::ROTL, MVT::i32, Expand);
141 setOperationAction(ISD::ROTL, MVT::i64, Expand);
143 setOperationAction(ISD::UREM, MVT::i32, Expand);
144 setOperationAction(ISD::UREM, MVT::i64, Expand);
145 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
146 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
148 setOperationAction(ISD::SREM, MVT::i32, Expand);
149 setOperationAction(ISD::SREM, MVT::i64, Expand);
150 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
151 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
153 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
154 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
156 // Legal floating-point operations.
157 setOperationAction(ISD::FABS, MVT::f32, Legal);
158 setOperationAction(ISD::FABS, MVT::f64, Legal);
160 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
161 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
163 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
164 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
166 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
167 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
169 setOperationAction(ISD::FNEG, MVT::f32, Legal);
170 setOperationAction(ISD::FNEG, MVT::f64, Legal);
172 setOperationAction(ISD::FRINT, MVT::f32, Legal);
173 setOperationAction(ISD::FRINT, MVT::f64, Legal);
175 setOperationAction(ISD::FSQRT, MVT::f32, Legal);
176 setOperationAction(ISD::FSQRT, MVT::f64, Legal);
178 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
179 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
181 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
182 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
183 setOperationAction(ISD::ConstantFP, MVT::f128, Legal);
185 // Illegal floating-point operations.
186 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
187 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
189 setOperationAction(ISD::FCOS, MVT::f32, Expand);
190 setOperationAction(ISD::FCOS, MVT::f64, Expand);
192 setOperationAction(ISD::FEXP, MVT::f32, Expand);
193 setOperationAction(ISD::FEXP, MVT::f64, Expand);
195 setOperationAction(ISD::FEXP2, MVT::f32, Expand);
196 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
198 setOperationAction(ISD::FLOG, MVT::f32, Expand);
199 setOperationAction(ISD::FLOG, MVT::f64, Expand);
201 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
202 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
204 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
205 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
207 setOperationAction(ISD::FPOW, MVT::f32, Expand);
208 setOperationAction(ISD::FPOW, MVT::f64, Expand);
210 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
211 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
213 setOperationAction(ISD::FREM, MVT::f32, Expand);
214 setOperationAction(ISD::FREM, MVT::f64, Expand);
216 setOperationAction(ISD::FSIN, MVT::f32, Expand);
217 setOperationAction(ISD::FSIN, MVT::f64, Expand);
219 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
220 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
222 // Virtually no operation on f128 is legal, but LLVM can't expand them when
223 // there's a valid register class, so we need custom operations in most cases.
224 setOperationAction(ISD::FABS, MVT::f128, Expand);
225 setOperationAction(ISD::FADD, MVT::f128, Custom);
226 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
227 setOperationAction(ISD::FCOS, MVT::f128, Expand);
228 setOperationAction(ISD::FDIV, MVT::f128, Custom);
229 setOperationAction(ISD::FMA, MVT::f128, Expand);
230 setOperationAction(ISD::FMUL, MVT::f128, Custom);
231 setOperationAction(ISD::FNEG, MVT::f128, Expand);
232 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
233 setOperationAction(ISD::FP_ROUND, MVT::f128, Expand);
234 setOperationAction(ISD::FPOW, MVT::f128, Expand);
235 setOperationAction(ISD::FREM, MVT::f128, Expand);
236 setOperationAction(ISD::FRINT, MVT::f128, Expand);
237 setOperationAction(ISD::FSIN, MVT::f128, Expand);
238 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
239 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
240 setOperationAction(ISD::FSUB, MVT::f128, Custom);
241 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
242 setOperationAction(ISD::SETCC, MVT::f128, Custom);
243 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
244 setOperationAction(ISD::SELECT, MVT::f128, Expand);
245 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
246 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
248 // Lowering for many of the conversions is actually specified by the non-f128
249 // type. The LowerXXX function will be trivial when f128 isn't involved.
250 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
251 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
252 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
253 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
254 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
255 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
257 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
258 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
259 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
260 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
261 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
262 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
263 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
265 // This prevents LLVM trying to compress double constants into a floating
266 // constant-pool entry and trying to load from there. It's of doubtful benefit
267 // for A64: we'd need LDR followed by FCVT, I believe.
268 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
269 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
270 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
272 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
273 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
274 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
275 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
276 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
277 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
279 setExceptionPointerRegister(AArch64::X0);
280 setExceptionSelectorRegister(AArch64::X1);
282 if (Subtarget->hasNEON()) {
283 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i8, Custom);
284 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
285 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
286 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i16, Custom);
287 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
288 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
289 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i32, Custom);
290 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
291 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
292 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
293 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
294 setOperationAction(ISD::BUILD_VECTOR, MVT::v1f32, Custom);
295 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
296 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
297 setOperationAction(ISD::BUILD_VECTOR, MVT::v1f64, Custom);
298 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
300 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
301 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
302 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
303 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
304 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
305 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i32, Custom);
306 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f32, Custom);
309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1f64, Custom);
311 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
313 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Legal);
314 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Legal);
315 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Legal);
316 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Legal);
317 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Legal);
318 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Legal);
319 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Legal);
320 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Legal);
321 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Legal);
323 setOperationAction(ISD::SETCC, MVT::v8i8, Custom);
324 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
325 setOperationAction(ISD::SETCC, MVT::v4i16, Custom);
326 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
327 setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
328 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
329 setOperationAction(ISD::SETCC, MVT::v1i64, Custom);
330 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
331 setOperationAction(ISD::SETCC, MVT::v1f32, Custom);
332 setOperationAction(ISD::SETCC, MVT::v2f32, Custom);
333 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
334 setOperationAction(ISD::SETCC, MVT::v1f64, Custom);
335 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
339 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
340 // It's reasonably important that this value matches the "natural" legal
341 // promotion from i1 for scalar types. Otherwise LegalizeTypes can get itself
342 // in a twist (e.g. inserting an any_extend which then becomes i64 -> i64).
343 if (!VT.isVector()) return MVT::i32;
344 return VT.changeVectorElementTypeToInteger();
347 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
350 static const unsigned LoadBares[] = {AArch64::LDXR_byte, AArch64::LDXR_hword,
351 AArch64::LDXR_word, AArch64::LDXR_dword};
352 static const unsigned LoadAcqs[] = {AArch64::LDAXR_byte, AArch64::LDAXR_hword,
353 AArch64::LDAXR_word, AArch64::LDAXR_dword};
354 static const unsigned StoreBares[] = {AArch64::STXR_byte, AArch64::STXR_hword,
355 AArch64::STXR_word, AArch64::STXR_dword};
356 static const unsigned StoreRels[] = {AArch64::STLXR_byte,AArch64::STLXR_hword,
357 AArch64::STLXR_word, AArch64::STLXR_dword};
359 const unsigned *LoadOps, *StoreOps;
360 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
365 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
366 StoreOps = StoreRels;
368 StoreOps = StoreBares;
370 assert(isPowerOf2_32(Size) && Size <= 8 &&
371 "unsupported size for atomic binary op!");
373 LdrOpc = LoadOps[Log2_32(Size)];
374 StrOpc = StoreOps[Log2_32(Size)];
378 AArch64TargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
380 unsigned BinOpcode) const {
381 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
382 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
384 const BasicBlock *LLVM_BB = BB->getBasicBlock();
385 MachineFunction *MF = BB->getParent();
386 MachineFunction::iterator It = BB;
389 unsigned dest = MI->getOperand(0).getReg();
390 unsigned ptr = MI->getOperand(1).getReg();
391 unsigned incr = MI->getOperand(2).getReg();
392 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
393 DebugLoc dl = MI->getDebugLoc();
395 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
397 unsigned ldrOpc, strOpc;
398 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
400 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
401 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
402 MF->insert(It, loopMBB);
403 MF->insert(It, exitMBB);
405 // Transfer the remainder of BB and its successor edges to exitMBB.
406 exitMBB->splice(exitMBB->begin(), BB,
407 llvm::next(MachineBasicBlock::iterator(MI)),
409 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
411 const TargetRegisterClass *TRC
412 = Size == 8 ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
413 unsigned scratch = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
417 // fallthrough --> loopMBB
418 BB->addSuccessor(loopMBB);
422 // <binop> scratch, dest, incr
423 // stxr stxr_status, scratch, ptr
424 // cbnz stxr_status, loopMBB
425 // fallthrough --> exitMBB
427 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
429 // All arithmetic operations we'll be creating are designed to take an extra
430 // shift or extend operand, which we can conveniently set to zero.
432 // Operand order needs to go the other way for NAND.
433 if (BinOpcode == AArch64::BICwww_lsl || BinOpcode == AArch64::BICxxx_lsl)
434 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
435 .addReg(incr).addReg(dest).addImm(0);
437 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
438 .addReg(dest).addReg(incr).addImm(0);
441 // From the stxr, the register is GPR32; from the cmp it's GPR32wsp
442 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
443 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
445 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(scratch).addReg(ptr);
446 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
447 .addReg(stxr_status).addMBB(loopMBB);
449 BB->addSuccessor(loopMBB);
450 BB->addSuccessor(exitMBB);
456 MI->eraseFromParent(); // The instruction is gone now.
462 AArch64TargetLowering::emitAtomicBinaryMinMax(MachineInstr *MI,
463 MachineBasicBlock *BB,
466 A64CC::CondCodes Cond) const {
467 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
469 const BasicBlock *LLVM_BB = BB->getBasicBlock();
470 MachineFunction *MF = BB->getParent();
471 MachineFunction::iterator It = BB;
474 unsigned dest = MI->getOperand(0).getReg();
475 unsigned ptr = MI->getOperand(1).getReg();
476 unsigned incr = MI->getOperand(2).getReg();
477 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
479 unsigned oldval = dest;
480 DebugLoc dl = MI->getDebugLoc();
482 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
483 const TargetRegisterClass *TRC, *TRCsp;
485 TRC = &AArch64::GPR64RegClass;
486 TRCsp = &AArch64::GPR64xspRegClass;
488 TRC = &AArch64::GPR32RegClass;
489 TRCsp = &AArch64::GPR32wspRegClass;
492 unsigned ldrOpc, strOpc;
493 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
495 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
496 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
497 MF->insert(It, loopMBB);
498 MF->insert(It, exitMBB);
500 // Transfer the remainder of BB and its successor edges to exitMBB.
501 exitMBB->splice(exitMBB->begin(), BB,
502 llvm::next(MachineBasicBlock::iterator(MI)),
504 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
506 unsigned scratch = MRI.createVirtualRegister(TRC);
507 MRI.constrainRegClass(scratch, TRCsp);
511 // fallthrough --> loopMBB
512 BB->addSuccessor(loopMBB);
516 // cmp incr, dest (, sign extend if necessary)
517 // csel scratch, dest, incr, cond
518 // stxr stxr_status, scratch, ptr
519 // cbnz stxr_status, loopMBB
520 // fallthrough --> exitMBB
522 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
524 // Build compare and cmov instructions.
525 MRI.constrainRegClass(incr, TRCsp);
526 BuildMI(BB, dl, TII->get(CmpOp))
527 .addReg(incr).addReg(oldval).addImm(0);
529 BuildMI(BB, dl, TII->get(Size == 8 ? AArch64::CSELxxxc : AArch64::CSELwwwc),
531 .addReg(oldval).addReg(incr).addImm(Cond);
533 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
534 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
536 BuildMI(BB, dl, TII->get(strOpc), stxr_status)
537 .addReg(scratch).addReg(ptr);
538 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
539 .addReg(stxr_status).addMBB(loopMBB);
541 BB->addSuccessor(loopMBB);
542 BB->addSuccessor(exitMBB);
548 MI->eraseFromParent(); // The instruction is gone now.
554 AArch64TargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
555 MachineBasicBlock *BB,
556 unsigned Size) const {
557 unsigned dest = MI->getOperand(0).getReg();
558 unsigned ptr = MI->getOperand(1).getReg();
559 unsigned oldval = MI->getOperand(2).getReg();
560 unsigned newval = MI->getOperand(3).getReg();
561 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
562 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
563 DebugLoc dl = MI->getDebugLoc();
565 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
566 const TargetRegisterClass *TRCsp;
567 TRCsp = Size == 8 ? &AArch64::GPR64xspRegClass : &AArch64::GPR32wspRegClass;
569 unsigned ldrOpc, strOpc;
570 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
572 MachineFunction *MF = BB->getParent();
573 const BasicBlock *LLVM_BB = BB->getBasicBlock();
574 MachineFunction::iterator It = BB;
575 ++It; // insert the new blocks after the current block
577 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
578 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
579 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
580 MF->insert(It, loop1MBB);
581 MF->insert(It, loop2MBB);
582 MF->insert(It, exitMBB);
584 // Transfer the remainder of BB and its successor edges to exitMBB.
585 exitMBB->splice(exitMBB->begin(), BB,
586 llvm::next(MachineBasicBlock::iterator(MI)),
588 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
592 // fallthrough --> loop1MBB
593 BB->addSuccessor(loop1MBB);
600 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
602 unsigned CmpOp = Size == 8 ? AArch64::CMPxx_lsl : AArch64::CMPww_lsl;
603 MRI.constrainRegClass(dest, TRCsp);
604 BuildMI(BB, dl, TII->get(CmpOp))
605 .addReg(dest).addReg(oldval).addImm(0);
606 BuildMI(BB, dl, TII->get(AArch64::Bcc))
607 .addImm(A64CC::NE).addMBB(exitMBB);
608 BB->addSuccessor(loop2MBB);
609 BB->addSuccessor(exitMBB);
612 // strex stxr_status, newval, [ptr]
613 // cbnz stxr_status, loop1MBB
615 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
616 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
618 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(newval).addReg(ptr);
619 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
620 .addReg(stxr_status).addMBB(loop1MBB);
621 BB->addSuccessor(loop1MBB);
622 BB->addSuccessor(exitMBB);
628 MI->eraseFromParent(); // The instruction is gone now.
634 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
635 MachineBasicBlock *MBB) const {
636 // We materialise the F128CSEL pseudo-instruction using conditional branches
637 // and loads, giving an instruciton sequence like:
646 // Using virtual registers would probably not be beneficial since COPY
647 // instructions are expensive for f128 (there's no actual instruction to
650 // An alternative would be to do an integer-CSEL on some address. E.g.:
655 // csel x0, x0, x1, ne
658 // It's unclear which approach is actually optimal.
659 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
660 MachineFunction *MF = MBB->getParent();
661 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
662 DebugLoc DL = MI->getDebugLoc();
663 MachineFunction::iterator It = MBB;
666 unsigned DestReg = MI->getOperand(0).getReg();
667 unsigned IfTrueReg = MI->getOperand(1).getReg();
668 unsigned IfFalseReg = MI->getOperand(2).getReg();
669 unsigned CondCode = MI->getOperand(3).getImm();
670 bool NZCVKilled = MI->getOperand(4).isKill();
672 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
673 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
674 MF->insert(It, TrueBB);
675 MF->insert(It, EndBB);
677 // Transfer rest of current basic-block to EndBB
678 EndBB->splice(EndBB->begin(), MBB,
679 llvm::next(MachineBasicBlock::iterator(MI)),
681 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
683 // We need somewhere to store the f128 value needed.
684 int ScratchFI = MF->getFrameInfo()->CreateSpillStackObject(16, 16);
686 // [... start of incoming MBB ...]
687 // str qIFFALSE, [sp]
690 BuildMI(MBB, DL, TII->get(AArch64::LSFP128_STR))
692 .addFrameIndex(ScratchFI)
694 BuildMI(MBB, DL, TII->get(AArch64::Bcc))
697 BuildMI(MBB, DL, TII->get(AArch64::Bimm))
699 MBB->addSuccessor(TrueBB);
700 MBB->addSuccessor(EndBB);
704 BuildMI(TrueBB, DL, TII->get(AArch64::LSFP128_STR))
706 .addFrameIndex(ScratchFI)
709 // Note: fallthrough. We can rely on LLVM adding a branch if it reorders the
711 TrueBB->addSuccessor(EndBB);
715 // [... rest of incoming MBB ...]
717 EndBB->addLiveIn(AArch64::NZCV);
718 MachineInstr *StartOfEnd = EndBB->begin();
719 BuildMI(*EndBB, StartOfEnd, DL, TII->get(AArch64::LSFP128_LDR), DestReg)
720 .addFrameIndex(ScratchFI)
723 MI->eraseFromParent();
728 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
729 MachineBasicBlock *MBB) const {
730 switch (MI->getOpcode()) {
731 default: llvm_unreachable("Unhandled instruction with custom inserter");
732 case AArch64::F128CSEL:
733 return EmitF128CSEL(MI, MBB);
734 case AArch64::ATOMIC_LOAD_ADD_I8:
735 return emitAtomicBinary(MI, MBB, 1, AArch64::ADDwww_lsl);
736 case AArch64::ATOMIC_LOAD_ADD_I16:
737 return emitAtomicBinary(MI, MBB, 2, AArch64::ADDwww_lsl);
738 case AArch64::ATOMIC_LOAD_ADD_I32:
739 return emitAtomicBinary(MI, MBB, 4, AArch64::ADDwww_lsl);
740 case AArch64::ATOMIC_LOAD_ADD_I64:
741 return emitAtomicBinary(MI, MBB, 8, AArch64::ADDxxx_lsl);
743 case AArch64::ATOMIC_LOAD_SUB_I8:
744 return emitAtomicBinary(MI, MBB, 1, AArch64::SUBwww_lsl);
745 case AArch64::ATOMIC_LOAD_SUB_I16:
746 return emitAtomicBinary(MI, MBB, 2, AArch64::SUBwww_lsl);
747 case AArch64::ATOMIC_LOAD_SUB_I32:
748 return emitAtomicBinary(MI, MBB, 4, AArch64::SUBwww_lsl);
749 case AArch64::ATOMIC_LOAD_SUB_I64:
750 return emitAtomicBinary(MI, MBB, 8, AArch64::SUBxxx_lsl);
752 case AArch64::ATOMIC_LOAD_AND_I8:
753 return emitAtomicBinary(MI, MBB, 1, AArch64::ANDwww_lsl);
754 case AArch64::ATOMIC_LOAD_AND_I16:
755 return emitAtomicBinary(MI, MBB, 2, AArch64::ANDwww_lsl);
756 case AArch64::ATOMIC_LOAD_AND_I32:
757 return emitAtomicBinary(MI, MBB, 4, AArch64::ANDwww_lsl);
758 case AArch64::ATOMIC_LOAD_AND_I64:
759 return emitAtomicBinary(MI, MBB, 8, AArch64::ANDxxx_lsl);
761 case AArch64::ATOMIC_LOAD_OR_I8:
762 return emitAtomicBinary(MI, MBB, 1, AArch64::ORRwww_lsl);
763 case AArch64::ATOMIC_LOAD_OR_I16:
764 return emitAtomicBinary(MI, MBB, 2, AArch64::ORRwww_lsl);
765 case AArch64::ATOMIC_LOAD_OR_I32:
766 return emitAtomicBinary(MI, MBB, 4, AArch64::ORRwww_lsl);
767 case AArch64::ATOMIC_LOAD_OR_I64:
768 return emitAtomicBinary(MI, MBB, 8, AArch64::ORRxxx_lsl);
770 case AArch64::ATOMIC_LOAD_XOR_I8:
771 return emitAtomicBinary(MI, MBB, 1, AArch64::EORwww_lsl);
772 case AArch64::ATOMIC_LOAD_XOR_I16:
773 return emitAtomicBinary(MI, MBB, 2, AArch64::EORwww_lsl);
774 case AArch64::ATOMIC_LOAD_XOR_I32:
775 return emitAtomicBinary(MI, MBB, 4, AArch64::EORwww_lsl);
776 case AArch64::ATOMIC_LOAD_XOR_I64:
777 return emitAtomicBinary(MI, MBB, 8, AArch64::EORxxx_lsl);
779 case AArch64::ATOMIC_LOAD_NAND_I8:
780 return emitAtomicBinary(MI, MBB, 1, AArch64::BICwww_lsl);
781 case AArch64::ATOMIC_LOAD_NAND_I16:
782 return emitAtomicBinary(MI, MBB, 2, AArch64::BICwww_lsl);
783 case AArch64::ATOMIC_LOAD_NAND_I32:
784 return emitAtomicBinary(MI, MBB, 4, AArch64::BICwww_lsl);
785 case AArch64::ATOMIC_LOAD_NAND_I64:
786 return emitAtomicBinary(MI, MBB, 8, AArch64::BICxxx_lsl);
788 case AArch64::ATOMIC_LOAD_MIN_I8:
789 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::GT);
790 case AArch64::ATOMIC_LOAD_MIN_I16:
791 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::GT);
792 case AArch64::ATOMIC_LOAD_MIN_I32:
793 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::GT);
794 case AArch64::ATOMIC_LOAD_MIN_I64:
795 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::GT);
797 case AArch64::ATOMIC_LOAD_MAX_I8:
798 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::LT);
799 case AArch64::ATOMIC_LOAD_MAX_I16:
800 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::LT);
801 case AArch64::ATOMIC_LOAD_MAX_I32:
802 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LT);
803 case AArch64::ATOMIC_LOAD_MAX_I64:
804 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LT);
806 case AArch64::ATOMIC_LOAD_UMIN_I8:
807 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::HI);
808 case AArch64::ATOMIC_LOAD_UMIN_I16:
809 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::HI);
810 case AArch64::ATOMIC_LOAD_UMIN_I32:
811 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::HI);
812 case AArch64::ATOMIC_LOAD_UMIN_I64:
813 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::HI);
815 case AArch64::ATOMIC_LOAD_UMAX_I8:
816 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::LO);
817 case AArch64::ATOMIC_LOAD_UMAX_I16:
818 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::LO);
819 case AArch64::ATOMIC_LOAD_UMAX_I32:
820 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LO);
821 case AArch64::ATOMIC_LOAD_UMAX_I64:
822 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LO);
824 case AArch64::ATOMIC_SWAP_I8:
825 return emitAtomicBinary(MI, MBB, 1, 0);
826 case AArch64::ATOMIC_SWAP_I16:
827 return emitAtomicBinary(MI, MBB, 2, 0);
828 case AArch64::ATOMIC_SWAP_I32:
829 return emitAtomicBinary(MI, MBB, 4, 0);
830 case AArch64::ATOMIC_SWAP_I64:
831 return emitAtomicBinary(MI, MBB, 8, 0);
833 case AArch64::ATOMIC_CMP_SWAP_I8:
834 return emitAtomicCmpSwap(MI, MBB, 1);
835 case AArch64::ATOMIC_CMP_SWAP_I16:
836 return emitAtomicCmpSwap(MI, MBB, 2);
837 case AArch64::ATOMIC_CMP_SWAP_I32:
838 return emitAtomicCmpSwap(MI, MBB, 4);
839 case AArch64::ATOMIC_CMP_SWAP_I64:
840 return emitAtomicCmpSwap(MI, MBB, 8);
845 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
847 case AArch64ISD::BR_CC: return "AArch64ISD::BR_CC";
848 case AArch64ISD::Call: return "AArch64ISD::Call";
849 case AArch64ISD::FPMOV: return "AArch64ISD::FPMOV";
850 case AArch64ISD::GOTLoad: return "AArch64ISD::GOTLoad";
851 case AArch64ISD::BFI: return "AArch64ISD::BFI";
852 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
853 case AArch64ISD::Ret: return "AArch64ISD::Ret";
854 case AArch64ISD::SBFX: return "AArch64ISD::SBFX";
855 case AArch64ISD::SELECT_CC: return "AArch64ISD::SELECT_CC";
856 case AArch64ISD::SETCC: return "AArch64ISD::SETCC";
857 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
858 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
859 case AArch64ISD::TLSDESCCALL: return "AArch64ISD::TLSDESCCALL";
860 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
861 case AArch64ISD::WrapperSmall: return "AArch64ISD::WrapperSmall";
863 case AArch64ISD::NEON_BSL:
864 return "AArch64ISD::NEON_BSL";
865 case AArch64ISD::NEON_MOVIMM:
866 return "AArch64ISD::NEON_MOVIMM";
867 case AArch64ISD::NEON_MVNIMM:
868 return "AArch64ISD::NEON_MVNIMM";
869 case AArch64ISD::NEON_FMOVIMM:
870 return "AArch64ISD::NEON_FMOVIMM";
871 case AArch64ISD::NEON_CMP:
872 return "AArch64ISD::NEON_CMP";
873 case AArch64ISD::NEON_CMPZ:
874 return "AArch64ISD::NEON_CMPZ";
875 case AArch64ISD::NEON_TST:
876 return "AArch64ISD::NEON_TST";
877 case AArch64ISD::NEON_QSHLs:
878 return "AArch64ISD::NEON_QSHLs";
879 case AArch64ISD::NEON_QSHLu:
880 return "AArch64ISD::NEON_QSHLu";
881 case AArch64ISD::NEON_VDUP:
882 return "AArch64ISD::NEON_VDUP";
883 case AArch64ISD::NEON_VDUPLANE:
884 return "AArch64ISD::NEON_VDUPLANE";
890 static const uint16_t AArch64FPRArgRegs[] = {
891 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
892 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7
894 static const unsigned NumFPRArgRegs = llvm::array_lengthof(AArch64FPRArgRegs);
896 static const uint16_t AArch64ArgRegs[] = {
897 AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3,
898 AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7
900 static const unsigned NumArgRegs = llvm::array_lengthof(AArch64ArgRegs);
902 static bool CC_AArch64NoMoreRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
903 CCValAssign::LocInfo LocInfo,
904 ISD::ArgFlagsTy ArgFlags, CCState &State) {
905 // Mark all remaining general purpose registers as allocated. We don't
906 // backtrack: if (for example) an i128 gets put on the stack, no subsequent
907 // i64 will go in registers (C.11).
908 for (unsigned i = 0; i < NumArgRegs; ++i)
909 State.AllocateReg(AArch64ArgRegs[i]);
914 #include "AArch64GenCallingConv.inc"
916 CCAssignFn *AArch64TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
919 default: llvm_unreachable("Unsupported calling convention");
920 case CallingConv::Fast:
927 AArch64TargetLowering::SaveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG,
928 SDLoc DL, SDValue &Chain) const {
929 MachineFunction &MF = DAG.getMachineFunction();
930 MachineFrameInfo *MFI = MF.getFrameInfo();
931 AArch64MachineFunctionInfo *FuncInfo
932 = MF.getInfo<AArch64MachineFunctionInfo>();
934 SmallVector<SDValue, 8> MemOps;
936 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(AArch64ArgRegs,
938 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(AArch64FPRArgRegs,
941 unsigned GPRSaveSize = 8 * (NumArgRegs - FirstVariadicGPR);
943 if (GPRSaveSize != 0) {
944 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
946 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
948 for (unsigned i = FirstVariadicGPR; i < NumArgRegs; ++i) {
949 unsigned VReg = MF.addLiveIn(AArch64ArgRegs[i], &AArch64::GPR64RegClass);
950 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
951 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
952 MachinePointerInfo::getStack(i * 8),
954 MemOps.push_back(Store);
955 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
956 DAG.getConstant(8, getPointerTy()));
960 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
962 if (FPRSaveSize != 0) {
963 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
965 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
967 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
968 unsigned VReg = MF.addLiveIn(AArch64FPRArgRegs[i],
969 &AArch64::FPR128RegClass);
970 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
971 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
972 MachinePointerInfo::getStack(i * 16),
974 MemOps.push_back(Store);
975 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
976 DAG.getConstant(16, getPointerTy()));
980 int StackIdx = MFI->CreateFixedObject(8, CCInfo.getNextStackOffset(), true);
982 FuncInfo->setVariadicStackIdx(StackIdx);
983 FuncInfo->setVariadicGPRIdx(GPRIdx);
984 FuncInfo->setVariadicGPRSize(GPRSaveSize);
985 FuncInfo->setVariadicFPRIdx(FPRIdx);
986 FuncInfo->setVariadicFPRSize(FPRSaveSize);
988 if (!MemOps.empty()) {
989 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
996 AArch64TargetLowering::LowerFormalArguments(SDValue Chain,
997 CallingConv::ID CallConv, bool isVarArg,
998 const SmallVectorImpl<ISD::InputArg> &Ins,
999 SDLoc dl, SelectionDAG &DAG,
1000 SmallVectorImpl<SDValue> &InVals) const {
1001 MachineFunction &MF = DAG.getMachineFunction();
1002 AArch64MachineFunctionInfo *FuncInfo
1003 = MF.getInfo<AArch64MachineFunctionInfo>();
1004 MachineFrameInfo *MFI = MF.getFrameInfo();
1005 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1007 SmallVector<CCValAssign, 16> ArgLocs;
1008 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1009 getTargetMachine(), ArgLocs, *DAG.getContext());
1010 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1012 SmallVector<SDValue, 16> ArgValues;
1015 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1016 CCValAssign &VA = ArgLocs[i];
1017 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1019 if (Flags.isByVal()) {
1020 // Byval is used for small structs and HFAs in the PCS, but the system
1021 // should work in a non-compliant manner for larger structs.
1022 EVT PtrTy = getPointerTy();
1023 int Size = Flags.getByValSize();
1024 unsigned NumRegs = (Size + 7) / 8;
1026 unsigned FrameIdx = MFI->CreateFixedObject(8 * NumRegs,
1027 VA.getLocMemOffset(),
1029 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1030 InVals.push_back(FrameIdxN);
1033 } else if (VA.isRegLoc()) {
1034 MVT RegVT = VA.getLocVT();
1035 const TargetRegisterClass *RC = getRegClassFor(RegVT);
1036 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1038 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1039 } else { // VA.isRegLoc()
1040 assert(VA.isMemLoc());
1042 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
1043 VA.getLocMemOffset(), true);
1045 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1046 ArgValue = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1047 MachinePointerInfo::getFixedStack(FI),
1048 false, false, false, 0);
1053 switch (VA.getLocInfo()) {
1054 default: llvm_unreachable("Unknown loc info!");
1055 case CCValAssign::Full: break;
1056 case CCValAssign::BCvt:
1057 ArgValue = DAG.getNode(ISD::BITCAST,dl, VA.getValVT(), ArgValue);
1059 case CCValAssign::SExt:
1060 case CCValAssign::ZExt:
1061 case CCValAssign::AExt: {
1062 unsigned DestSize = VA.getValVT().getSizeInBits();
1063 unsigned DestSubReg;
1066 case 8: DestSubReg = AArch64::sub_8; break;
1067 case 16: DestSubReg = AArch64::sub_16; break;
1068 case 32: DestSubReg = AArch64::sub_32; break;
1069 case 64: DestSubReg = AArch64::sub_64; break;
1070 default: llvm_unreachable("Unexpected argument promotion");
1073 ArgValue = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1074 VA.getValVT(), ArgValue,
1075 DAG.getTargetConstant(DestSubReg, MVT::i32)),
1081 InVals.push_back(ArgValue);
1085 SaveVarArgRegisters(CCInfo, DAG, dl, Chain);
1087 unsigned StackArgSize = CCInfo.getNextStackOffset();
1088 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1089 // This is a non-standard ABI so by fiat I say we're allowed to make full
1090 // use of the stack area to be popped, which must be aligned to 16 bytes in
1092 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1094 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1095 // a multiple of 16.
1096 FuncInfo->setArgumentStackToRestore(StackArgSize);
1098 // This realignment carries over to the available bytes below. Our own
1099 // callers will guarantee the space is free by giving an aligned value to
1102 // Even if we're not expected to free up the space, it's useful to know how
1103 // much is there while considering tail calls (because we can reuse it).
1104 FuncInfo->setBytesInStackArgArea(StackArgSize);
1110 AArch64TargetLowering::LowerReturn(SDValue Chain,
1111 CallingConv::ID CallConv, bool isVarArg,
1112 const SmallVectorImpl<ISD::OutputArg> &Outs,
1113 const SmallVectorImpl<SDValue> &OutVals,
1114 SDLoc dl, SelectionDAG &DAG) const {
1115 // CCValAssign - represent the assignment of the return value to a location.
1116 SmallVector<CCValAssign, 16> RVLocs;
1118 // CCState - Info about the registers and stack slots.
1119 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1120 getTargetMachine(), RVLocs, *DAG.getContext());
1122 // Analyze outgoing return values.
1123 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv));
1126 SmallVector<SDValue, 4> RetOps(1, Chain);
1128 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1129 // PCS: "If the type, T, of the result of a function is such that
1130 // void func(T arg) would require that arg be passed as a value in a
1131 // register (or set of registers) according to the rules in 5.4, then the
1132 // result is returned in the same registers as would be used for such an
1135 // Otherwise, the caller shall reserve a block of memory of sufficient
1136 // size and alignment to hold the result. The address of the memory block
1137 // shall be passed as an additional argument to the function in x8."
1139 // This is implemented in two places. The register-return values are dealt
1140 // with here, more complex returns are passed as an sret parameter, which
1141 // means we don't have to worry about it during actual return.
1142 CCValAssign &VA = RVLocs[i];
1143 assert(VA.isRegLoc() && "Only register-returns should be created by PCS");
1146 SDValue Arg = OutVals[i];
1148 // There's no convenient note in the ABI about this as there is for normal
1149 // arguments, but it says return values are passed in the same registers as
1150 // an argument would be. I believe that includes the comments about
1151 // unspecified higher bits, putting the burden of widening on the *caller*
1152 // for return values.
1153 switch (VA.getLocInfo()) {
1154 default: llvm_unreachable("Unknown loc info");
1155 case CCValAssign::Full: break;
1156 case CCValAssign::SExt:
1157 case CCValAssign::ZExt:
1158 case CCValAssign::AExt:
1159 // Floating-point values should only be extended when they're going into
1160 // memory, which can't happen here so an integer extend is acceptable.
1161 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1163 case CCValAssign::BCvt:
1164 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1168 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1169 Flag = Chain.getValue(1);
1170 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1173 RetOps[0] = Chain; // Update chain.
1175 // Add the flag if we have it.
1177 RetOps.push_back(Flag);
1179 return DAG.getNode(AArch64ISD::Ret, dl, MVT::Other,
1180 &RetOps[0], RetOps.size());
1184 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1185 SmallVectorImpl<SDValue> &InVals) const {
1186 SelectionDAG &DAG = CLI.DAG;
1188 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1189 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1190 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1191 SDValue Chain = CLI.Chain;
1192 SDValue Callee = CLI.Callee;
1193 bool &IsTailCall = CLI.IsTailCall;
1194 CallingConv::ID CallConv = CLI.CallConv;
1195 bool IsVarArg = CLI.IsVarArg;
1197 MachineFunction &MF = DAG.getMachineFunction();
1198 AArch64MachineFunctionInfo *FuncInfo
1199 = MF.getInfo<AArch64MachineFunctionInfo>();
1200 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1201 bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1202 bool IsSibCall = false;
1205 IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1206 IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1207 Outs, OutVals, Ins, DAG);
1209 // A sibling call is one where we're under the usual C ABI and not planning
1210 // to change that but can still do a tail call:
1211 if (!TailCallOpt && IsTailCall)
1215 SmallVector<CCValAssign, 16> ArgLocs;
1216 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1217 getTargetMachine(), ArgLocs, *DAG.getContext());
1218 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1220 // On AArch64 (and all other architectures I'm aware of) the most this has to
1221 // do is adjust the stack pointer.
1222 unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1224 // Since we're not changing the ABI to make this a tail call, the memory
1225 // operands are already available in the caller's incoming argument space.
1229 // FPDiff is the byte offset of the call's argument area from the callee's.
1230 // Stores to callee stack arguments will be placed in FixedStackSlots offset
1231 // by this amount for a tail call. In a sibling call it must be 0 because the
1232 // caller will deallocate the entire stack and the callee still expects its
1233 // arguments to begin at SP+0. Completely unused for non-tail calls.
1236 if (IsTailCall && !IsSibCall) {
1237 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1239 // FPDiff will be negative if this tail call requires more space than we
1240 // would automatically have in our incoming argument space. Positive if we
1241 // can actually shrink the stack.
1242 FPDiff = NumReusableBytes - NumBytes;
1244 // The stack pointer must be 16-byte aligned at all times it's used for a
1245 // memory operation, which in practice means at *all* times and in
1246 // particular across call boundaries. Therefore our own arguments started at
1247 // a 16-byte aligned SP and the delta applied for the tail call should
1248 // satisfy the same constraint.
1249 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1253 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1256 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1259 SmallVector<SDValue, 8> MemOpChains;
1260 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1262 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1263 CCValAssign &VA = ArgLocs[i];
1264 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1265 SDValue Arg = OutVals[i];
1267 // Callee does the actual widening, so all extensions just use an implicit
1268 // definition of the rest of the Loc. Aesthetically, this would be nicer as
1269 // an ANY_EXTEND, but that isn't valid for floating-point types and this
1270 // alternative works on integer types too.
1271 switch (VA.getLocInfo()) {
1272 default: llvm_unreachable("Unknown loc info!");
1273 case CCValAssign::Full: break;
1274 case CCValAssign::SExt:
1275 case CCValAssign::ZExt:
1276 case CCValAssign::AExt: {
1277 unsigned SrcSize = VA.getValVT().getSizeInBits();
1281 case 8: SrcSubReg = AArch64::sub_8; break;
1282 case 16: SrcSubReg = AArch64::sub_16; break;
1283 case 32: SrcSubReg = AArch64::sub_32; break;
1284 case 64: SrcSubReg = AArch64::sub_64; break;
1285 default: llvm_unreachable("Unexpected argument promotion");
1288 Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1290 DAG.getUNDEF(VA.getLocVT()),
1292 DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1297 case CCValAssign::BCvt:
1298 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1302 if (VA.isRegLoc()) {
1303 // A normal register (sub-) argument. For now we just note it down because
1304 // we want to copy things into registers as late as possible to avoid
1305 // register-pressure (and possibly worse).
1306 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1310 assert(VA.isMemLoc() && "unexpected argument location");
1313 MachinePointerInfo DstInfo;
1315 uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1316 VA.getLocVT().getSizeInBits();
1317 OpSize = (OpSize + 7) / 8;
1318 int32_t Offset = VA.getLocMemOffset() + FPDiff;
1319 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1321 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1322 DstInfo = MachinePointerInfo::getFixedStack(FI);
1324 // Make sure any stack arguments overlapping with where we're storing are
1325 // loaded before this eventual operation. Otherwise they'll be clobbered.
1326 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1328 SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1330 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1331 DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1334 if (Flags.isByVal()) {
1335 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1336 SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1337 Flags.getByValAlign(),
1338 /*isVolatile = */ false,
1339 /*alwaysInline = */ false,
1340 DstInfo, MachinePointerInfo(0));
1341 MemOpChains.push_back(Cpy);
1343 // Normal stack argument, put it where it's needed.
1344 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1346 MemOpChains.push_back(Store);
1350 // The loads and stores generated above shouldn't clash with each
1351 // other. Combining them with this TokenFactor notes that fact for the rest of
1353 if (!MemOpChains.empty())
1354 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1355 &MemOpChains[0], MemOpChains.size());
1357 // Most of the rest of the instructions need to be glued together; we don't
1358 // want assignments to actual registers used by a call to be rearranged by a
1359 // well-meaning scheduler.
1362 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1363 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1364 RegsToPass[i].second, InFlag);
1365 InFlag = Chain.getValue(1);
1368 // The linker is responsible for inserting veneers when necessary to put a
1369 // function call destination in range, so we don't need to bother with a
1371 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1372 const GlobalValue *GV = G->getGlobal();
1373 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1374 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1375 const char *Sym = S->getSymbol();
1376 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1379 // We don't usually want to end the call-sequence here because we would tidy
1380 // the frame up *after* the call, however in the ABI-changing tail-call case
1381 // we've carefully laid out the parameters so that when sp is reset they'll be
1382 // in the correct location.
1383 if (IsTailCall && !IsSibCall) {
1384 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1385 DAG.getIntPtrConstant(0, true), InFlag, dl);
1386 InFlag = Chain.getValue(1);
1389 // We produce the following DAG scheme for the actual call instruction:
1390 // (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1392 // Most arguments aren't going to be used and just keep the values live as
1393 // far as LLVM is concerned. It's expected to be selected as simply "bl
1394 // callee" (for a direct, non-tail call).
1395 std::vector<SDValue> Ops;
1396 Ops.push_back(Chain);
1397 Ops.push_back(Callee);
1400 // Each tail call may have to adjust the stack by a different amount, so
1401 // this information must travel along with the operation for eventual
1402 // consumption by emitEpilogue.
1403 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1406 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1407 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1408 RegsToPass[i].second.getValueType()));
1411 // Add a register mask operand representing the call-preserved registers. This
1412 // is used later in codegen to constrain register-allocation.
1413 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1414 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1415 assert(Mask && "Missing call preserved mask for calling convention");
1416 Ops.push_back(DAG.getRegisterMask(Mask));
1418 // If we needed glue, put it in as the last argument.
1419 if (InFlag.getNode())
1420 Ops.push_back(InFlag);
1422 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1425 return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1428 Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1429 InFlag = Chain.getValue(1);
1431 // Now we can reclaim the stack, just as well do it before working out where
1432 // our return value is.
1434 uint64_t CalleePopBytes
1435 = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1437 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1438 DAG.getIntPtrConstant(CalleePopBytes, true),
1440 InFlag = Chain.getValue(1);
1443 return LowerCallResult(Chain, InFlag, CallConv,
1444 IsVarArg, Ins, dl, DAG, InVals);
1448 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1449 CallingConv::ID CallConv, bool IsVarArg,
1450 const SmallVectorImpl<ISD::InputArg> &Ins,
1451 SDLoc dl, SelectionDAG &DAG,
1452 SmallVectorImpl<SDValue> &InVals) const {
1453 // Assign locations to each value returned by this call.
1454 SmallVector<CCValAssign, 16> RVLocs;
1455 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1456 getTargetMachine(), RVLocs, *DAG.getContext());
1457 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1459 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1460 CCValAssign VA = RVLocs[i];
1462 // Return values that are too big to fit into registers should use an sret
1463 // pointer, so this can be a lot simpler than the main argument code.
1464 assert(VA.isRegLoc() && "Memory locations not expected for call return");
1466 SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1468 Chain = Val.getValue(1);
1469 InFlag = Val.getValue(2);
1471 switch (VA.getLocInfo()) {
1472 default: llvm_unreachable("Unknown loc info!");
1473 case CCValAssign::Full: break;
1474 case CCValAssign::BCvt:
1475 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1477 case CCValAssign::ZExt:
1478 case CCValAssign::SExt:
1479 case CCValAssign::AExt:
1480 // Floating-point arguments only get extended/truncated if they're going
1481 // in memory, so using the integer operation is acceptable here.
1482 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1486 InVals.push_back(Val);
1493 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1494 CallingConv::ID CalleeCC,
1496 bool IsCalleeStructRet,
1497 bool IsCallerStructRet,
1498 const SmallVectorImpl<ISD::OutputArg> &Outs,
1499 const SmallVectorImpl<SDValue> &OutVals,
1500 const SmallVectorImpl<ISD::InputArg> &Ins,
1501 SelectionDAG& DAG) const {
1503 // For CallingConv::C this function knows whether the ABI needs
1504 // changing. That's not true for other conventions so they will have to opt in
1506 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1509 const MachineFunction &MF = DAG.getMachineFunction();
1510 const Function *CallerF = MF.getFunction();
1511 CallingConv::ID CallerCC = CallerF->getCallingConv();
1512 bool CCMatch = CallerCC == CalleeCC;
1514 // Byval parameters hand the function a pointer directly into the stack area
1515 // we want to reuse during a tail call. Working around this *is* possible (see
1516 // X86) but less efficient and uglier in LowerCall.
1517 for (Function::const_arg_iterator i = CallerF->arg_begin(),
1518 e = CallerF->arg_end(); i != e; ++i)
1519 if (i->hasByValAttr())
1522 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1523 if (IsTailCallConvention(CalleeCC) && CCMatch)
1528 // Now we search for cases where we can use a tail call without changing the
1529 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1532 // I want anyone implementing a new calling convention to think long and hard
1533 // about this assert.
1534 assert((!IsVarArg || CalleeCC == CallingConv::C)
1535 && "Unexpected variadic calling convention");
1537 if (IsVarArg && !Outs.empty()) {
1538 // At least two cases here: if caller is fastcc then we can't have any
1539 // memory arguments (we'd be expected to clean up the stack afterwards). If
1540 // caller is C then we could potentially use its argument area.
1542 // FIXME: for now we take the most conservative of these in both cases:
1543 // disallow all variadic memory operands.
1544 SmallVector<CCValAssign, 16> ArgLocs;
1545 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1546 getTargetMachine(), ArgLocs, *DAG.getContext());
1548 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1549 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1550 if (!ArgLocs[i].isRegLoc())
1554 // If the calling conventions do not match, then we'd better make sure the
1555 // results are returned in the same way as what the caller expects.
1557 SmallVector<CCValAssign, 16> RVLocs1;
1558 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1559 getTargetMachine(), RVLocs1, *DAG.getContext());
1560 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1562 SmallVector<CCValAssign, 16> RVLocs2;
1563 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1564 getTargetMachine(), RVLocs2, *DAG.getContext());
1565 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1567 if (RVLocs1.size() != RVLocs2.size())
1569 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1570 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1572 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1574 if (RVLocs1[i].isRegLoc()) {
1575 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1578 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1584 // Nothing more to check if the callee is taking no arguments
1588 SmallVector<CCValAssign, 16> ArgLocs;
1589 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1590 getTargetMachine(), ArgLocs, *DAG.getContext());
1592 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1594 const AArch64MachineFunctionInfo *FuncInfo
1595 = MF.getInfo<AArch64MachineFunctionInfo>();
1597 // If the stack arguments for this call would fit into our own save area then
1598 // the call can be made tail.
1599 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1602 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1603 bool TailCallOpt) const {
1604 return CallCC == CallingConv::Fast && TailCallOpt;
1607 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1608 return CallCC == CallingConv::Fast;
1611 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1613 MachineFrameInfo *MFI,
1614 int ClobberedFI) const {
1615 SmallVector<SDValue, 8> ArgChains;
1616 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1617 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1619 // Include the original chain at the beginning of the list. When this is
1620 // used by target LowerCall hooks, this helps legalize find the
1621 // CALLSEQ_BEGIN node.
1622 ArgChains.push_back(Chain);
1624 // Add a chain value for each stack argument corresponding
1625 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1626 UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1627 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1628 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1629 if (FI->getIndex() < 0) {
1630 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1631 int64_t InLastByte = InFirstByte;
1632 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1634 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1635 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1636 ArgChains.push_back(SDValue(L, 1));
1639 // Build a tokenfactor for all the chains.
1640 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1641 &ArgChains[0], ArgChains.size());
1644 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1646 case ISD::SETEQ: return A64CC::EQ;
1647 case ISD::SETGT: return A64CC::GT;
1648 case ISD::SETGE: return A64CC::GE;
1649 case ISD::SETLT: return A64CC::LT;
1650 case ISD::SETLE: return A64CC::LE;
1651 case ISD::SETNE: return A64CC::NE;
1652 case ISD::SETUGT: return A64CC::HI;
1653 case ISD::SETUGE: return A64CC::HS;
1654 case ISD::SETULT: return A64CC::LO;
1655 case ISD::SETULE: return A64CC::LS;
1656 default: llvm_unreachable("Unexpected condition code");
1660 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1661 // icmp is implemented using adds/subs immediate, which take an unsigned
1662 // 12-bit immediate, optionally shifted left by 12 bits.
1664 // Symmetric by using adds/subs
1668 return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1671 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1672 ISD::CondCode CC, SDValue &A64cc,
1673 SelectionDAG &DAG, SDLoc &dl) const {
1674 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1676 EVT VT = RHSC->getValueType(0);
1677 bool knownInvalid = false;
1679 // I'm not convinced the rest of LLVM handles these edge cases properly, but
1680 // we can at least get it right.
1681 if (isSignedIntSetCC(CC)) {
1682 C = RHSC->getSExtValue();
1683 } else if (RHSC->getZExtValue() > INT64_MAX) {
1684 // A 64-bit constant not representable by a signed 64-bit integer is far
1685 // too big to fit into a SUBS immediate anyway.
1686 knownInvalid = true;
1688 C = RHSC->getZExtValue();
1691 if (!knownInvalid && !isLegalICmpImmediate(C)) {
1692 // Constant does not fit, try adjusting it by one?
1697 if (isLegalICmpImmediate(C-1)) {
1698 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1699 RHS = DAG.getConstant(C-1, VT);
1704 if (isLegalICmpImmediate(C-1)) {
1705 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1706 RHS = DAG.getConstant(C-1, VT);
1711 if (isLegalICmpImmediate(C+1)) {
1712 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1713 RHS = DAG.getConstant(C+1, VT);
1718 if (isLegalICmpImmediate(C+1)) {
1719 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1720 RHS = DAG.getConstant(C+1, VT);
1727 A64CC::CondCodes CondCode = IntCCToA64CC(CC);
1728 A64cc = DAG.getConstant(CondCode, MVT::i32);
1729 return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1730 DAG.getCondCode(CC));
1733 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
1734 A64CC::CondCodes &Alternative) {
1735 A64CC::CondCodes CondCode = A64CC::Invalid;
1736 Alternative = A64CC::Invalid;
1739 default: llvm_unreachable("Unknown FP condition!");
1741 case ISD::SETOEQ: CondCode = A64CC::EQ; break;
1743 case ISD::SETOGT: CondCode = A64CC::GT; break;
1745 case ISD::SETOGE: CondCode = A64CC::GE; break;
1746 case ISD::SETOLT: CondCode = A64CC::MI; break;
1747 case ISD::SETOLE: CondCode = A64CC::LS; break;
1748 case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
1749 case ISD::SETO: CondCode = A64CC::VC; break;
1750 case ISD::SETUO: CondCode = A64CC::VS; break;
1751 case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
1752 case ISD::SETUGT: CondCode = A64CC::HI; break;
1753 case ISD::SETUGE: CondCode = A64CC::PL; break;
1755 case ISD::SETULT: CondCode = A64CC::LT; break;
1757 case ISD::SETULE: CondCode = A64CC::LE; break;
1759 case ISD::SETUNE: CondCode = A64CC::NE; break;
1765 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1767 EVT PtrVT = getPointerTy();
1768 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1770 switch(getTargetMachine().getCodeModel()) {
1771 case CodeModel::Small:
1772 // The most efficient code is PC-relative anyway for the small memory model,
1773 // so we don't need to worry about relocation model.
1774 return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
1775 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1776 AArch64II::MO_NO_FLAG),
1777 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1778 AArch64II::MO_LO12),
1779 DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
1780 case CodeModel::Large:
1782 AArch64ISD::WrapperLarge, DL, PtrVT,
1783 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
1784 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1785 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1786 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1788 llvm_unreachable("Only small and large code models supported now");
1793 // (BRCOND chain, val, dest)
1795 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1797 SDValue Chain = Op.getOperand(0);
1798 SDValue TheBit = Op.getOperand(1);
1799 SDValue DestBB = Op.getOperand(2);
1801 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
1802 // that as the consumer we are responsible for ignoring rubbish in higher
1804 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
1805 DAG.getConstant(1, MVT::i32));
1807 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
1808 DAG.getConstant(0, TheBit.getValueType()),
1809 DAG.getCondCode(ISD::SETNE));
1811 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
1812 A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
1816 // (BR_CC chain, condcode, lhs, rhs, dest)
1818 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1820 SDValue Chain = Op.getOperand(0);
1821 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1822 SDValue LHS = Op.getOperand(2);
1823 SDValue RHS = Op.getOperand(3);
1824 SDValue DestBB = Op.getOperand(4);
1826 if (LHS.getValueType() == MVT::f128) {
1827 // f128 comparisons are lowered to runtime calls by a routine which sets
1828 // LHS, RHS and CC appropriately for the rest of this function to continue.
1829 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
1831 // If softenSetCCOperands returned a scalar, we need to compare the result
1832 // against zero to select between true and false values.
1833 if (RHS.getNode() == 0) {
1834 RHS = DAG.getConstant(0, LHS.getValueType());
1839 if (LHS.getValueType().isInteger()) {
1842 // Integers are handled in a separate function because the combinations of
1843 // immediates and tests can get hairy and we may want to fiddle things.
1844 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
1846 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1847 Chain, CmpOp, A64cc, DestBB);
1850 // Note that some LLVM floating-point CondCodes can't be lowered to a single
1851 // conditional branch, hence FPCCToA64CC can set a second test, where either
1852 // passing is sufficient.
1853 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
1854 CondCode = FPCCToA64CC(CC, Alternative);
1855 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
1856 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1857 DAG.getCondCode(CC));
1858 SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1859 Chain, SetCC, A64cc, DestBB);
1861 if (Alternative != A64CC::Invalid) {
1862 A64cc = DAG.getConstant(Alternative, MVT::i32);
1863 A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1864 A64BR_CC, SetCC, A64cc, DestBB);
1872 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
1873 RTLIB::Libcall Call) const {
1876 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
1877 EVT ArgVT = Op.getOperand(i).getValueType();
1878 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1879 Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
1880 Entry.isSExt = false;
1881 Entry.isZExt = false;
1882 Args.push_back(Entry);
1884 SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
1886 Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
1888 // By default, the input chain to this libcall is the entry node of the
1889 // function. If the libcall is going to be emitted as a tail call then
1890 // isUsedByReturnOnly will change it to the right chain if the return
1891 // node which is being folded has a non-entry input chain.
1892 SDValue InChain = DAG.getEntryNode();
1894 // isTailCall may be true since the callee does not reference caller stack
1895 // frame. Check if it's in the right position.
1896 SDValue TCChain = InChain;
1897 bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
1902 CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
1903 0, getLibcallCallingConv(Call), isTailCall,
1904 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1905 Callee, Args, DAG, SDLoc(Op));
1906 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
1908 if (!CallInfo.second.getNode())
1909 // It's a tailcall, return the chain (which is the DAG root).
1910 return DAG.getRoot();
1912 return CallInfo.first;
1916 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
1917 if (Op.getOperand(0).getValueType() != MVT::f128) {
1918 // It's legal except when f128 is involved
1923 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1925 SDValue SrcVal = Op.getOperand(0);
1926 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1927 /*isSigned*/ false, SDLoc(Op)).first;
1931 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
1932 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1935 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1937 return LowerF128ToCall(Op, DAG, LC);
1941 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
1942 bool IsSigned) const {
1943 if (Op.getOperand(0).getValueType() != MVT::f128) {
1944 // It's legal except when f128 is involved
1950 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1952 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1954 return LowerF128ToCall(Op, DAG, LC);
1958 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
1959 SelectionDAG &DAG) const {
1960 assert(getTargetMachine().getCodeModel() == CodeModel::Large);
1961 assert(getTargetMachine().getRelocationModel() == Reloc::Static);
1963 EVT PtrVT = getPointerTy();
1965 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1966 const GlobalValue *GV = GN->getGlobal();
1968 SDValue GlobalAddr = DAG.getNode(
1969 AArch64ISD::WrapperLarge, dl, PtrVT,
1970 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
1971 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1972 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1973 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1975 if (GN->getOffset() != 0)
1976 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
1977 DAG.getConstant(GN->getOffset(), PtrVT));
1983 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
1984 SelectionDAG &DAG) const {
1985 assert(getTargetMachine().getCodeModel() == CodeModel::Small);
1987 EVT PtrVT = getPointerTy();
1989 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1990 const GlobalValue *GV = GN->getGlobal();
1991 unsigned Alignment = GV->getAlignment();
1992 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1993 if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
1994 // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
1995 // to zero when they remain undefined. In PIC mode the GOT can take care of
1996 // this, but in absolute mode we use a constant pool load.
1998 PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
1999 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2000 AArch64II::MO_NO_FLAG),
2001 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
2002 AArch64II::MO_LO12),
2003 DAG.getConstant(8, MVT::i32));
2004 SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
2005 MachinePointerInfo::getConstantPool(),
2006 /*isVolatile=*/ false,
2007 /*isNonTemporal=*/ true,
2008 /*isInvariant=*/ true, 8);
2009 if (GN->getOffset() != 0)
2010 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2011 DAG.getConstant(GN->getOffset(), PtrVT));
2016 if (Alignment == 0) {
2017 const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2018 if (GVPtrTy->getElementType()->isSized()) {
2020 = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2022 // Be conservative if we can't guess, not that it really matters:
2023 // functions and labels aren't valid for loads, and the methods used to
2024 // actually calculate an address work with any alignment.
2029 unsigned char HiFixup, LoFixup;
2030 bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2033 HiFixup = AArch64II::MO_GOT;
2034 LoFixup = AArch64II::MO_GOT_LO12;
2037 HiFixup = AArch64II::MO_NO_FLAG;
2038 LoFixup = AArch64II::MO_LO12;
2041 // AArch64's small model demands the following sequence:
2042 // ADRP x0, somewhere
2043 // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2044 SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2045 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2047 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2049 DAG.getConstant(Alignment, MVT::i32));
2052 GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2056 if (GN->getOffset() != 0)
2057 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2058 DAG.getConstant(GN->getOffset(), PtrVT));
2064 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2065 SelectionDAG &DAG) const {
2066 // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2067 // we make those distinctions here.
2069 switch (getTargetMachine().getCodeModel()) {
2070 case CodeModel::Small:
2071 return LowerGlobalAddressELFSmall(Op, DAG);
2072 case CodeModel::Large:
2073 return LowerGlobalAddressELFLarge(Op, DAG);
2075 llvm_unreachable("Only small and large code models supported now");
2079 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2082 SelectionDAG &DAG) const {
2083 EVT PtrVT = getPointerTy();
2085 // The function we need to call is simply the first entry in the GOT for this
2086 // descriptor, load it in preparation.
2087 SDValue Func, Chain;
2088 Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2091 // The function takes only one argument: the address of the descriptor itself
2094 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2095 Glue = Chain.getValue(1);
2097 // Finally, there's a special calling-convention which means that the lookup
2098 // must preserve all registers (except X0, obviously).
2099 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2100 const AArch64RegisterInfo *A64RI
2101 = static_cast<const AArch64RegisterInfo *>(TRI);
2102 const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2104 // We're now ready to populate the argument list, as with a normal call:
2105 std::vector<SDValue> Ops;
2106 Ops.push_back(Chain);
2107 Ops.push_back(Func);
2108 Ops.push_back(SymAddr);
2109 Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2110 Ops.push_back(DAG.getRegisterMask(Mask));
2111 Ops.push_back(Glue);
2113 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2114 Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2116 Glue = Chain.getValue(1);
2118 // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2119 // back to the generic handling code.
2120 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2124 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2125 SelectionDAG &DAG) const {
2126 assert(getSubtarget()->isTargetELF() &&
2127 "TLS not implemented for non-ELF targets");
2128 assert(getTargetMachine().getCodeModel() == CodeModel::Small
2129 && "TLS only supported in small memory model");
2130 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2132 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2135 EVT PtrVT = getPointerTy();
2137 const GlobalValue *GV = GA->getGlobal();
2139 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2141 if (Model == TLSModel::InitialExec) {
2142 TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2143 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2144 AArch64II::MO_GOTTPREL),
2145 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2146 AArch64II::MO_GOTTPREL_LO12),
2147 DAG.getConstant(8, MVT::i32));
2148 TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2150 } else if (Model == TLSModel::LocalExec) {
2151 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2152 AArch64II::MO_TPREL_G1);
2153 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2154 AArch64II::MO_TPREL_G0_NC);
2156 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2157 DAG.getTargetConstant(1, MVT::i32)), 0);
2158 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2160 DAG.getTargetConstant(0, MVT::i32)), 0);
2161 } else if (Model == TLSModel::GeneralDynamic) {
2162 // Accesses used in this sequence go via the TLS descriptor which lives in
2163 // the GOT. Prepare an address we can use to handle this.
2164 SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2165 AArch64II::MO_TLSDESC);
2166 SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2167 AArch64II::MO_TLSDESC_LO12);
2168 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2170 DAG.getConstant(8, MVT::i32));
2171 SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2173 TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2174 } else if (Model == TLSModel::LocalDynamic) {
2175 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2176 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2177 // the beginning of the module's TLS region, followed by a DTPREL offset
2180 // These accesses will need deduplicating if there's more than one.
2181 AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2182 .getInfo<AArch64MachineFunctionInfo>();
2183 MFI->incNumLocalDynamicTLSAccesses();
2186 // Get the location of _TLS_MODULE_BASE_:
2187 SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2188 AArch64II::MO_TLSDESC);
2189 SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2190 AArch64II::MO_TLSDESC_LO12);
2191 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2193 DAG.getConstant(8, MVT::i32));
2194 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2196 ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2198 // Get the variable's offset from _TLS_MODULE_BASE_
2199 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2200 AArch64II::MO_DTPREL_G1);
2201 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2202 AArch64II::MO_DTPREL_G0_NC);
2204 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2205 DAG.getTargetConstant(0, MVT::i32)), 0);
2206 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2208 DAG.getTargetConstant(0, MVT::i32)), 0);
2210 llvm_unreachable("Unsupported TLS access model");
2213 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2217 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2218 bool IsSigned) const {
2219 if (Op.getValueType() != MVT::f128) {
2220 // Legal for everything except f128.
2226 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2228 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2230 return LowerF128ToCall(Op, DAG, LC);
2235 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2236 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2238 EVT PtrVT = getPointerTy();
2240 // When compiling PIC, jump tables get put in the code section so a static
2241 // relocation-style is acceptable for both cases.
2242 switch (getTargetMachine().getCodeModel()) {
2243 case CodeModel::Small:
2244 return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2245 DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2246 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2247 AArch64II::MO_LO12),
2248 DAG.getConstant(1, MVT::i32));
2249 case CodeModel::Large:
2251 AArch64ISD::WrapperLarge, dl, PtrVT,
2252 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2253 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2254 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2255 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2257 llvm_unreachable("Only small and large code models supported now");
2261 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
2263 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2265 SDValue LHS = Op.getOperand(0);
2266 SDValue RHS = Op.getOperand(1);
2267 SDValue IfTrue = Op.getOperand(2);
2268 SDValue IfFalse = Op.getOperand(3);
2269 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2271 if (LHS.getValueType() == MVT::f128) {
2272 // f128 comparisons are lowered to libcalls, but slot in nicely here
2274 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2276 // If softenSetCCOperands returned a scalar, we need to compare the result
2277 // against zero to select between true and false values.
2278 if (RHS.getNode() == 0) {
2279 RHS = DAG.getConstant(0, LHS.getValueType());
2284 if (LHS.getValueType().isInteger()) {
2287 // Integers are handled in a separate function because the combinations of
2288 // immediates and tests can get hairy and we may want to fiddle things.
2289 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2291 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2292 CmpOp, IfTrue, IfFalse, A64cc);
2295 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2296 // conditional branch, hence FPCCToA64CC can set a second test, where either
2297 // passing is sufficient.
2298 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2299 CondCode = FPCCToA64CC(CC, Alternative);
2300 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2301 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2302 DAG.getCondCode(CC));
2303 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
2305 SetCC, IfTrue, IfFalse, A64cc);
2307 if (Alternative != A64CC::Invalid) {
2308 A64cc = DAG.getConstant(Alternative, MVT::i32);
2309 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2310 SetCC, IfTrue, A64SELECT_CC, A64cc);
2314 return A64SELECT_CC;
2317 // (SELECT testbit, iftrue, iffalse)
2319 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2321 SDValue TheBit = Op.getOperand(0);
2322 SDValue IfTrue = Op.getOperand(1);
2323 SDValue IfFalse = Op.getOperand(2);
2325 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2326 // that as the consumer we are responsible for ignoring rubbish in higher
2328 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2329 DAG.getConstant(1, MVT::i32));
2330 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2331 DAG.getConstant(0, TheBit.getValueType()),
2332 DAG.getCondCode(ISD::SETNE));
2334 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2335 A64CMP, IfTrue, IfFalse,
2336 DAG.getConstant(A64CC::NE, MVT::i32));
2339 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2341 SDValue LHS = Op.getOperand(0);
2342 SDValue RHS = Op.getOperand(1);
2343 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2344 EVT VT = Op.getValueType();
2345 bool Invert = false;
2349 if (LHS.getValueType().isInteger()) {
2351 // Attempt to use Vector Integer Compare Mask Test instruction.
2352 // TST = icmp ne (and (op0, op1), zero).
2353 if (CC == ISD::SETNE) {
2354 if (((LHS.getOpcode() == ISD::AND) &&
2355 ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2356 ((RHS.getOpcode() == ISD::AND) &&
2357 ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2359 SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2360 SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2361 SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2362 return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2366 // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2367 // Note: Compare against Zero does not support unsigned predicates.
2368 if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2369 ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2370 !isUnsignedIntSetCC(CC)) {
2372 // If LHS is the zero value, swap operands and CondCode.
2373 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2374 CC = getSetCCSwappedOperands(CC);
2379 // Ensure valid CondCode for Compare Mask against Zero instruction:
2380 // EQ, GE, GT, LE, LT.
2381 if (ISD::SETNE == CC) {
2386 // Using constant type to differentiate integer and FP compares with zero.
2387 Op1 = DAG.getConstant(0, MVT::i32);
2388 Opcode = AArch64ISD::NEON_CMPZ;
2391 // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2392 // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2396 llvm_unreachable("Illegal integer comparison.");
2412 CC = getSetCCSwappedOperands(CC);
2416 std::swap(LHS, RHS);
2418 Opcode = AArch64ISD::NEON_CMP;
2423 // Generate Compare Mask instr or Compare Mask against Zero instr.
2425 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2428 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2433 // Now handle Floating Point cases.
2434 // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2435 if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2436 ISD::isBuildVectorAllZeros(LHS.getNode())) {
2438 // If LHS is the zero value, swap operands and CondCode.
2439 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2440 CC = getSetCCSwappedOperands(CC);
2445 // Using constant type to differentiate integer and FP compares with zero.
2446 Op1 = DAG.getConstantFP(0, MVT::f32);
2447 Opcode = AArch64ISD::NEON_CMPZ;
2449 // Attempt to use Vector Floating Point Compare Mask instruction.
2452 Opcode = AArch64ISD::NEON_CMP;
2456 // Some register compares have to be implemented with swapped CC and operands,
2457 // e.g.: OLT implemented as OGT with swapped operands.
2458 bool SwapIfRegArgs = false;
2460 // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2461 // EQ, GE, GT, LE, LT.
2462 // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2465 llvm_unreachable("Illegal FP comparison");
2468 Invert = true; // Fallthrough
2476 SwapIfRegArgs = true;
2485 SwapIfRegArgs = true;
2494 SwapIfRegArgs = true;
2503 SwapIfRegArgs = true;
2510 Invert = true; // Fallthrough
2512 // Expand this to (OGT |OLT).
2514 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2516 SwapIfRegArgs = true;
2519 Invert = true; // Fallthrough
2521 // Expand this to (OGE | OLT).
2523 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2525 SwapIfRegArgs = true;
2529 if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2530 CC = getSetCCSwappedOperands(CC);
2531 std::swap(Op0, Op1);
2534 // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2535 SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2537 if (NeonCmpAlt.getNode())
2538 NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2541 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2546 // (SETCC lhs, rhs, condcode)
2548 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2550 SDValue LHS = Op.getOperand(0);
2551 SDValue RHS = Op.getOperand(1);
2552 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2553 EVT VT = Op.getValueType();
2556 return LowerVectorSETCC(Op, DAG);
2558 if (LHS.getValueType() == MVT::f128) {
2559 // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2560 // for the rest of the function (some i32 or i64 values).
2561 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2563 // If softenSetCCOperands returned a scalar, use it.
2564 if (RHS.getNode() == 0) {
2565 assert(LHS.getValueType() == Op.getValueType() &&
2566 "Unexpected setcc expansion!");
2571 if (LHS.getValueType().isInteger()) {
2574 // Integers are handled in a separate function because the combinations of
2575 // immediates and tests can get hairy and we may want to fiddle things.
2576 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2578 return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2579 CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2583 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2584 // conditional branch, hence FPCCToA64CC can set a second test, where either
2585 // passing is sufficient.
2586 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2587 CondCode = FPCCToA64CC(CC, Alternative);
2588 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2589 SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2590 DAG.getCondCode(CC));
2591 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2592 CmpOp, DAG.getConstant(1, VT),
2593 DAG.getConstant(0, VT), A64cc);
2595 if (Alternative != A64CC::Invalid) {
2596 A64cc = DAG.getConstant(Alternative, MVT::i32);
2597 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
2598 DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
2601 return A64SELECT_CC;
2605 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2606 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2607 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2609 // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
2610 // rather than just 8.
2611 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
2612 Op.getOperand(1), Op.getOperand(2),
2613 DAG.getConstant(32, MVT::i32), 8, false, false,
2614 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
2618 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2619 // The layout of the va_list struct is specified in the AArch64 Procedure Call
2620 // Standard, section B.3.
2621 MachineFunction &MF = DAG.getMachineFunction();
2622 AArch64MachineFunctionInfo *FuncInfo
2623 = MF.getInfo<AArch64MachineFunctionInfo>();
2626 SDValue Chain = Op.getOperand(0);
2627 SDValue VAList = Op.getOperand(1);
2628 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2629 SmallVector<SDValue, 4> MemOps;
2631 // void *__stack at offset 0
2632 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
2634 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
2635 MachinePointerInfo(SV), false, false, 0));
2637 // void *__gr_top at offset 8
2638 int GPRSize = FuncInfo->getVariadicGPRSize();
2640 SDValue GRTop, GRTopAddr;
2642 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2643 DAG.getConstant(8, getPointerTy()));
2645 GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
2646 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
2647 DAG.getConstant(GPRSize, getPointerTy()));
2649 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
2650 MachinePointerInfo(SV, 8),
2654 // void *__vr_top at offset 16
2655 int FPRSize = FuncInfo->getVariadicFPRSize();
2657 SDValue VRTop, VRTopAddr;
2658 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2659 DAG.getConstant(16, getPointerTy()));
2661 VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
2662 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
2663 DAG.getConstant(FPRSize, getPointerTy()));
2665 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
2666 MachinePointerInfo(SV, 16),
2670 // int __gr_offs at offset 24
2671 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2672 DAG.getConstant(24, getPointerTy()));
2673 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
2674 GROffsAddr, MachinePointerInfo(SV, 24),
2677 // int __vr_offs at offset 28
2678 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2679 DAG.getConstant(28, getPointerTy()));
2680 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
2681 VROffsAddr, MachinePointerInfo(SV, 28),
2684 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2689 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2690 switch (Op.getOpcode()) {
2691 default: llvm_unreachable("Don't know how to custom lower this!");
2692 case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
2693 case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
2694 case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
2695 case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
2696 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
2697 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
2698 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
2699 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
2700 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
2701 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
2703 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
2704 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2705 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
2706 case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
2707 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
2708 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
2709 case ISD::SELECT: return LowerSELECT(Op, DAG);
2710 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
2711 case ISD::SETCC: return LowerSETCC(Op, DAG);
2712 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
2713 case ISD::VASTART: return LowerVASTART(Op, DAG);
2714 case ISD::BUILD_VECTOR:
2715 return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
2716 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2722 /// Check if the specified splat value corresponds to a valid vector constant
2723 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI). If
2724 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
2726 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2727 unsigned SplatBitSize, SelectionDAG &DAG,
2728 bool is128Bits, NeonModImmType type, EVT &VT,
2729 unsigned &Imm, unsigned &OpCmode) {
2730 switch (SplatBitSize) {
2732 llvm_unreachable("unexpected size for isNeonModifiedImm");
2734 if (type != Neon_Mov_Imm)
2736 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2737 // Neon movi per byte: Op=0, Cmode=1110.
2740 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
2744 // Neon move inst per halfword
2745 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
2746 if ((SplatBits & ~0xff) == 0) {
2747 // Value = 0x00nn is 0x00nn LSL 0
2748 // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
2749 // bic: Op=1, Cmode=1001; orr: Op=0, Cmode=1001
2755 if ((SplatBits & ~0xff00) == 0) {
2756 // Value = 0xnn00 is 0x00nn LSL 8
2757 // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
2758 // bic: Op=1, Cmode=1011; orr: Op=0, Cmode=1011
2760 Imm = SplatBits >> 8;
2764 // can't handle any other
2769 // First the LSL variants (MSL is unusable by some interested instructions).
2771 // Neon move instr per word, shift zeros
2772 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
2773 if ((SplatBits & ~0xff) == 0) {
2774 // Value = 0x000000nn is 0x000000nn LSL 0
2775 // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
2776 // bic: Op=1, Cmode= 0001; orr: Op=0, Cmode= 0001
2782 if ((SplatBits & ~0xff00) == 0) {
2783 // Value = 0x0000nn00 is 0x000000nn LSL 8
2784 // movi: Op=0, Cmode= 0010; mvni: Op=1, Cmode= 0010
2785 // bic: Op=1, Cmode= 0011; orr : Op=0, Cmode= 0011
2787 Imm = SplatBits >> 8;
2791 if ((SplatBits & ~0xff0000) == 0) {
2792 // Value = 0x00nn0000 is 0x000000nn LSL 16
2793 // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
2794 // bic: Op=1, Cmode= 0101; orr: Op=0, Cmode= 0101
2796 Imm = SplatBits >> 16;
2800 if ((SplatBits & ~0xff000000) == 0) {
2801 // Value = 0xnn000000 is 0x000000nn LSL 24
2802 // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
2803 // bic: Op=1, Cmode= 0111; orr: Op=0, Cmode= 0111
2805 Imm = SplatBits >> 24;
2810 // Now the MSL immediates.
2812 // Neon move instr per word, shift ones
2813 if ((SplatBits & ~0xffff) == 0 &&
2814 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
2815 // Value = 0x0000nnff is 0x000000nn MSL 8
2816 // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
2818 Imm = SplatBits >> 8;
2822 if ((SplatBits & ~0xffffff) == 0 &&
2823 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
2824 // Value = 0x00nnffff is 0x000000nn MSL 16
2825 // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
2827 Imm = SplatBits >> 16;
2831 // can't handle any other
2836 if (type != Neon_Mov_Imm)
2838 // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
2839 // movi Op=1, Cmode=1110.
2841 uint64_t BitMask = 0xff;
2843 unsigned ImmMask = 1;
2845 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2846 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
2849 } else if ((SplatBits & BitMask) != 0) {
2856 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
2864 static SDValue PerformANDCombine(SDNode *N,
2865 TargetLowering::DAGCombinerInfo &DCI) {
2867 SelectionDAG &DAG = DCI.DAG;
2869 EVT VT = N->getValueType(0);
2871 // We're looking for an SRA/SHL pair which form an SBFX.
2873 if (VT != MVT::i32 && VT != MVT::i64)
2876 if (!isa<ConstantSDNode>(N->getOperand(1)))
2879 uint64_t TruncMask = N->getConstantOperandVal(1);
2880 if (!isMask_64(TruncMask))
2883 uint64_t Width = CountPopulation_64(TruncMask);
2884 SDValue Shift = N->getOperand(0);
2886 if (Shift.getOpcode() != ISD::SRL)
2889 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
2891 uint64_t LSB = Shift->getConstantOperandVal(1);
2893 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
2896 return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
2897 DAG.getConstant(LSB, MVT::i64),
2898 DAG.getConstant(LSB + Width - 1, MVT::i64));
2901 /// For a true bitfield insert, the bits getting into that contiguous mask
2902 /// should come from the low part of an existing value: they must be formed from
2903 /// a compatible SHL operation (unless they're already low). This function
2904 /// checks that condition and returns the least-significant bit that's
2905 /// intended. If the operation not a field preparation, -1 is returned.
2906 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
2907 SDValue &MaskedVal, uint64_t Mask) {
2908 if (!isShiftedMask_64(Mask))
2911 // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
2912 // instruction. BFI will do a left-shift by LSB before applying the mask we've
2913 // spotted, so in general we should pre-emptively "undo" that by making sure
2914 // the incoming bits have had a right-shift applied to them.
2916 // This right shift, however, will combine with existing left/right shifts. In
2917 // the simplest case of a completely straight bitfield operation, it will be
2918 // expected to completely cancel out with an existing SHL. More complicated
2919 // cases (e.g. bitfield to bitfield copy) may still need a real shift before
2922 uint64_t LSB = countTrailingZeros(Mask);
2923 int64_t ShiftRightRequired = LSB;
2924 if (MaskedVal.getOpcode() == ISD::SHL &&
2925 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2926 ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
2927 MaskedVal = MaskedVal.getOperand(0);
2928 } else if (MaskedVal.getOpcode() == ISD::SRL &&
2929 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2930 ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
2931 MaskedVal = MaskedVal.getOperand(0);
2934 if (ShiftRightRequired > 0)
2935 MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
2936 DAG.getConstant(ShiftRightRequired, MVT::i64));
2937 else if (ShiftRightRequired < 0) {
2938 // We could actually end up with a residual left shift, for example with
2939 // "struc.bitfield = val << 1".
2940 MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
2941 DAG.getConstant(-ShiftRightRequired, MVT::i64));
2947 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
2948 /// a mask and an extension. Returns true if a BFI was found and provides
2949 /// information on its surroundings.
2950 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
2953 if (N.getOpcode() == ISD::ZERO_EXTEND) {
2955 N = N.getOperand(0);
2958 if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
2959 Mask = N->getConstantOperandVal(1);
2960 N = N.getOperand(0);
2962 // Mask is the whole width.
2963 Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
2966 if (N.getOpcode() == AArch64ISD::BFI) {
2974 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
2975 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
2976 /// can often be further combined with a larger mask. Ultimately, we want mask
2977 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
2978 static SDValue tryCombineToBFI(SDNode *N,
2979 TargetLowering::DAGCombinerInfo &DCI,
2980 const AArch64Subtarget *Subtarget) {
2981 SelectionDAG &DAG = DCI.DAG;
2983 EVT VT = N->getValueType(0);
2985 assert(N->getOpcode() == ISD::OR && "Unexpected root");
2987 // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
2988 // abandon the effort.
2989 SDValue LHS = N->getOperand(0);
2990 if (LHS.getOpcode() != ISD::AND)
2994 if (isa<ConstantSDNode>(LHS.getOperand(1)))
2995 LHSMask = LHS->getConstantOperandVal(1);
2999 // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
3000 // is or abandon the effort.
3001 SDValue RHS = N->getOperand(1);
3002 if (RHS.getOpcode() != ISD::AND)
3006 if (isa<ConstantSDNode>(RHS.getOperand(1)))
3007 RHSMask = RHS->getConstantOperandVal(1);
3011 // Can't do anything if the masks are incompatible.
3012 if (LHSMask & RHSMask)
3015 // Now we need one of the masks to be a contiguous field. Without loss of
3016 // generality that should be the RHS one.
3017 SDValue Bitfield = LHS.getOperand(0);
3018 if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3019 // We know that LHS is a candidate new value, and RHS isn't already a better
3021 std::swap(LHS, RHS);
3022 std::swap(LHSMask, RHSMask);
3025 // We've done our best to put the right operands in the right places, all we
3026 // can do now is check whether a BFI exists.
3027 Bitfield = RHS.getOperand(0);
3028 int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3032 uint32_t Width = CountPopulation_64(RHSMask);
3033 assert(Width && "Expected non-zero bitfield width");
3035 SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3036 LHS.getOperand(0), Bitfield,
3037 DAG.getConstant(LSB, MVT::i64),
3038 DAG.getConstant(Width, MVT::i64));
3041 if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3044 return DAG.getNode(ISD::AND, DL, VT, BFI,
3045 DAG.getConstant(LHSMask | RHSMask, VT));
3048 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3049 /// original input. This is surprisingly common because SROA splits things up
3050 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3051 /// on the low (say) byte of a word. This is then orred into the rest of the
3052 /// word afterwards.
3054 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3056 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3057 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3059 static SDValue tryCombineToLargerBFI(SDNode *N,
3060 TargetLowering::DAGCombinerInfo &DCI,
3061 const AArch64Subtarget *Subtarget) {
3062 SelectionDAG &DAG = DCI.DAG;
3064 EVT VT = N->getValueType(0);
3066 // First job is to hunt for a MaskedBFI on either the left or right. Swap
3067 // operands if it's actually on the right.
3069 SDValue PossExtraMask;
3070 uint64_t ExistingMask = 0;
3071 bool Extended = false;
3072 if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3073 PossExtraMask = N->getOperand(1);
3074 else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3075 PossExtraMask = N->getOperand(0);
3079 // We can only combine a BFI with another compatible mask.
3080 if (PossExtraMask.getOpcode() != ISD::AND ||
3081 !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3084 uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3086 // Masks must be compatible.
3087 if (ExtraMask & ExistingMask)
3090 SDValue OldBFIVal = BFI.getOperand(0);
3091 SDValue NewBFIVal = BFI.getOperand(1);
3093 // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3094 // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3095 // need to be made compatible.
3096 assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3097 && "Invalid types for BFI");
3098 OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3099 NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3102 // We need the MaskedBFI to be combined with a mask of the *same* value.
3103 if (PossExtraMask.getOperand(0) != OldBFIVal)
3106 BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3107 OldBFIVal, NewBFIVal,
3108 BFI.getOperand(2), BFI.getOperand(3));
3110 // If the masking is trivial, we don't need to create it.
3111 if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3114 return DAG.getNode(ISD::AND, DL, VT, BFI,
3115 DAG.getConstant(ExtraMask | ExistingMask, VT));
3118 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3119 /// searches for and classifies those shifts.
3120 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3122 if (N.getOpcode() == ISD::SHL)
3124 else if (N.getOpcode() == ISD::SRL)
3129 if (!isa<ConstantSDNode>(N.getOperand(1)))
3132 ShiftAmount = N->getConstantOperandVal(1);
3133 Src = N->getOperand(0);
3137 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3138 /// registers viewed as a high/low pair. This function looks for the pattern:
3139 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3140 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3142 static SDValue tryCombineToEXTR(SDNode *N,
3143 TargetLowering::DAGCombinerInfo &DCI) {
3144 SelectionDAG &DAG = DCI.DAG;
3146 EVT VT = N->getValueType(0);
3148 assert(N->getOpcode() == ISD::OR && "Unexpected root");
3150 if (VT != MVT::i32 && VT != MVT::i64)
3154 uint32_t ShiftLHS = 0;
3156 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3160 uint32_t ShiftRHS = 0;
3162 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3165 // If they're both trying to come from the high part of the register, they're
3166 // not really an EXTR.
3167 if (LHSFromHi == RHSFromHi)
3170 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3174 std::swap(LHS, RHS);
3175 std::swap(ShiftLHS, ShiftRHS);
3178 return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3180 DAG.getConstant(ShiftRHS, MVT::i64));
3183 /// Target-specific dag combine xforms for ISD::OR
3184 static SDValue PerformORCombine(SDNode *N,
3185 TargetLowering::DAGCombinerInfo &DCI,
3186 const AArch64Subtarget *Subtarget) {
3188 SelectionDAG &DAG = DCI.DAG;
3190 EVT VT = N->getValueType(0);
3192 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3195 // Attempt to recognise bitfield-insert operations.
3196 SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3200 // Attempt to combine an existing MaskedBFI operation into one with a larger
3202 Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3206 Res = tryCombineToEXTR(N, DCI);
3210 if (!Subtarget->hasNEON())
3213 // Attempt to use vector immediate-form BSL
3214 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3216 SDValue N0 = N->getOperand(0);
3217 if (N0.getOpcode() != ISD::AND)
3220 SDValue N1 = N->getOperand(1);
3221 if (N1.getOpcode() != ISD::AND)
3224 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3226 unsigned SplatBitSize;
3228 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3230 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3233 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3235 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3237 !HasAnyUndefs && SplatBits0 == ~SplatBits1) {
3238 // Canonicalize the vector type to make instruction selection simpler.
3239 EVT CanonicalVT = VT.is128BitVector() ? MVT::v16i8 : MVT::v8i8;
3240 SDValue Result = DAG.getNode(AArch64ISD::NEON_BSL, DL, CanonicalVT,
3241 N0->getOperand(1), N0->getOperand(0),
3243 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
3251 /// Target-specific dag combine xforms for ISD::SRA
3252 static SDValue PerformSRACombine(SDNode *N,
3253 TargetLowering::DAGCombinerInfo &DCI) {
3255 SelectionDAG &DAG = DCI.DAG;
3257 EVT VT = N->getValueType(0);
3259 // We're looking for an SRA/SHL pair which form an SBFX.
3261 if (VT != MVT::i32 && VT != MVT::i64)
3264 if (!isa<ConstantSDNode>(N->getOperand(1)))
3267 uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3268 SDValue Shift = N->getOperand(0);
3270 if (Shift.getOpcode() != ISD::SHL)
3273 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3276 uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3277 uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3278 uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3280 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3283 return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3284 DAG.getConstant(LSB, MVT::i64),
3285 DAG.getConstant(LSB + Width - 1, MVT::i64));
3288 /// Check if this is a valid build_vector for the immediate operand of
3289 /// a vector shift operation, where all the elements of the build_vector
3290 /// must have the same constant integer value.
3291 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3292 // Ignore bit_converts.
3293 while (Op.getOpcode() == ISD::BITCAST)
3294 Op = Op.getOperand(0);
3295 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3296 APInt SplatBits, SplatUndef;
3297 unsigned SplatBitSize;
3299 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3300 HasAnyUndefs, ElementBits) ||
3301 SplatBitSize > ElementBits)
3303 Cnt = SplatBits.getSExtValue();
3307 /// Check if this is a valid build_vector for the immediate operand of
3308 /// a vector shift left operation. That value must be in the range:
3309 /// 0 <= Value < ElementBits
3310 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3311 assert(VT.isVector() && "vector shift count is not a vector type");
3312 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3313 if (!getVShiftImm(Op, ElementBits, Cnt))
3315 return (Cnt >= 0 && Cnt < ElementBits);
3318 /// Check if this is a valid build_vector for the immediate operand of a
3319 /// vector shift right operation. The value must be in the range:
3320 /// 1 <= Value <= ElementBits
3321 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3322 assert(VT.isVector() && "vector shift count is not a vector type");
3323 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3324 if (!getVShiftImm(Op, ElementBits, Cnt))
3326 return (Cnt >= 1 && Cnt <= ElementBits);
3329 /// Checks for immediate versions of vector shifts and lowers them.
3330 static SDValue PerformShiftCombine(SDNode *N,
3331 TargetLowering::DAGCombinerInfo &DCI,
3332 const AArch64Subtarget *ST) {
3333 SelectionDAG &DAG = DCI.DAG;
3334 EVT VT = N->getValueType(0);
3335 if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3336 return PerformSRACombine(N, DCI);
3338 // Nothing to be done for scalar shifts.
3339 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3340 if (!VT.isVector() || !TLI.isTypeLegal(VT))
3343 assert(ST->hasNEON() && "unexpected vector shift");
3346 switch (N->getOpcode()) {
3348 llvm_unreachable("unexpected shift opcode");
3351 if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3353 DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
3354 DAG.getConstant(Cnt, MVT::i32));
3355 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3361 if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
3363 DAG.getNode(AArch64ISD::NEON_VDUP, SDLoc(N->getOperand(1)), VT,
3364 DAG.getConstant(Cnt, MVT::i32));
3365 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
3373 /// ARM-specific DAG combining for intrinsics.
3374 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3375 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3379 // Don't do anything for most intrinsics.
3382 case Intrinsic::arm_neon_vqshifts:
3383 case Intrinsic::arm_neon_vqshiftu:
3384 EVT VT = N->getOperand(1).getValueType();
3386 if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
3388 unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
3389 ? AArch64ISD::NEON_QSHLs
3390 : AArch64ISD::NEON_QSHLu;
3391 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
3392 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3399 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
3400 DAGCombinerInfo &DCI) const {
3401 switch (N->getOpcode()) {
3403 case ISD::AND: return PerformANDCombine(N, DCI);
3404 case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
3408 return PerformShiftCombine(N, DCI, getSubtarget());
3409 case ISD::INTRINSIC_WO_CHAIN:
3410 return PerformIntrinsicCombine(N, DCI.DAG);
3416 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3417 VT = VT.getScalarType();
3422 switch (VT.getSimpleVT().SimpleTy) {
3436 // If this is a case we can't handle, return null and let the default
3437 // expansion code take care of it.
3439 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3440 const AArch64Subtarget *ST) const {
3442 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3444 EVT VT = Op.getValueType();
3446 APInt SplatBits, SplatUndef;
3447 unsigned SplatBitSize;
3450 // Note we favor lowering MOVI over MVNI.
3451 // This has implications on the definition of patterns in TableGen to select
3452 // BIC immediate instructions but not ORR immediate instructions.
3453 // If this lowering order is changed, TableGen patterns for BIC immediate and
3454 // ORR immediate instructions have to be updated.
3455 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3456 if (SplatBitSize <= 64) {
3457 // First attempt to use vector immediate-form MOVI
3460 unsigned OpCmode = 0;
3462 if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
3463 SplatBitSize, DAG, VT.is128BitVector(),
3464 Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
3465 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3466 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3468 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3469 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
3470 ImmVal, OpCmodeVal);
3471 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3475 // Then attempt to use vector immediate-form MVNI
3476 uint64_t NegatedImm = (~SplatBits).getZExtValue();
3477 if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
3478 DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
3480 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3481 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3482 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3483 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
3484 ImmVal, OpCmodeVal);
3485 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3489 // Attempt to use vector immediate-form FMOV
3490 if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
3491 (VT == MVT::v2f64 && SplatBitSize == 64)) {
3493 SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
3496 if (A64Imms::isFPImm(RealVal, ImmVal)) {
3497 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
3498 return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
3504 unsigned NumElts = VT.getVectorNumElements();
3505 bool isOnlyLowElement = true;
3506 bool usesOnlyOneValue = true;
3507 bool hasDominantValue = false;
3508 bool isConstant = true;
3510 // Map of the number of times a particular SDValue appears in the
3512 DenseMap<SDValue, unsigned> ValueCounts;
3514 for (unsigned i = 0; i < NumElts; ++i) {
3515 SDValue V = Op.getOperand(i);
3516 if (V.getOpcode() == ISD::UNDEF)
3519 isOnlyLowElement = false;
3520 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
3523 ValueCounts.insert(std::make_pair(V, 0));
3524 unsigned &Count = ValueCounts[V];
3526 // Is this value dominant? (takes up more than half of the lanes)
3527 if (++Count > (NumElts / 2)) {
3528 hasDominantValue = true;
3532 if (ValueCounts.size() != 1)
3533 usesOnlyOneValue = false;
3534 if (!Value.getNode() && ValueCounts.size() > 0)
3535 Value = ValueCounts.begin()->first;
3537 if (ValueCounts.size() == 0)
3538 return DAG.getUNDEF(VT);
3540 // Loads are better lowered with insert_vector_elt.
3541 // Keep going if we are hitting this case.
3542 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
3543 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3545 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3546 // Use VDUP for non-constant splats.
3547 if (hasDominantValue && EltSize <= 64) {
3551 // If we are DUPing a value that comes directly from a vector, we could
3552 // just use DUPLANE. We can only do this if the lane being extracted
3553 // is at a constant index, as the DUP from lane instructions only have
3554 // constant-index forms.
3555 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3556 isa<ConstantSDNode>(Value->getOperand(1))) {
3557 N = DAG.getNode(AArch64ISD::NEON_VDUPLANE, DL, VT,
3558 Value->getOperand(0), Value->getOperand(1));
3560 N = DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
3562 if (!usesOnlyOneValue) {
3563 // The dominant value was splatted as 'N', but we now have to insert
3564 // all differing elements.
3565 for (unsigned I = 0; I < NumElts; ++I) {
3566 if (Op.getOperand(I) == Value)
3568 SmallVector<SDValue, 3> Ops;
3570 Ops.push_back(Op.getOperand(I));
3571 Ops.push_back(DAG.getConstant(I, MVT::i32));
3572 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, &Ops[0], 3);
3577 if (usesOnlyOneValue && isConstant) {
3578 return DAG.getNode(AArch64ISD::NEON_VDUP, DL, VT, Value);
3581 // If all elements are constants and the case above didn't get hit, fall back
3582 // to the default expansion, which will generate a load from the constant
3587 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
3588 // know the default expansion would otherwise fall back on something even
3589 // worse. For a vector with one or two non-undef values, that's
3590 // scalar_to_vector for the elements followed by a shuffle (provided the
3591 // shuffle is valid for the target) and materialization element by element
3592 // on the stack followed by a load for everything else.
3593 if (!isConstant && !usesOnlyOneValue) {
3594 SDValue Vec = DAG.getUNDEF(VT);
3595 for (unsigned i = 0 ; i < NumElts; ++i) {
3596 SDValue V = Op.getOperand(i);
3597 if (V.getOpcode() == ISD::UNDEF)
3599 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
3600 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, LaneIdx);
3608 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
3609 SelectionDAG &DAG) const {
3610 SDValue V1 = Op.getOperand(0);
3611 SDValue V2 = Op.getOperand(1);
3613 EVT VT = Op.getValueType();
3614 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
3616 // Convert shuffles that are directly supported on NEON to target-specific
3617 // DAG nodes, instead of keeping them as shuffles and matching them again
3618 // during code selection. This is more efficient and avoids the possibility
3619 // of inconsistencies between legalization and selection.
3620 ArrayRef<int> ShuffleMask = SVN->getMask();
3622 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3623 if (EltSize <= 64) {
3624 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
3625 int Lane = SVN->getSplatIndex();
3626 // If this is undef splat, generate it via "just" vdup, if possible.
3627 if (Lane == -1) Lane = 0;
3629 // Test if V1 is a SCALAR_TO_VECTOR.
3630 if (V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3631 return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT, V1.getOperand(0));
3633 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR.
3634 if (V1.getOpcode() == ISD::BUILD_VECTOR) {
3635 bool IsScalarToVector = true;
3636 for (unsigned i = 0, e = V1.getNumOperands(); i != e; ++i)
3637 if (V1.getOperand(i).getOpcode() != ISD::UNDEF &&
3638 i != (unsigned)Lane) {
3639 IsScalarToVector = false;
3642 if (IsScalarToVector)
3643 return DAG.getNode(AArch64ISD::NEON_VDUP, dl, VT,
3644 V1.getOperand(Lane));
3646 return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
3647 DAG.getConstant(Lane, MVT::i64));
3649 // For shuffle mask like "0, 1, 2, 3, 4, 5, 13, 7", try to generate insert
3650 // by element from V2 to V1 .
3651 // If shuffle mask is like "0, 1, 10, 11, 12, 13, 14, 15", V2 would be a
3652 // better choice to be inserted than V1 as less insert needed, so we count
3653 // element to be inserted for both V1 and V2, and select less one as insert
3656 // Collect elements need to be inserted and their index.
3657 SmallVector<int, 8> NV1Elt;
3658 SmallVector<int, 8> N1Index;
3659 SmallVector<int, 8> NV2Elt;
3660 SmallVector<int, 8> N2Index;
3661 int Length = ShuffleMask.size();
3662 int V1EltNum = V1.getValueType().getVectorNumElements();
3663 for (int I = 0; I != Length; ++I) {
3664 if (ShuffleMask[I] != I) {
3665 NV1Elt.push_back(ShuffleMask[I]);
3666 N1Index.push_back(I);
3669 for (int I = 0; I != Length; ++I) {
3670 if (ShuffleMask[I] != (I + V1EltNum)) {
3671 NV2Elt.push_back(ShuffleMask[I]);
3672 N2Index.push_back(I);
3676 // Decide which to be inserted. If all lanes mismatch, neither V1 nor V2
3677 // will be inserted.
3679 SmallVector<int, 8> InsMasks = NV1Elt;
3680 SmallVector<int, 8> InsIndex = N1Index;
3681 if ((int)NV1Elt.size() != Length || (int)NV2Elt.size() != Length) {
3682 if (NV1Elt.size() > NV2Elt.size()) {
3688 InsV = DAG.getNode(ISD::UNDEF, dl, VT);
3693 for (int I = 0, E = InsMasks.size(); I != E; ++I) {
3695 int Mask = InsMasks[I];
3696 if (Mask > V1EltNum) {
3700 // Any value type smaller than i32 is illegal in AArch64, and this lower
3701 // function is called after legalize pass, so we need to legalize
3703 EVT EltVT = MVT::i32;
3706 PassN = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ExtV,
3707 DAG.getConstant(Mask, MVT::i64));
3708 PassN = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, InsV, PassN,
3709 DAG.getConstant(InsIndex[I], MVT::i64));
3717 AArch64TargetLowering::ConstraintType
3718 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3719 if (Constraint.size() == 1) {
3720 switch (Constraint[0]) {
3722 case 'w': // An FP/SIMD vector register
3723 return C_RegisterClass;
3724 case 'I': // Constant that can be used with an ADD instruction
3725 case 'J': // Constant that can be used with a SUB instruction
3726 case 'K': // Constant that can be used with a 32-bit logical instruction
3727 case 'L': // Constant that can be used with a 64-bit logical instruction
3728 case 'M': // Constant that can be used as a 32-bit MOV immediate
3729 case 'N': // Constant that can be used as a 64-bit MOV immediate
3730 case 'Y': // Floating point constant zero
3731 case 'Z': // Integer constant zero
3733 case 'Q': // A memory reference with base register and no offset
3735 case 'S': // A symbolic address
3740 // FIXME: Ump, Utf, Usa, Ush
3741 // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
3742 // whatever they may be
3743 // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
3744 // Usa: An absolute symbolic address
3745 // Ush: The high part (bits 32:12) of a pc-relative symbolic address
3746 assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
3747 && Constraint != "Ush" && "Unimplemented constraints");
3749 return TargetLowering::getConstraintType(Constraint);
3752 TargetLowering::ConstraintWeight
3753 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
3754 const char *Constraint) const {
3756 llvm_unreachable("Constraint weight unimplemented");
3760 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3761 std::string &Constraint,
3762 std::vector<SDValue> &Ops,
3763 SelectionDAG &DAG) const {
3764 SDValue Result(0, 0);
3766 // Only length 1 constraints are C_Other.
3767 if (Constraint.size() != 1) return;
3769 // Only C_Other constraints get lowered like this. That means constants for us
3770 // so return early if there's no hope the constraint can be lowered.
3772 switch(Constraint[0]) {
3774 case 'I': case 'J': case 'K': case 'L':
3775 case 'M': case 'N': case 'Z': {
3776 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3780 uint64_t CVal = C->getZExtValue();
3783 switch (Constraint[0]) {
3785 // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
3786 // is a peculiarly useless SUB constraint.
3787 llvm_unreachable("Unimplemented C_Other constraint");
3793 if (A64Imms::isLogicalImm(32, CVal, Bits))
3797 if (A64Imms::isLogicalImm(64, CVal, Bits))
3806 Result = DAG.getTargetConstant(CVal, Op.getValueType());
3810 // An absolute symbolic address or label reference.
3811 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
3812 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
3813 GA->getValueType(0));
3814 } else if (const BlockAddressSDNode *BA
3815 = dyn_cast<BlockAddressSDNode>(Op)) {
3816 Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
3817 BA->getValueType(0));
3818 } else if (const ExternalSymbolSDNode *ES
3819 = dyn_cast<ExternalSymbolSDNode>(Op)) {
3820 Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
3821 ES->getValueType(0));
3827 if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
3828 if (CFP->isExactlyValue(0.0)) {
3829 Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
3836 if (Result.getNode()) {
3837 Ops.push_back(Result);
3841 // It's an unknown constraint for us. Let generic code have a go.
3842 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3845 std::pair<unsigned, const TargetRegisterClass*>
3846 AArch64TargetLowering::getRegForInlineAsmConstraint(
3847 const std::string &Constraint,
3849 if (Constraint.size() == 1) {
3850 switch (Constraint[0]) {
3852 if (VT.getSizeInBits() <= 32)
3853 return std::make_pair(0U, &AArch64::GPR32RegClass);
3854 else if (VT == MVT::i64)
3855 return std::make_pair(0U, &AArch64::GPR64RegClass);
3859 return std::make_pair(0U, &AArch64::FPR16RegClass);
3860 else if (VT == MVT::f32)
3861 return std::make_pair(0U, &AArch64::FPR32RegClass);
3862 else if (VT.getSizeInBits() == 64)
3863 return std::make_pair(0U, &AArch64::FPR64RegClass);
3864 else if (VT.getSizeInBits() == 128)
3865 return std::make_pair(0U, &AArch64::FPR128RegClass);
3870 // Use the default implementation in TargetLowering to convert the register
3871 // constraint into a member of a register class.
3872 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3875 /// Represent NEON load and store intrinsics as MemIntrinsicNodes.
3876 /// The associated MachineMemOperands record the alignment specified
3877 /// in the intrinsic calls.
3878 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
3880 unsigned Intrinsic) const {
3881 switch (Intrinsic) {
3882 case Intrinsic::arm_neon_vld1:
3883 case Intrinsic::arm_neon_vld2:
3884 case Intrinsic::arm_neon_vld3:
3885 case Intrinsic::arm_neon_vld4: {
3886 Info.opc = ISD::INTRINSIC_W_CHAIN;
3887 // Conservatively set memVT to the entire set of vectors loaded.
3888 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
3889 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
3890 Info.ptrVal = I.getArgOperand(0);
3892 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
3893 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
3894 Info.vol = false; // volatile loads with NEON intrinsics not supported
3895 Info.readMem = true;
3896 Info.writeMem = false;
3899 case Intrinsic::arm_neon_vst1:
3900 case Intrinsic::arm_neon_vst2:
3901 case Intrinsic::arm_neon_vst3:
3902 case Intrinsic::arm_neon_vst4: {
3903 Info.opc = ISD::INTRINSIC_VOID;
3904 // Conservatively set memVT to the entire set of vectors stored.
3905 unsigned NumElts = 0;
3906 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
3907 Type *ArgTy = I.getArgOperand(ArgI)->getType();
3908 if (!ArgTy->isVectorTy())
3910 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
3912 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
3913 Info.ptrVal = I.getArgOperand(0);
3915 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
3916 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
3917 Info.vol = false; // volatile stores with NEON intrinsics not supported
3918 Info.readMem = false;
3919 Info.writeMem = true;