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::v4i16, Custom);
301 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
302 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
303 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i32, Custom);
304 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f32, Custom);
305 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
306 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1f64, Custom);
307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
309 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Legal);
310 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Legal);
311 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Legal);
312 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Legal);
313 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Legal);
315 setOperationAction(ISD::SETCC, MVT::v8i8, Custom);
316 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
317 setOperationAction(ISD::SETCC, MVT::v4i16, Custom);
318 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
319 setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
320 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
321 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
322 setOperationAction(ISD::SETCC, MVT::v2f32, Custom);
323 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
324 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
328 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
329 // It's reasonably important that this value matches the "natural" legal
330 // promotion from i1 for scalar types. Otherwise LegalizeTypes can get itself
331 // in a twist (e.g. inserting an any_extend which then becomes i64 -> i64).
332 if (!VT.isVector()) return MVT::i32;
333 return VT.changeVectorElementTypeToInteger();
336 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
339 static const unsigned LoadBares[] = {AArch64::LDXR_byte, AArch64::LDXR_hword,
340 AArch64::LDXR_word, AArch64::LDXR_dword};
341 static const unsigned LoadAcqs[] = {AArch64::LDAXR_byte, AArch64::LDAXR_hword,
342 AArch64::LDAXR_word, AArch64::LDAXR_dword};
343 static const unsigned StoreBares[] = {AArch64::STXR_byte, AArch64::STXR_hword,
344 AArch64::STXR_word, AArch64::STXR_dword};
345 static const unsigned StoreRels[] = {AArch64::STLXR_byte,AArch64::STLXR_hword,
346 AArch64::STLXR_word, AArch64::STLXR_dword};
348 const unsigned *LoadOps, *StoreOps;
349 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
354 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
355 StoreOps = StoreRels;
357 StoreOps = StoreBares;
359 assert(isPowerOf2_32(Size) && Size <= 8 &&
360 "unsupported size for atomic binary op!");
362 LdrOpc = LoadOps[Log2_32(Size)];
363 StrOpc = StoreOps[Log2_32(Size)];
367 AArch64TargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
369 unsigned BinOpcode) const {
370 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
371 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
373 const BasicBlock *LLVM_BB = BB->getBasicBlock();
374 MachineFunction *MF = BB->getParent();
375 MachineFunction::iterator It = BB;
378 unsigned dest = MI->getOperand(0).getReg();
379 unsigned ptr = MI->getOperand(1).getReg();
380 unsigned incr = MI->getOperand(2).getReg();
381 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
382 DebugLoc dl = MI->getDebugLoc();
384 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
386 unsigned ldrOpc, strOpc;
387 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
389 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
390 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
391 MF->insert(It, loopMBB);
392 MF->insert(It, exitMBB);
394 // Transfer the remainder of BB and its successor edges to exitMBB.
395 exitMBB->splice(exitMBB->begin(), BB,
396 llvm::next(MachineBasicBlock::iterator(MI)),
398 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
400 const TargetRegisterClass *TRC
401 = Size == 8 ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
402 unsigned scratch = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
406 // fallthrough --> loopMBB
407 BB->addSuccessor(loopMBB);
411 // <binop> scratch, dest, incr
412 // stxr stxr_status, scratch, ptr
413 // cbnz stxr_status, loopMBB
414 // fallthrough --> exitMBB
416 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
418 // All arithmetic operations we'll be creating are designed to take an extra
419 // shift or extend operand, which we can conveniently set to zero.
421 // Operand order needs to go the other way for NAND.
422 if (BinOpcode == AArch64::BICwww_lsl || BinOpcode == AArch64::BICxxx_lsl)
423 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
424 .addReg(incr).addReg(dest).addImm(0);
426 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
427 .addReg(dest).addReg(incr).addImm(0);
430 // From the stxr, the register is GPR32; from the cmp it's GPR32wsp
431 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
432 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
434 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(scratch).addReg(ptr);
435 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
436 .addReg(stxr_status).addMBB(loopMBB);
438 BB->addSuccessor(loopMBB);
439 BB->addSuccessor(exitMBB);
445 MI->eraseFromParent(); // The instruction is gone now.
451 AArch64TargetLowering::emitAtomicBinaryMinMax(MachineInstr *MI,
452 MachineBasicBlock *BB,
455 A64CC::CondCodes Cond) const {
456 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
458 const BasicBlock *LLVM_BB = BB->getBasicBlock();
459 MachineFunction *MF = BB->getParent();
460 MachineFunction::iterator It = BB;
463 unsigned dest = MI->getOperand(0).getReg();
464 unsigned ptr = MI->getOperand(1).getReg();
465 unsigned incr = MI->getOperand(2).getReg();
466 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
468 unsigned oldval = dest;
469 DebugLoc dl = MI->getDebugLoc();
471 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
472 const TargetRegisterClass *TRC, *TRCsp;
474 TRC = &AArch64::GPR64RegClass;
475 TRCsp = &AArch64::GPR64xspRegClass;
477 TRC = &AArch64::GPR32RegClass;
478 TRCsp = &AArch64::GPR32wspRegClass;
481 unsigned ldrOpc, strOpc;
482 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
484 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
485 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
486 MF->insert(It, loopMBB);
487 MF->insert(It, exitMBB);
489 // Transfer the remainder of BB and its successor edges to exitMBB.
490 exitMBB->splice(exitMBB->begin(), BB,
491 llvm::next(MachineBasicBlock::iterator(MI)),
493 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
495 unsigned scratch = MRI.createVirtualRegister(TRC);
496 MRI.constrainRegClass(scratch, TRCsp);
500 // fallthrough --> loopMBB
501 BB->addSuccessor(loopMBB);
505 // cmp incr, dest (, sign extend if necessary)
506 // csel scratch, dest, incr, cond
507 // stxr stxr_status, scratch, ptr
508 // cbnz stxr_status, loopMBB
509 // fallthrough --> exitMBB
511 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
513 // Build compare and cmov instructions.
514 MRI.constrainRegClass(incr, TRCsp);
515 BuildMI(BB, dl, TII->get(CmpOp))
516 .addReg(incr).addReg(oldval).addImm(0);
518 BuildMI(BB, dl, TII->get(Size == 8 ? AArch64::CSELxxxc : AArch64::CSELwwwc),
520 .addReg(oldval).addReg(incr).addImm(Cond);
522 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
523 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
525 BuildMI(BB, dl, TII->get(strOpc), stxr_status)
526 .addReg(scratch).addReg(ptr);
527 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
528 .addReg(stxr_status).addMBB(loopMBB);
530 BB->addSuccessor(loopMBB);
531 BB->addSuccessor(exitMBB);
537 MI->eraseFromParent(); // The instruction is gone now.
543 AArch64TargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
544 MachineBasicBlock *BB,
545 unsigned Size) const {
546 unsigned dest = MI->getOperand(0).getReg();
547 unsigned ptr = MI->getOperand(1).getReg();
548 unsigned oldval = MI->getOperand(2).getReg();
549 unsigned newval = MI->getOperand(3).getReg();
550 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
551 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
552 DebugLoc dl = MI->getDebugLoc();
554 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
555 const TargetRegisterClass *TRCsp;
556 TRCsp = Size == 8 ? &AArch64::GPR64xspRegClass : &AArch64::GPR32wspRegClass;
558 unsigned ldrOpc, strOpc;
559 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
561 MachineFunction *MF = BB->getParent();
562 const BasicBlock *LLVM_BB = BB->getBasicBlock();
563 MachineFunction::iterator It = BB;
564 ++It; // insert the new blocks after the current block
566 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
567 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
568 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
569 MF->insert(It, loop1MBB);
570 MF->insert(It, loop2MBB);
571 MF->insert(It, exitMBB);
573 // Transfer the remainder of BB and its successor edges to exitMBB.
574 exitMBB->splice(exitMBB->begin(), BB,
575 llvm::next(MachineBasicBlock::iterator(MI)),
577 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
581 // fallthrough --> loop1MBB
582 BB->addSuccessor(loop1MBB);
589 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
591 unsigned CmpOp = Size == 8 ? AArch64::CMPxx_lsl : AArch64::CMPww_lsl;
592 MRI.constrainRegClass(dest, TRCsp);
593 BuildMI(BB, dl, TII->get(CmpOp))
594 .addReg(dest).addReg(oldval).addImm(0);
595 BuildMI(BB, dl, TII->get(AArch64::Bcc))
596 .addImm(A64CC::NE).addMBB(exitMBB);
597 BB->addSuccessor(loop2MBB);
598 BB->addSuccessor(exitMBB);
601 // strex stxr_status, newval, [ptr]
602 // cbnz stxr_status, loop1MBB
604 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
605 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
607 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(newval).addReg(ptr);
608 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
609 .addReg(stxr_status).addMBB(loop1MBB);
610 BB->addSuccessor(loop1MBB);
611 BB->addSuccessor(exitMBB);
617 MI->eraseFromParent(); // The instruction is gone now.
623 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
624 MachineBasicBlock *MBB) const {
625 // We materialise the F128CSEL pseudo-instruction using conditional branches
626 // and loads, giving an instruciton sequence like:
635 // Using virtual registers would probably not be beneficial since COPY
636 // instructions are expensive for f128 (there's no actual instruction to
639 // An alternative would be to do an integer-CSEL on some address. E.g.:
644 // csel x0, x0, x1, ne
647 // It's unclear which approach is actually optimal.
648 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
649 MachineFunction *MF = MBB->getParent();
650 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
651 DebugLoc DL = MI->getDebugLoc();
652 MachineFunction::iterator It = MBB;
655 unsigned DestReg = MI->getOperand(0).getReg();
656 unsigned IfTrueReg = MI->getOperand(1).getReg();
657 unsigned IfFalseReg = MI->getOperand(2).getReg();
658 unsigned CondCode = MI->getOperand(3).getImm();
659 bool NZCVKilled = MI->getOperand(4).isKill();
661 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
662 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
663 MF->insert(It, TrueBB);
664 MF->insert(It, EndBB);
666 // Transfer rest of current basic-block to EndBB
667 EndBB->splice(EndBB->begin(), MBB,
668 llvm::next(MachineBasicBlock::iterator(MI)),
670 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
672 // We need somewhere to store the f128 value needed.
673 int ScratchFI = MF->getFrameInfo()->CreateSpillStackObject(16, 16);
675 // [... start of incoming MBB ...]
676 // str qIFFALSE, [sp]
679 BuildMI(MBB, DL, TII->get(AArch64::LSFP128_STR))
681 .addFrameIndex(ScratchFI)
683 BuildMI(MBB, DL, TII->get(AArch64::Bcc))
686 BuildMI(MBB, DL, TII->get(AArch64::Bimm))
688 MBB->addSuccessor(TrueBB);
689 MBB->addSuccessor(EndBB);
693 BuildMI(TrueBB, DL, TII->get(AArch64::LSFP128_STR))
695 .addFrameIndex(ScratchFI)
698 // Note: fallthrough. We can rely on LLVM adding a branch if it reorders the
700 TrueBB->addSuccessor(EndBB);
704 // [... rest of incoming MBB ...]
706 EndBB->addLiveIn(AArch64::NZCV);
707 MachineInstr *StartOfEnd = EndBB->begin();
708 BuildMI(*EndBB, StartOfEnd, DL, TII->get(AArch64::LSFP128_LDR), DestReg)
709 .addFrameIndex(ScratchFI)
712 MI->eraseFromParent();
717 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
718 MachineBasicBlock *MBB) const {
719 switch (MI->getOpcode()) {
720 default: llvm_unreachable("Unhandled instruction with custom inserter");
721 case AArch64::F128CSEL:
722 return EmitF128CSEL(MI, MBB);
723 case AArch64::ATOMIC_LOAD_ADD_I8:
724 return emitAtomicBinary(MI, MBB, 1, AArch64::ADDwww_lsl);
725 case AArch64::ATOMIC_LOAD_ADD_I16:
726 return emitAtomicBinary(MI, MBB, 2, AArch64::ADDwww_lsl);
727 case AArch64::ATOMIC_LOAD_ADD_I32:
728 return emitAtomicBinary(MI, MBB, 4, AArch64::ADDwww_lsl);
729 case AArch64::ATOMIC_LOAD_ADD_I64:
730 return emitAtomicBinary(MI, MBB, 8, AArch64::ADDxxx_lsl);
732 case AArch64::ATOMIC_LOAD_SUB_I8:
733 return emitAtomicBinary(MI, MBB, 1, AArch64::SUBwww_lsl);
734 case AArch64::ATOMIC_LOAD_SUB_I16:
735 return emitAtomicBinary(MI, MBB, 2, AArch64::SUBwww_lsl);
736 case AArch64::ATOMIC_LOAD_SUB_I32:
737 return emitAtomicBinary(MI, MBB, 4, AArch64::SUBwww_lsl);
738 case AArch64::ATOMIC_LOAD_SUB_I64:
739 return emitAtomicBinary(MI, MBB, 8, AArch64::SUBxxx_lsl);
741 case AArch64::ATOMIC_LOAD_AND_I8:
742 return emitAtomicBinary(MI, MBB, 1, AArch64::ANDwww_lsl);
743 case AArch64::ATOMIC_LOAD_AND_I16:
744 return emitAtomicBinary(MI, MBB, 2, AArch64::ANDwww_lsl);
745 case AArch64::ATOMIC_LOAD_AND_I32:
746 return emitAtomicBinary(MI, MBB, 4, AArch64::ANDwww_lsl);
747 case AArch64::ATOMIC_LOAD_AND_I64:
748 return emitAtomicBinary(MI, MBB, 8, AArch64::ANDxxx_lsl);
750 case AArch64::ATOMIC_LOAD_OR_I8:
751 return emitAtomicBinary(MI, MBB, 1, AArch64::ORRwww_lsl);
752 case AArch64::ATOMIC_LOAD_OR_I16:
753 return emitAtomicBinary(MI, MBB, 2, AArch64::ORRwww_lsl);
754 case AArch64::ATOMIC_LOAD_OR_I32:
755 return emitAtomicBinary(MI, MBB, 4, AArch64::ORRwww_lsl);
756 case AArch64::ATOMIC_LOAD_OR_I64:
757 return emitAtomicBinary(MI, MBB, 8, AArch64::ORRxxx_lsl);
759 case AArch64::ATOMIC_LOAD_XOR_I8:
760 return emitAtomicBinary(MI, MBB, 1, AArch64::EORwww_lsl);
761 case AArch64::ATOMIC_LOAD_XOR_I16:
762 return emitAtomicBinary(MI, MBB, 2, AArch64::EORwww_lsl);
763 case AArch64::ATOMIC_LOAD_XOR_I32:
764 return emitAtomicBinary(MI, MBB, 4, AArch64::EORwww_lsl);
765 case AArch64::ATOMIC_LOAD_XOR_I64:
766 return emitAtomicBinary(MI, MBB, 8, AArch64::EORxxx_lsl);
768 case AArch64::ATOMIC_LOAD_NAND_I8:
769 return emitAtomicBinary(MI, MBB, 1, AArch64::BICwww_lsl);
770 case AArch64::ATOMIC_LOAD_NAND_I16:
771 return emitAtomicBinary(MI, MBB, 2, AArch64::BICwww_lsl);
772 case AArch64::ATOMIC_LOAD_NAND_I32:
773 return emitAtomicBinary(MI, MBB, 4, AArch64::BICwww_lsl);
774 case AArch64::ATOMIC_LOAD_NAND_I64:
775 return emitAtomicBinary(MI, MBB, 8, AArch64::BICxxx_lsl);
777 case AArch64::ATOMIC_LOAD_MIN_I8:
778 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::GT);
779 case AArch64::ATOMIC_LOAD_MIN_I16:
780 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::GT);
781 case AArch64::ATOMIC_LOAD_MIN_I32:
782 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::GT);
783 case AArch64::ATOMIC_LOAD_MIN_I64:
784 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::GT);
786 case AArch64::ATOMIC_LOAD_MAX_I8:
787 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::LT);
788 case AArch64::ATOMIC_LOAD_MAX_I16:
789 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::LT);
790 case AArch64::ATOMIC_LOAD_MAX_I32:
791 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LT);
792 case AArch64::ATOMIC_LOAD_MAX_I64:
793 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LT);
795 case AArch64::ATOMIC_LOAD_UMIN_I8:
796 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::HI);
797 case AArch64::ATOMIC_LOAD_UMIN_I16:
798 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::HI);
799 case AArch64::ATOMIC_LOAD_UMIN_I32:
800 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::HI);
801 case AArch64::ATOMIC_LOAD_UMIN_I64:
802 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::HI);
804 case AArch64::ATOMIC_LOAD_UMAX_I8:
805 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::LO);
806 case AArch64::ATOMIC_LOAD_UMAX_I16:
807 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::LO);
808 case AArch64::ATOMIC_LOAD_UMAX_I32:
809 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LO);
810 case AArch64::ATOMIC_LOAD_UMAX_I64:
811 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LO);
813 case AArch64::ATOMIC_SWAP_I8:
814 return emitAtomicBinary(MI, MBB, 1, 0);
815 case AArch64::ATOMIC_SWAP_I16:
816 return emitAtomicBinary(MI, MBB, 2, 0);
817 case AArch64::ATOMIC_SWAP_I32:
818 return emitAtomicBinary(MI, MBB, 4, 0);
819 case AArch64::ATOMIC_SWAP_I64:
820 return emitAtomicBinary(MI, MBB, 8, 0);
822 case AArch64::ATOMIC_CMP_SWAP_I8:
823 return emitAtomicCmpSwap(MI, MBB, 1);
824 case AArch64::ATOMIC_CMP_SWAP_I16:
825 return emitAtomicCmpSwap(MI, MBB, 2);
826 case AArch64::ATOMIC_CMP_SWAP_I32:
827 return emitAtomicCmpSwap(MI, MBB, 4);
828 case AArch64::ATOMIC_CMP_SWAP_I64:
829 return emitAtomicCmpSwap(MI, MBB, 8);
834 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
836 case AArch64ISD::BR_CC: return "AArch64ISD::BR_CC";
837 case AArch64ISD::Call: return "AArch64ISD::Call";
838 case AArch64ISD::FPMOV: return "AArch64ISD::FPMOV";
839 case AArch64ISD::GOTLoad: return "AArch64ISD::GOTLoad";
840 case AArch64ISD::BFI: return "AArch64ISD::BFI";
841 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
842 case AArch64ISD::Ret: return "AArch64ISD::Ret";
843 case AArch64ISD::SBFX: return "AArch64ISD::SBFX";
844 case AArch64ISD::SELECT_CC: return "AArch64ISD::SELECT_CC";
845 case AArch64ISD::SETCC: return "AArch64ISD::SETCC";
846 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
847 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
848 case AArch64ISD::TLSDESCCALL: return "AArch64ISD::TLSDESCCALL";
849 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
850 case AArch64ISD::WrapperSmall: return "AArch64ISD::WrapperSmall";
852 case AArch64ISD::NEON_BSL:
853 return "AArch64ISD::NEON_BSL";
854 case AArch64ISD::NEON_MOVIMM:
855 return "AArch64ISD::NEON_MOVIMM";
856 case AArch64ISD::NEON_MVNIMM:
857 return "AArch64ISD::NEON_MVNIMM";
858 case AArch64ISD::NEON_FMOVIMM:
859 return "AArch64ISD::NEON_FMOVIMM";
860 case AArch64ISD::NEON_CMP:
861 return "AArch64ISD::NEON_CMP";
862 case AArch64ISD::NEON_CMPZ:
863 return "AArch64ISD::NEON_CMPZ";
864 case AArch64ISD::NEON_TST:
865 return "AArch64ISD::NEON_TST";
866 case AArch64ISD::NEON_DUPIMM:
867 return "AArch64ISD::NEON_DUPIMM";
868 case AArch64ISD::NEON_QSHLs:
869 return "AArch64ISD::NEON_QSHLs";
870 case AArch64ISD::NEON_QSHLu:
871 return "AArch64ISD::NEON_QSHLu";
872 case AArch64ISD::NEON_VDUPLANE:
873 return "AArch64ISD::NEON_VDUPLANE";
879 static const uint16_t AArch64FPRArgRegs[] = {
880 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
881 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7
883 static const unsigned NumFPRArgRegs = llvm::array_lengthof(AArch64FPRArgRegs);
885 static const uint16_t AArch64ArgRegs[] = {
886 AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3,
887 AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7
889 static const unsigned NumArgRegs = llvm::array_lengthof(AArch64ArgRegs);
891 static bool CC_AArch64NoMoreRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
892 CCValAssign::LocInfo LocInfo,
893 ISD::ArgFlagsTy ArgFlags, CCState &State) {
894 // Mark all remaining general purpose registers as allocated. We don't
895 // backtrack: if (for example) an i128 gets put on the stack, no subsequent
896 // i64 will go in registers (C.11).
897 for (unsigned i = 0; i < NumArgRegs; ++i)
898 State.AllocateReg(AArch64ArgRegs[i]);
903 #include "AArch64GenCallingConv.inc"
905 CCAssignFn *AArch64TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
908 default: llvm_unreachable("Unsupported calling convention");
909 case CallingConv::Fast:
916 AArch64TargetLowering::SaveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG,
917 SDLoc DL, SDValue &Chain) const {
918 MachineFunction &MF = DAG.getMachineFunction();
919 MachineFrameInfo *MFI = MF.getFrameInfo();
920 AArch64MachineFunctionInfo *FuncInfo
921 = MF.getInfo<AArch64MachineFunctionInfo>();
923 SmallVector<SDValue, 8> MemOps;
925 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(AArch64ArgRegs,
927 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(AArch64FPRArgRegs,
930 unsigned GPRSaveSize = 8 * (NumArgRegs - FirstVariadicGPR);
932 if (GPRSaveSize != 0) {
933 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
935 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
937 for (unsigned i = FirstVariadicGPR; i < NumArgRegs; ++i) {
938 unsigned VReg = MF.addLiveIn(AArch64ArgRegs[i], &AArch64::GPR64RegClass);
939 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
940 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
941 MachinePointerInfo::getStack(i * 8),
943 MemOps.push_back(Store);
944 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
945 DAG.getConstant(8, getPointerTy()));
949 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
951 if (FPRSaveSize != 0) {
952 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
954 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
956 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
957 unsigned VReg = MF.addLiveIn(AArch64FPRArgRegs[i],
958 &AArch64::FPR128RegClass);
959 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
960 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
961 MachinePointerInfo::getStack(i * 16),
963 MemOps.push_back(Store);
964 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
965 DAG.getConstant(16, getPointerTy()));
969 int StackIdx = MFI->CreateFixedObject(8, CCInfo.getNextStackOffset(), true);
971 FuncInfo->setVariadicStackIdx(StackIdx);
972 FuncInfo->setVariadicGPRIdx(GPRIdx);
973 FuncInfo->setVariadicGPRSize(GPRSaveSize);
974 FuncInfo->setVariadicFPRIdx(FPRIdx);
975 FuncInfo->setVariadicFPRSize(FPRSaveSize);
977 if (!MemOps.empty()) {
978 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
985 AArch64TargetLowering::LowerFormalArguments(SDValue Chain,
986 CallingConv::ID CallConv, bool isVarArg,
987 const SmallVectorImpl<ISD::InputArg> &Ins,
988 SDLoc dl, SelectionDAG &DAG,
989 SmallVectorImpl<SDValue> &InVals) const {
990 MachineFunction &MF = DAG.getMachineFunction();
991 AArch64MachineFunctionInfo *FuncInfo
992 = MF.getInfo<AArch64MachineFunctionInfo>();
993 MachineFrameInfo *MFI = MF.getFrameInfo();
994 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
996 SmallVector<CCValAssign, 16> ArgLocs;
997 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
998 getTargetMachine(), ArgLocs, *DAG.getContext());
999 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1001 SmallVector<SDValue, 16> ArgValues;
1004 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1005 CCValAssign &VA = ArgLocs[i];
1006 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1008 if (Flags.isByVal()) {
1009 // Byval is used for small structs and HFAs in the PCS, but the system
1010 // should work in a non-compliant manner for larger structs.
1011 EVT PtrTy = getPointerTy();
1012 int Size = Flags.getByValSize();
1013 unsigned NumRegs = (Size + 7) / 8;
1015 unsigned FrameIdx = MFI->CreateFixedObject(8 * NumRegs,
1016 VA.getLocMemOffset(),
1018 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1019 InVals.push_back(FrameIdxN);
1022 } else if (VA.isRegLoc()) {
1023 MVT RegVT = VA.getLocVT();
1024 const TargetRegisterClass *RC = getRegClassFor(RegVT);
1025 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1027 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1028 } else { // VA.isRegLoc()
1029 assert(VA.isMemLoc());
1031 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
1032 VA.getLocMemOffset(), true);
1034 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1035 ArgValue = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1036 MachinePointerInfo::getFixedStack(FI),
1037 false, false, false, 0);
1042 switch (VA.getLocInfo()) {
1043 default: llvm_unreachable("Unknown loc info!");
1044 case CCValAssign::Full: break;
1045 case CCValAssign::BCvt:
1046 ArgValue = DAG.getNode(ISD::BITCAST,dl, VA.getValVT(), ArgValue);
1048 case CCValAssign::SExt:
1049 case CCValAssign::ZExt:
1050 case CCValAssign::AExt: {
1051 unsigned DestSize = VA.getValVT().getSizeInBits();
1052 unsigned DestSubReg;
1055 case 8: DestSubReg = AArch64::sub_8; break;
1056 case 16: DestSubReg = AArch64::sub_16; break;
1057 case 32: DestSubReg = AArch64::sub_32; break;
1058 case 64: DestSubReg = AArch64::sub_64; break;
1059 default: llvm_unreachable("Unexpected argument promotion");
1062 ArgValue = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1063 VA.getValVT(), ArgValue,
1064 DAG.getTargetConstant(DestSubReg, MVT::i32)),
1070 InVals.push_back(ArgValue);
1074 SaveVarArgRegisters(CCInfo, DAG, dl, Chain);
1076 unsigned StackArgSize = CCInfo.getNextStackOffset();
1077 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1078 // This is a non-standard ABI so by fiat I say we're allowed to make full
1079 // use of the stack area to be popped, which must be aligned to 16 bytes in
1081 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1083 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1084 // a multiple of 16.
1085 FuncInfo->setArgumentStackToRestore(StackArgSize);
1087 // This realignment carries over to the available bytes below. Our own
1088 // callers will guarantee the space is free by giving an aligned value to
1091 // Even if we're not expected to free up the space, it's useful to know how
1092 // much is there while considering tail calls (because we can reuse it).
1093 FuncInfo->setBytesInStackArgArea(StackArgSize);
1099 AArch64TargetLowering::LowerReturn(SDValue Chain,
1100 CallingConv::ID CallConv, bool isVarArg,
1101 const SmallVectorImpl<ISD::OutputArg> &Outs,
1102 const SmallVectorImpl<SDValue> &OutVals,
1103 SDLoc dl, SelectionDAG &DAG) const {
1104 // CCValAssign - represent the assignment of the return value to a location.
1105 SmallVector<CCValAssign, 16> RVLocs;
1107 // CCState - Info about the registers and stack slots.
1108 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1109 getTargetMachine(), RVLocs, *DAG.getContext());
1111 // Analyze outgoing return values.
1112 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv));
1115 SmallVector<SDValue, 4> RetOps(1, Chain);
1117 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1118 // PCS: "If the type, T, of the result of a function is such that
1119 // void func(T arg) would require that arg be passed as a value in a
1120 // register (or set of registers) according to the rules in 5.4, then the
1121 // result is returned in the same registers as would be used for such an
1124 // Otherwise, the caller shall reserve a block of memory of sufficient
1125 // size and alignment to hold the result. The address of the memory block
1126 // shall be passed as an additional argument to the function in x8."
1128 // This is implemented in two places. The register-return values are dealt
1129 // with here, more complex returns are passed as an sret parameter, which
1130 // means we don't have to worry about it during actual return.
1131 CCValAssign &VA = RVLocs[i];
1132 assert(VA.isRegLoc() && "Only register-returns should be created by PCS");
1135 SDValue Arg = OutVals[i];
1137 // There's no convenient note in the ABI about this as there is for normal
1138 // arguments, but it says return values are passed in the same registers as
1139 // an argument would be. I believe that includes the comments about
1140 // unspecified higher bits, putting the burden of widening on the *caller*
1141 // for return values.
1142 switch (VA.getLocInfo()) {
1143 default: llvm_unreachable("Unknown loc info");
1144 case CCValAssign::Full: break;
1145 case CCValAssign::SExt:
1146 case CCValAssign::ZExt:
1147 case CCValAssign::AExt:
1148 // Floating-point values should only be extended when they're going into
1149 // memory, which can't happen here so an integer extend is acceptable.
1150 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1152 case CCValAssign::BCvt:
1153 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1157 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1158 Flag = Chain.getValue(1);
1159 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1162 RetOps[0] = Chain; // Update chain.
1164 // Add the flag if we have it.
1166 RetOps.push_back(Flag);
1168 return DAG.getNode(AArch64ISD::Ret, dl, MVT::Other,
1169 &RetOps[0], RetOps.size());
1173 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1174 SmallVectorImpl<SDValue> &InVals) const {
1175 SelectionDAG &DAG = CLI.DAG;
1177 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1178 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1179 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1180 SDValue Chain = CLI.Chain;
1181 SDValue Callee = CLI.Callee;
1182 bool &IsTailCall = CLI.IsTailCall;
1183 CallingConv::ID CallConv = CLI.CallConv;
1184 bool IsVarArg = CLI.IsVarArg;
1186 MachineFunction &MF = DAG.getMachineFunction();
1187 AArch64MachineFunctionInfo *FuncInfo
1188 = MF.getInfo<AArch64MachineFunctionInfo>();
1189 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1190 bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1191 bool IsSibCall = false;
1194 IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1195 IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1196 Outs, OutVals, Ins, DAG);
1198 // A sibling call is one where we're under the usual C ABI and not planning
1199 // to change that but can still do a tail call:
1200 if (!TailCallOpt && IsTailCall)
1204 SmallVector<CCValAssign, 16> ArgLocs;
1205 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1206 getTargetMachine(), ArgLocs, *DAG.getContext());
1207 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1209 // On AArch64 (and all other architectures I'm aware of) the most this has to
1210 // do is adjust the stack pointer.
1211 unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1213 // Since we're not changing the ABI to make this a tail call, the memory
1214 // operands are already available in the caller's incoming argument space.
1218 // FPDiff is the byte offset of the call's argument area from the callee's.
1219 // Stores to callee stack arguments will be placed in FixedStackSlots offset
1220 // by this amount for a tail call. In a sibling call it must be 0 because the
1221 // caller will deallocate the entire stack and the callee still expects its
1222 // arguments to begin at SP+0. Completely unused for non-tail calls.
1225 if (IsTailCall && !IsSibCall) {
1226 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1228 // FPDiff will be negative if this tail call requires more space than we
1229 // would automatically have in our incoming argument space. Positive if we
1230 // can actually shrink the stack.
1231 FPDiff = NumReusableBytes - NumBytes;
1233 // The stack pointer must be 16-byte aligned at all times it's used for a
1234 // memory operation, which in practice means at *all* times and in
1235 // particular across call boundaries. Therefore our own arguments started at
1236 // a 16-byte aligned SP and the delta applied for the tail call should
1237 // satisfy the same constraint.
1238 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1242 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1245 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1248 SmallVector<SDValue, 8> MemOpChains;
1249 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1251 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1252 CCValAssign &VA = ArgLocs[i];
1253 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1254 SDValue Arg = OutVals[i];
1256 // Callee does the actual widening, so all extensions just use an implicit
1257 // definition of the rest of the Loc. Aesthetically, this would be nicer as
1258 // an ANY_EXTEND, but that isn't valid for floating-point types and this
1259 // alternative works on integer types too.
1260 switch (VA.getLocInfo()) {
1261 default: llvm_unreachable("Unknown loc info!");
1262 case CCValAssign::Full: break;
1263 case CCValAssign::SExt:
1264 case CCValAssign::ZExt:
1265 case CCValAssign::AExt: {
1266 unsigned SrcSize = VA.getValVT().getSizeInBits();
1270 case 8: SrcSubReg = AArch64::sub_8; break;
1271 case 16: SrcSubReg = AArch64::sub_16; break;
1272 case 32: SrcSubReg = AArch64::sub_32; break;
1273 case 64: SrcSubReg = AArch64::sub_64; break;
1274 default: llvm_unreachable("Unexpected argument promotion");
1277 Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1279 DAG.getUNDEF(VA.getLocVT()),
1281 DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1286 case CCValAssign::BCvt:
1287 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1291 if (VA.isRegLoc()) {
1292 // A normal register (sub-) argument. For now we just note it down because
1293 // we want to copy things into registers as late as possible to avoid
1294 // register-pressure (and possibly worse).
1295 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1299 assert(VA.isMemLoc() && "unexpected argument location");
1302 MachinePointerInfo DstInfo;
1304 uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1305 VA.getLocVT().getSizeInBits();
1306 OpSize = (OpSize + 7) / 8;
1307 int32_t Offset = VA.getLocMemOffset() + FPDiff;
1308 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1310 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1311 DstInfo = MachinePointerInfo::getFixedStack(FI);
1313 // Make sure any stack arguments overlapping with where we're storing are
1314 // loaded before this eventual operation. Otherwise they'll be clobbered.
1315 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1317 SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1319 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1320 DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1323 if (Flags.isByVal()) {
1324 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1325 SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1326 Flags.getByValAlign(),
1327 /*isVolatile = */ false,
1328 /*alwaysInline = */ false,
1329 DstInfo, MachinePointerInfo(0));
1330 MemOpChains.push_back(Cpy);
1332 // Normal stack argument, put it where it's needed.
1333 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1335 MemOpChains.push_back(Store);
1339 // The loads and stores generated above shouldn't clash with each
1340 // other. Combining them with this TokenFactor notes that fact for the rest of
1342 if (!MemOpChains.empty())
1343 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1344 &MemOpChains[0], MemOpChains.size());
1346 // Most of the rest of the instructions need to be glued together; we don't
1347 // want assignments to actual registers used by a call to be rearranged by a
1348 // well-meaning scheduler.
1351 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1352 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1353 RegsToPass[i].second, InFlag);
1354 InFlag = Chain.getValue(1);
1357 // The linker is responsible for inserting veneers when necessary to put a
1358 // function call destination in range, so we don't need to bother with a
1360 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1361 const GlobalValue *GV = G->getGlobal();
1362 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1363 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1364 const char *Sym = S->getSymbol();
1365 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1368 // We don't usually want to end the call-sequence here because we would tidy
1369 // the frame up *after* the call, however in the ABI-changing tail-call case
1370 // we've carefully laid out the parameters so that when sp is reset they'll be
1371 // in the correct location.
1372 if (IsTailCall && !IsSibCall) {
1373 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1374 DAG.getIntPtrConstant(0, true), InFlag, dl);
1375 InFlag = Chain.getValue(1);
1378 // We produce the following DAG scheme for the actual call instruction:
1379 // (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1381 // Most arguments aren't going to be used and just keep the values live as
1382 // far as LLVM is concerned. It's expected to be selected as simply "bl
1383 // callee" (for a direct, non-tail call).
1384 std::vector<SDValue> Ops;
1385 Ops.push_back(Chain);
1386 Ops.push_back(Callee);
1389 // Each tail call may have to adjust the stack by a different amount, so
1390 // this information must travel along with the operation for eventual
1391 // consumption by emitEpilogue.
1392 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1395 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1396 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1397 RegsToPass[i].second.getValueType()));
1400 // Add a register mask operand representing the call-preserved registers. This
1401 // is used later in codegen to constrain register-allocation.
1402 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1403 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1404 assert(Mask && "Missing call preserved mask for calling convention");
1405 Ops.push_back(DAG.getRegisterMask(Mask));
1407 // If we needed glue, put it in as the last argument.
1408 if (InFlag.getNode())
1409 Ops.push_back(InFlag);
1411 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1414 return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1417 Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1418 InFlag = Chain.getValue(1);
1420 // Now we can reclaim the stack, just as well do it before working out where
1421 // our return value is.
1423 uint64_t CalleePopBytes
1424 = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1426 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1427 DAG.getIntPtrConstant(CalleePopBytes, true),
1429 InFlag = Chain.getValue(1);
1432 return LowerCallResult(Chain, InFlag, CallConv,
1433 IsVarArg, Ins, dl, DAG, InVals);
1437 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1438 CallingConv::ID CallConv, bool IsVarArg,
1439 const SmallVectorImpl<ISD::InputArg> &Ins,
1440 SDLoc dl, SelectionDAG &DAG,
1441 SmallVectorImpl<SDValue> &InVals) const {
1442 // Assign locations to each value returned by this call.
1443 SmallVector<CCValAssign, 16> RVLocs;
1444 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1445 getTargetMachine(), RVLocs, *DAG.getContext());
1446 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1448 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1449 CCValAssign VA = RVLocs[i];
1451 // Return values that are too big to fit into registers should use an sret
1452 // pointer, so this can be a lot simpler than the main argument code.
1453 assert(VA.isRegLoc() && "Memory locations not expected for call return");
1455 SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1457 Chain = Val.getValue(1);
1458 InFlag = Val.getValue(2);
1460 switch (VA.getLocInfo()) {
1461 default: llvm_unreachable("Unknown loc info!");
1462 case CCValAssign::Full: break;
1463 case CCValAssign::BCvt:
1464 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1466 case CCValAssign::ZExt:
1467 case CCValAssign::SExt:
1468 case CCValAssign::AExt:
1469 // Floating-point arguments only get extended/truncated if they're going
1470 // in memory, so using the integer operation is acceptable here.
1471 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1475 InVals.push_back(Val);
1482 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1483 CallingConv::ID CalleeCC,
1485 bool IsCalleeStructRet,
1486 bool IsCallerStructRet,
1487 const SmallVectorImpl<ISD::OutputArg> &Outs,
1488 const SmallVectorImpl<SDValue> &OutVals,
1489 const SmallVectorImpl<ISD::InputArg> &Ins,
1490 SelectionDAG& DAG) const {
1492 // For CallingConv::C this function knows whether the ABI needs
1493 // changing. That's not true for other conventions so they will have to opt in
1495 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1498 const MachineFunction &MF = DAG.getMachineFunction();
1499 const Function *CallerF = MF.getFunction();
1500 CallingConv::ID CallerCC = CallerF->getCallingConv();
1501 bool CCMatch = CallerCC == CalleeCC;
1503 // Byval parameters hand the function a pointer directly into the stack area
1504 // we want to reuse during a tail call. Working around this *is* possible (see
1505 // X86) but less efficient and uglier in LowerCall.
1506 for (Function::const_arg_iterator i = CallerF->arg_begin(),
1507 e = CallerF->arg_end(); i != e; ++i)
1508 if (i->hasByValAttr())
1511 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1512 if (IsTailCallConvention(CalleeCC) && CCMatch)
1517 // Now we search for cases where we can use a tail call without changing the
1518 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1521 // I want anyone implementing a new calling convention to think long and hard
1522 // about this assert.
1523 assert((!IsVarArg || CalleeCC == CallingConv::C)
1524 && "Unexpected variadic calling convention");
1526 if (IsVarArg && !Outs.empty()) {
1527 // At least two cases here: if caller is fastcc then we can't have any
1528 // memory arguments (we'd be expected to clean up the stack afterwards). If
1529 // caller is C then we could potentially use its argument area.
1531 // FIXME: for now we take the most conservative of these in both cases:
1532 // disallow all variadic memory operands.
1533 SmallVector<CCValAssign, 16> ArgLocs;
1534 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1535 getTargetMachine(), ArgLocs, *DAG.getContext());
1537 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1538 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1539 if (!ArgLocs[i].isRegLoc())
1543 // If the calling conventions do not match, then we'd better make sure the
1544 // results are returned in the same way as what the caller expects.
1546 SmallVector<CCValAssign, 16> RVLocs1;
1547 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1548 getTargetMachine(), RVLocs1, *DAG.getContext());
1549 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1551 SmallVector<CCValAssign, 16> RVLocs2;
1552 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1553 getTargetMachine(), RVLocs2, *DAG.getContext());
1554 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1556 if (RVLocs1.size() != RVLocs2.size())
1558 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1559 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1561 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1563 if (RVLocs1[i].isRegLoc()) {
1564 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1567 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1573 // Nothing more to check if the callee is taking no arguments
1577 SmallVector<CCValAssign, 16> ArgLocs;
1578 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1579 getTargetMachine(), ArgLocs, *DAG.getContext());
1581 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1583 const AArch64MachineFunctionInfo *FuncInfo
1584 = MF.getInfo<AArch64MachineFunctionInfo>();
1586 // If the stack arguments for this call would fit into our own save area then
1587 // the call can be made tail.
1588 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1591 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1592 bool TailCallOpt) const {
1593 return CallCC == CallingConv::Fast && TailCallOpt;
1596 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1597 return CallCC == CallingConv::Fast;
1600 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1602 MachineFrameInfo *MFI,
1603 int ClobberedFI) const {
1604 SmallVector<SDValue, 8> ArgChains;
1605 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1606 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1608 // Include the original chain at the beginning of the list. When this is
1609 // used by target LowerCall hooks, this helps legalize find the
1610 // CALLSEQ_BEGIN node.
1611 ArgChains.push_back(Chain);
1613 // Add a chain value for each stack argument corresponding
1614 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1615 UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1616 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1617 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1618 if (FI->getIndex() < 0) {
1619 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1620 int64_t InLastByte = InFirstByte;
1621 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1623 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1624 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1625 ArgChains.push_back(SDValue(L, 1));
1628 // Build a tokenfactor for all the chains.
1629 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1630 &ArgChains[0], ArgChains.size());
1633 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1635 case ISD::SETEQ: return A64CC::EQ;
1636 case ISD::SETGT: return A64CC::GT;
1637 case ISD::SETGE: return A64CC::GE;
1638 case ISD::SETLT: return A64CC::LT;
1639 case ISD::SETLE: return A64CC::LE;
1640 case ISD::SETNE: return A64CC::NE;
1641 case ISD::SETUGT: return A64CC::HI;
1642 case ISD::SETUGE: return A64CC::HS;
1643 case ISD::SETULT: return A64CC::LO;
1644 case ISD::SETULE: return A64CC::LS;
1645 default: llvm_unreachable("Unexpected condition code");
1649 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1650 // icmp is implemented using adds/subs immediate, which take an unsigned
1651 // 12-bit immediate, optionally shifted left by 12 bits.
1653 // Symmetric by using adds/subs
1657 return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1660 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1661 ISD::CondCode CC, SDValue &A64cc,
1662 SelectionDAG &DAG, SDLoc &dl) const {
1663 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1665 EVT VT = RHSC->getValueType(0);
1666 bool knownInvalid = false;
1668 // I'm not convinced the rest of LLVM handles these edge cases properly, but
1669 // we can at least get it right.
1670 if (isSignedIntSetCC(CC)) {
1671 C = RHSC->getSExtValue();
1672 } else if (RHSC->getZExtValue() > INT64_MAX) {
1673 // A 64-bit constant not representable by a signed 64-bit integer is far
1674 // too big to fit into a SUBS immediate anyway.
1675 knownInvalid = true;
1677 C = RHSC->getZExtValue();
1680 if (!knownInvalid && !isLegalICmpImmediate(C)) {
1681 // Constant does not fit, try adjusting it by one?
1686 if (isLegalICmpImmediate(C-1)) {
1687 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1688 RHS = DAG.getConstant(C-1, VT);
1693 if (isLegalICmpImmediate(C-1)) {
1694 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1695 RHS = DAG.getConstant(C-1, VT);
1700 if (isLegalICmpImmediate(C+1)) {
1701 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1702 RHS = DAG.getConstant(C+1, VT);
1707 if (isLegalICmpImmediate(C+1)) {
1708 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1709 RHS = DAG.getConstant(C+1, VT);
1716 A64CC::CondCodes CondCode = IntCCToA64CC(CC);
1717 A64cc = DAG.getConstant(CondCode, MVT::i32);
1718 return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1719 DAG.getCondCode(CC));
1722 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
1723 A64CC::CondCodes &Alternative) {
1724 A64CC::CondCodes CondCode = A64CC::Invalid;
1725 Alternative = A64CC::Invalid;
1728 default: llvm_unreachable("Unknown FP condition!");
1730 case ISD::SETOEQ: CondCode = A64CC::EQ; break;
1732 case ISD::SETOGT: CondCode = A64CC::GT; break;
1734 case ISD::SETOGE: CondCode = A64CC::GE; break;
1735 case ISD::SETOLT: CondCode = A64CC::MI; break;
1736 case ISD::SETOLE: CondCode = A64CC::LS; break;
1737 case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
1738 case ISD::SETO: CondCode = A64CC::VC; break;
1739 case ISD::SETUO: CondCode = A64CC::VS; break;
1740 case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
1741 case ISD::SETUGT: CondCode = A64CC::HI; break;
1742 case ISD::SETUGE: CondCode = A64CC::PL; break;
1744 case ISD::SETULT: CondCode = A64CC::LT; break;
1746 case ISD::SETULE: CondCode = A64CC::LE; break;
1748 case ISD::SETUNE: CondCode = A64CC::NE; break;
1754 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1756 EVT PtrVT = getPointerTy();
1757 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1759 switch(getTargetMachine().getCodeModel()) {
1760 case CodeModel::Small:
1761 // The most efficient code is PC-relative anyway for the small memory model,
1762 // so we don't need to worry about relocation model.
1763 return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
1764 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1765 AArch64II::MO_NO_FLAG),
1766 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1767 AArch64II::MO_LO12),
1768 DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
1769 case CodeModel::Large:
1771 AArch64ISD::WrapperLarge, DL, PtrVT,
1772 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
1773 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1774 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1775 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1777 llvm_unreachable("Only small and large code models supported now");
1782 // (BRCOND chain, val, dest)
1784 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1786 SDValue Chain = Op.getOperand(0);
1787 SDValue TheBit = Op.getOperand(1);
1788 SDValue DestBB = Op.getOperand(2);
1790 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
1791 // that as the consumer we are responsible for ignoring rubbish in higher
1793 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
1794 DAG.getConstant(1, MVT::i32));
1796 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
1797 DAG.getConstant(0, TheBit.getValueType()),
1798 DAG.getCondCode(ISD::SETNE));
1800 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
1801 A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
1805 // (BR_CC chain, condcode, lhs, rhs, dest)
1807 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1809 SDValue Chain = Op.getOperand(0);
1810 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1811 SDValue LHS = Op.getOperand(2);
1812 SDValue RHS = Op.getOperand(3);
1813 SDValue DestBB = Op.getOperand(4);
1815 if (LHS.getValueType() == MVT::f128) {
1816 // f128 comparisons are lowered to runtime calls by a routine which sets
1817 // LHS, RHS and CC appropriately for the rest of this function to continue.
1818 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
1820 // If softenSetCCOperands returned a scalar, we need to compare the result
1821 // against zero to select between true and false values.
1822 if (RHS.getNode() == 0) {
1823 RHS = DAG.getConstant(0, LHS.getValueType());
1828 if (LHS.getValueType().isInteger()) {
1831 // Integers are handled in a separate function because the combinations of
1832 // immediates and tests can get hairy and we may want to fiddle things.
1833 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
1835 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1836 Chain, CmpOp, A64cc, DestBB);
1839 // Note that some LLVM floating-point CondCodes can't be lowered to a single
1840 // conditional branch, hence FPCCToA64CC can set a second test, where either
1841 // passing is sufficient.
1842 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
1843 CondCode = FPCCToA64CC(CC, Alternative);
1844 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
1845 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1846 DAG.getCondCode(CC));
1847 SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1848 Chain, SetCC, A64cc, DestBB);
1850 if (Alternative != A64CC::Invalid) {
1851 A64cc = DAG.getConstant(Alternative, MVT::i32);
1852 A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1853 A64BR_CC, SetCC, A64cc, DestBB);
1861 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
1862 RTLIB::Libcall Call) const {
1865 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
1866 EVT ArgVT = Op.getOperand(i).getValueType();
1867 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1868 Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
1869 Entry.isSExt = false;
1870 Entry.isZExt = false;
1871 Args.push_back(Entry);
1873 SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
1875 Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
1877 // By default, the input chain to this libcall is the entry node of the
1878 // function. If the libcall is going to be emitted as a tail call then
1879 // isUsedByReturnOnly will change it to the right chain if the return
1880 // node which is being folded has a non-entry input chain.
1881 SDValue InChain = DAG.getEntryNode();
1883 // isTailCall may be true since the callee does not reference caller stack
1884 // frame. Check if it's in the right position.
1885 SDValue TCChain = InChain;
1886 bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
1891 CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
1892 0, getLibcallCallingConv(Call), isTailCall,
1893 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1894 Callee, Args, DAG, SDLoc(Op));
1895 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
1897 if (!CallInfo.second.getNode())
1898 // It's a tailcall, return the chain (which is the DAG root).
1899 return DAG.getRoot();
1901 return CallInfo.first;
1905 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
1906 if (Op.getOperand(0).getValueType() != MVT::f128) {
1907 // It's legal except when f128 is involved
1912 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1914 SDValue SrcVal = Op.getOperand(0);
1915 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1916 /*isSigned*/ false, SDLoc(Op)).first;
1920 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
1921 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1924 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1926 return LowerF128ToCall(Op, DAG, LC);
1930 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
1931 bool IsSigned) const {
1932 if (Op.getOperand(0).getValueType() != MVT::f128) {
1933 // It's legal except when f128 is involved
1939 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1941 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1943 return LowerF128ToCall(Op, DAG, LC);
1947 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
1948 SelectionDAG &DAG) const {
1949 assert(getTargetMachine().getCodeModel() == CodeModel::Large);
1950 assert(getTargetMachine().getRelocationModel() == Reloc::Static);
1952 EVT PtrVT = getPointerTy();
1954 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1955 const GlobalValue *GV = GN->getGlobal();
1957 SDValue GlobalAddr = DAG.getNode(
1958 AArch64ISD::WrapperLarge, dl, PtrVT,
1959 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
1960 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1961 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1962 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1964 if (GN->getOffset() != 0)
1965 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
1966 DAG.getConstant(GN->getOffset(), PtrVT));
1972 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
1973 SelectionDAG &DAG) const {
1974 assert(getTargetMachine().getCodeModel() == CodeModel::Small);
1976 EVT PtrVT = getPointerTy();
1978 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1979 const GlobalValue *GV = GN->getGlobal();
1980 unsigned Alignment = GV->getAlignment();
1981 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1982 if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
1983 // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
1984 // to zero when they remain undefined. In PIC mode the GOT can take care of
1985 // this, but in absolute mode we use a constant pool load.
1987 PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
1988 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1989 AArch64II::MO_NO_FLAG),
1990 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1991 AArch64II::MO_LO12),
1992 DAG.getConstant(8, MVT::i32));
1993 SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
1994 MachinePointerInfo::getConstantPool(),
1995 /*isVolatile=*/ false,
1996 /*isNonTemporal=*/ true,
1997 /*isInvariant=*/ true, 8);
1998 if (GN->getOffset() != 0)
1999 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2000 DAG.getConstant(GN->getOffset(), PtrVT));
2005 if (Alignment == 0) {
2006 const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2007 if (GVPtrTy->getElementType()->isSized()) {
2009 = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2011 // Be conservative if we can't guess, not that it really matters:
2012 // functions and labels aren't valid for loads, and the methods used to
2013 // actually calculate an address work with any alignment.
2018 unsigned char HiFixup, LoFixup;
2019 bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2022 HiFixup = AArch64II::MO_GOT;
2023 LoFixup = AArch64II::MO_GOT_LO12;
2026 HiFixup = AArch64II::MO_NO_FLAG;
2027 LoFixup = AArch64II::MO_LO12;
2030 // AArch64's small model demands the following sequence:
2031 // ADRP x0, somewhere
2032 // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2033 SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2034 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2036 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2038 DAG.getConstant(Alignment, MVT::i32));
2041 GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2045 if (GN->getOffset() != 0)
2046 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2047 DAG.getConstant(GN->getOffset(), PtrVT));
2053 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2054 SelectionDAG &DAG) const {
2055 // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2056 // we make those distinctions here.
2058 switch (getTargetMachine().getCodeModel()) {
2059 case CodeModel::Small:
2060 return LowerGlobalAddressELFSmall(Op, DAG);
2061 case CodeModel::Large:
2062 return LowerGlobalAddressELFLarge(Op, DAG);
2064 llvm_unreachable("Only small and large code models supported now");
2068 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2071 SelectionDAG &DAG) const {
2072 EVT PtrVT = getPointerTy();
2074 // The function we need to call is simply the first entry in the GOT for this
2075 // descriptor, load it in preparation.
2076 SDValue Func, Chain;
2077 Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2080 // The function takes only one argument: the address of the descriptor itself
2083 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2084 Glue = Chain.getValue(1);
2086 // Finally, there's a special calling-convention which means that the lookup
2087 // must preserve all registers (except X0, obviously).
2088 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2089 const AArch64RegisterInfo *A64RI
2090 = static_cast<const AArch64RegisterInfo *>(TRI);
2091 const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2093 // We're now ready to populate the argument list, as with a normal call:
2094 std::vector<SDValue> Ops;
2095 Ops.push_back(Chain);
2096 Ops.push_back(Func);
2097 Ops.push_back(SymAddr);
2098 Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2099 Ops.push_back(DAG.getRegisterMask(Mask));
2100 Ops.push_back(Glue);
2102 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2103 Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2105 Glue = Chain.getValue(1);
2107 // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2108 // back to the generic handling code.
2109 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2113 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2114 SelectionDAG &DAG) const {
2115 assert(getSubtarget()->isTargetELF() &&
2116 "TLS not implemented for non-ELF targets");
2117 assert(getTargetMachine().getCodeModel() == CodeModel::Small
2118 && "TLS only supported in small memory model");
2119 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2121 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2124 EVT PtrVT = getPointerTy();
2126 const GlobalValue *GV = GA->getGlobal();
2128 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2130 if (Model == TLSModel::InitialExec) {
2131 TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2132 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2133 AArch64II::MO_GOTTPREL),
2134 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2135 AArch64II::MO_GOTTPREL_LO12),
2136 DAG.getConstant(8, MVT::i32));
2137 TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2139 } else if (Model == TLSModel::LocalExec) {
2140 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2141 AArch64II::MO_TPREL_G1);
2142 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2143 AArch64II::MO_TPREL_G0_NC);
2145 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2146 DAG.getTargetConstant(1, MVT::i32)), 0);
2147 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2149 DAG.getTargetConstant(0, MVT::i32)), 0);
2150 } else if (Model == TLSModel::GeneralDynamic) {
2151 // Accesses used in this sequence go via the TLS descriptor which lives in
2152 // the GOT. Prepare an address we can use to handle this.
2153 SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2154 AArch64II::MO_TLSDESC);
2155 SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2156 AArch64II::MO_TLSDESC_LO12);
2157 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2159 DAG.getConstant(8, MVT::i32));
2160 SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2162 TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2163 } else if (Model == TLSModel::LocalDynamic) {
2164 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2165 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2166 // the beginning of the module's TLS region, followed by a DTPREL offset
2169 // These accesses will need deduplicating if there's more than one.
2170 AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2171 .getInfo<AArch64MachineFunctionInfo>();
2172 MFI->incNumLocalDynamicTLSAccesses();
2175 // Get the location of _TLS_MODULE_BASE_:
2176 SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2177 AArch64II::MO_TLSDESC);
2178 SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2179 AArch64II::MO_TLSDESC_LO12);
2180 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2182 DAG.getConstant(8, MVT::i32));
2183 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2185 ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2187 // Get the variable's offset from _TLS_MODULE_BASE_
2188 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2189 AArch64II::MO_DTPREL_G1);
2190 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2191 AArch64II::MO_DTPREL_G0_NC);
2193 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2194 DAG.getTargetConstant(0, MVT::i32)), 0);
2195 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2197 DAG.getTargetConstant(0, MVT::i32)), 0);
2199 llvm_unreachable("Unsupported TLS access model");
2202 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2206 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2207 bool IsSigned) const {
2208 if (Op.getValueType() != MVT::f128) {
2209 // Legal for everything except f128.
2215 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2217 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2219 return LowerF128ToCall(Op, DAG, LC);
2224 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2225 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2227 EVT PtrVT = getPointerTy();
2229 // When compiling PIC, jump tables get put in the code section so a static
2230 // relocation-style is acceptable for both cases.
2231 switch (getTargetMachine().getCodeModel()) {
2232 case CodeModel::Small:
2233 return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2234 DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2235 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2236 AArch64II::MO_LO12),
2237 DAG.getConstant(1, MVT::i32));
2238 case CodeModel::Large:
2240 AArch64ISD::WrapperLarge, dl, PtrVT,
2241 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2242 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2243 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2244 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2246 llvm_unreachable("Only small and large code models supported now");
2250 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
2252 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2254 SDValue LHS = Op.getOperand(0);
2255 SDValue RHS = Op.getOperand(1);
2256 SDValue IfTrue = Op.getOperand(2);
2257 SDValue IfFalse = Op.getOperand(3);
2258 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2260 if (LHS.getValueType() == MVT::f128) {
2261 // f128 comparisons are lowered to libcalls, but slot in nicely here
2263 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2265 // If softenSetCCOperands returned a scalar, we need to compare the result
2266 // against zero to select between true and false values.
2267 if (RHS.getNode() == 0) {
2268 RHS = DAG.getConstant(0, LHS.getValueType());
2273 if (LHS.getValueType().isInteger()) {
2276 // Integers are handled in a separate function because the combinations of
2277 // immediates and tests can get hairy and we may want to fiddle things.
2278 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2280 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2281 CmpOp, IfTrue, IfFalse, A64cc);
2284 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2285 // conditional branch, hence FPCCToA64CC can set a second test, where either
2286 // passing is sufficient.
2287 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2288 CondCode = FPCCToA64CC(CC, Alternative);
2289 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2290 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2291 DAG.getCondCode(CC));
2292 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
2294 SetCC, IfTrue, IfFalse, A64cc);
2296 if (Alternative != A64CC::Invalid) {
2297 A64cc = DAG.getConstant(Alternative, MVT::i32);
2298 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2299 SetCC, IfTrue, A64SELECT_CC, A64cc);
2303 return A64SELECT_CC;
2306 // (SELECT testbit, iftrue, iffalse)
2308 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2310 SDValue TheBit = Op.getOperand(0);
2311 SDValue IfTrue = Op.getOperand(1);
2312 SDValue IfFalse = Op.getOperand(2);
2314 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2315 // that as the consumer we are responsible for ignoring rubbish in higher
2317 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2318 DAG.getConstant(1, MVT::i32));
2319 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2320 DAG.getConstant(0, TheBit.getValueType()),
2321 DAG.getCondCode(ISD::SETNE));
2323 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2324 A64CMP, IfTrue, IfFalse,
2325 DAG.getConstant(A64CC::NE, MVT::i32));
2328 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2330 SDValue LHS = Op.getOperand(0);
2331 SDValue RHS = Op.getOperand(1);
2332 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2333 EVT VT = Op.getValueType();
2334 bool Invert = false;
2338 if (LHS.getValueType().isInteger()) {
2340 // Attempt to use Vector Integer Compare Mask Test instruction.
2341 // TST = icmp ne (and (op0, op1), zero).
2342 if (CC == ISD::SETNE) {
2343 if (((LHS.getOpcode() == ISD::AND) &&
2344 ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2345 ((RHS.getOpcode() == ISD::AND) &&
2346 ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2348 SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2349 SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2350 SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2351 return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2355 // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2356 // Note: Compare against Zero does not support unsigned predicates.
2357 if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2358 ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2359 !isUnsignedIntSetCC(CC)) {
2361 // If LHS is the zero value, swap operands and CondCode.
2362 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2363 CC = getSetCCSwappedOperands(CC);
2368 // Ensure valid CondCode for Compare Mask against Zero instruction:
2369 // EQ, GE, GT, LE, LT.
2370 if (ISD::SETNE == CC) {
2375 // Using constant type to differentiate integer and FP compares with zero.
2376 Op1 = DAG.getConstant(0, MVT::i32);
2377 Opcode = AArch64ISD::NEON_CMPZ;
2380 // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2381 // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2385 llvm_unreachable("Illegal integer comparison.");
2401 CC = getSetCCSwappedOperands(CC);
2405 std::swap(LHS, RHS);
2407 Opcode = AArch64ISD::NEON_CMP;
2412 // Generate Compare Mask instr or Compare Mask against Zero instr.
2414 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2417 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2422 // Now handle Floating Point cases.
2423 // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2424 if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2425 ISD::isBuildVectorAllZeros(LHS.getNode())) {
2427 // If LHS is the zero value, swap operands and CondCode.
2428 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2429 CC = getSetCCSwappedOperands(CC);
2434 // Using constant type to differentiate integer and FP compares with zero.
2435 Op1 = DAG.getConstantFP(0, MVT::f32);
2436 Opcode = AArch64ISD::NEON_CMPZ;
2438 // Attempt to use Vector Floating Point Compare Mask instruction.
2441 Opcode = AArch64ISD::NEON_CMP;
2445 // Some register compares have to be implemented with swapped CC and operands,
2446 // e.g.: OLT implemented as OGT with swapped operands.
2447 bool SwapIfRegArgs = false;
2449 // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2450 // EQ, GE, GT, LE, LT.
2451 // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2454 llvm_unreachable("Illegal FP comparison");
2457 Invert = true; // Fallthrough
2465 SwapIfRegArgs = true;
2474 SwapIfRegArgs = true;
2483 SwapIfRegArgs = true;
2492 SwapIfRegArgs = true;
2499 Invert = true; // Fallthrough
2501 // Expand this to (OGT |OLT).
2503 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2505 SwapIfRegArgs = true;
2508 Invert = true; // Fallthrough
2510 // Expand this to (OGE | OLT).
2512 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2514 SwapIfRegArgs = true;
2518 if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2519 CC = getSetCCSwappedOperands(CC);
2520 std::swap(Op0, Op1);
2523 // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2524 SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2526 if (NeonCmpAlt.getNode())
2527 NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2530 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2535 // (SETCC lhs, rhs, condcode)
2537 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2539 SDValue LHS = Op.getOperand(0);
2540 SDValue RHS = Op.getOperand(1);
2541 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2542 EVT VT = Op.getValueType();
2545 return LowerVectorSETCC(Op, DAG);
2547 if (LHS.getValueType() == MVT::f128) {
2548 // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2549 // for the rest of the function (some i32 or i64 values).
2550 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2552 // If softenSetCCOperands returned a scalar, use it.
2553 if (RHS.getNode() == 0) {
2554 assert(LHS.getValueType() == Op.getValueType() &&
2555 "Unexpected setcc expansion!");
2560 if (LHS.getValueType().isInteger()) {
2563 // Integers are handled in a separate function because the combinations of
2564 // immediates and tests can get hairy and we may want to fiddle things.
2565 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2567 return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2568 CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2572 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2573 // conditional branch, hence FPCCToA64CC can set a second test, where either
2574 // passing is sufficient.
2575 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2576 CondCode = FPCCToA64CC(CC, Alternative);
2577 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2578 SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2579 DAG.getCondCode(CC));
2580 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2581 CmpOp, DAG.getConstant(1, VT),
2582 DAG.getConstant(0, VT), A64cc);
2584 if (Alternative != A64CC::Invalid) {
2585 A64cc = DAG.getConstant(Alternative, MVT::i32);
2586 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
2587 DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
2590 return A64SELECT_CC;
2594 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2595 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2596 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2598 // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
2599 // rather than just 8.
2600 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
2601 Op.getOperand(1), Op.getOperand(2),
2602 DAG.getConstant(32, MVT::i32), 8, false, false,
2603 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
2607 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2608 // The layout of the va_list struct is specified in the AArch64 Procedure Call
2609 // Standard, section B.3.
2610 MachineFunction &MF = DAG.getMachineFunction();
2611 AArch64MachineFunctionInfo *FuncInfo
2612 = MF.getInfo<AArch64MachineFunctionInfo>();
2615 SDValue Chain = Op.getOperand(0);
2616 SDValue VAList = Op.getOperand(1);
2617 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2618 SmallVector<SDValue, 4> MemOps;
2620 // void *__stack at offset 0
2621 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
2623 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
2624 MachinePointerInfo(SV), false, false, 0));
2626 // void *__gr_top at offset 8
2627 int GPRSize = FuncInfo->getVariadicGPRSize();
2629 SDValue GRTop, GRTopAddr;
2631 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2632 DAG.getConstant(8, getPointerTy()));
2634 GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
2635 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
2636 DAG.getConstant(GPRSize, getPointerTy()));
2638 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
2639 MachinePointerInfo(SV, 8),
2643 // void *__vr_top at offset 16
2644 int FPRSize = FuncInfo->getVariadicFPRSize();
2646 SDValue VRTop, VRTopAddr;
2647 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2648 DAG.getConstant(16, getPointerTy()));
2650 VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
2651 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
2652 DAG.getConstant(FPRSize, getPointerTy()));
2654 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
2655 MachinePointerInfo(SV, 16),
2659 // int __gr_offs at offset 24
2660 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2661 DAG.getConstant(24, getPointerTy()));
2662 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
2663 GROffsAddr, MachinePointerInfo(SV, 24),
2666 // int __vr_offs at offset 28
2667 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2668 DAG.getConstant(28, getPointerTy()));
2669 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
2670 VROffsAddr, MachinePointerInfo(SV, 28),
2673 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2678 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2679 switch (Op.getOpcode()) {
2680 default: llvm_unreachable("Don't know how to custom lower this!");
2681 case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
2682 case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
2683 case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
2684 case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
2685 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
2686 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
2687 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
2688 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
2689 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
2690 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
2692 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
2693 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2694 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
2695 case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
2696 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
2697 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
2698 case ISD::SELECT: return LowerSELECT(Op, DAG);
2699 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
2700 case ISD::SETCC: return LowerSETCC(Op, DAG);
2701 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
2702 case ISD::VASTART: return LowerVASTART(Op, DAG);
2703 case ISD::BUILD_VECTOR:
2704 return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
2705 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2711 /// Check if the specified splat value corresponds to a valid vector constant
2712 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI). If
2713 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
2715 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2716 unsigned SplatBitSize, SelectionDAG &DAG,
2717 bool is128Bits, NeonModImmType type, EVT &VT,
2718 unsigned &Imm, unsigned &OpCmode) {
2719 switch (SplatBitSize) {
2721 llvm_unreachable("unexpected size for isNeonModifiedImm");
2723 if (type != Neon_Mov_Imm)
2725 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2726 // Neon movi per byte: Op=0, Cmode=1110.
2729 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
2733 // Neon move inst per halfword
2734 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
2735 if ((SplatBits & ~0xff) == 0) {
2736 // Value = 0x00nn is 0x00nn LSL 0
2737 // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
2738 // bic: Op=1, Cmode=1001; orr: Op=0, Cmode=1001
2744 if ((SplatBits & ~0xff00) == 0) {
2745 // Value = 0xnn00 is 0x00nn LSL 8
2746 // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
2747 // bic: Op=1, Cmode=1011; orr: Op=0, Cmode=1011
2749 Imm = SplatBits >> 8;
2753 // can't handle any other
2758 // First the LSL variants (MSL is unusable by some interested instructions).
2760 // Neon move instr per word, shift zeros
2761 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
2762 if ((SplatBits & ~0xff) == 0) {
2763 // Value = 0x000000nn is 0x000000nn LSL 0
2764 // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
2765 // bic: Op=1, Cmode= 0001; orr: Op=0, Cmode= 0001
2771 if ((SplatBits & ~0xff00) == 0) {
2772 // Value = 0x0000nn00 is 0x000000nn LSL 8
2773 // movi: Op=0, Cmode= 0010; mvni: Op=1, Cmode= 0010
2774 // bic: Op=1, Cmode= 0011; orr : Op=0, Cmode= 0011
2776 Imm = SplatBits >> 8;
2780 if ((SplatBits & ~0xff0000) == 0) {
2781 // Value = 0x00nn0000 is 0x000000nn LSL 16
2782 // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
2783 // bic: Op=1, Cmode= 0101; orr: Op=0, Cmode= 0101
2785 Imm = SplatBits >> 16;
2789 if ((SplatBits & ~0xff000000) == 0) {
2790 // Value = 0xnn000000 is 0x000000nn LSL 24
2791 // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
2792 // bic: Op=1, Cmode= 0111; orr: Op=0, Cmode= 0111
2794 Imm = SplatBits >> 24;
2799 // Now the MSL immediates.
2801 // Neon move instr per word, shift ones
2802 if ((SplatBits & ~0xffff) == 0 &&
2803 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
2804 // Value = 0x0000nnff is 0x000000nn MSL 8
2805 // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
2807 Imm = SplatBits >> 8;
2811 if ((SplatBits & ~0xffffff) == 0 &&
2812 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
2813 // Value = 0x00nnffff is 0x000000nn MSL 16
2814 // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
2816 Imm = SplatBits >> 16;
2820 // can't handle any other
2825 if (type != Neon_Mov_Imm)
2827 // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
2828 // movi Op=1, Cmode=1110.
2830 uint64_t BitMask = 0xff;
2832 unsigned ImmMask = 1;
2834 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2835 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
2838 } else if ((SplatBits & BitMask) != 0) {
2845 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
2853 static SDValue PerformANDCombine(SDNode *N,
2854 TargetLowering::DAGCombinerInfo &DCI) {
2856 SelectionDAG &DAG = DCI.DAG;
2858 EVT VT = N->getValueType(0);
2860 // We're looking for an SRA/SHL pair which form an SBFX.
2862 if (VT != MVT::i32 && VT != MVT::i64)
2865 if (!isa<ConstantSDNode>(N->getOperand(1)))
2868 uint64_t TruncMask = N->getConstantOperandVal(1);
2869 if (!isMask_64(TruncMask))
2872 uint64_t Width = CountPopulation_64(TruncMask);
2873 SDValue Shift = N->getOperand(0);
2875 if (Shift.getOpcode() != ISD::SRL)
2878 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
2880 uint64_t LSB = Shift->getConstantOperandVal(1);
2882 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
2885 return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
2886 DAG.getConstant(LSB, MVT::i64),
2887 DAG.getConstant(LSB + Width - 1, MVT::i64));
2890 /// For a true bitfield insert, the bits getting into that contiguous mask
2891 /// should come from the low part of an existing value: they must be formed from
2892 /// a compatible SHL operation (unless they're already low). This function
2893 /// checks that condition and returns the least-significant bit that's
2894 /// intended. If the operation not a field preparation, -1 is returned.
2895 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
2896 SDValue &MaskedVal, uint64_t Mask) {
2897 if (!isShiftedMask_64(Mask))
2900 // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
2901 // instruction. BFI will do a left-shift by LSB before applying the mask we've
2902 // spotted, so in general we should pre-emptively "undo" that by making sure
2903 // the incoming bits have had a right-shift applied to them.
2905 // This right shift, however, will combine with existing left/right shifts. In
2906 // the simplest case of a completely straight bitfield operation, it will be
2907 // expected to completely cancel out with an existing SHL. More complicated
2908 // cases (e.g. bitfield to bitfield copy) may still need a real shift before
2911 uint64_t LSB = countTrailingZeros(Mask);
2912 int64_t ShiftRightRequired = LSB;
2913 if (MaskedVal.getOpcode() == ISD::SHL &&
2914 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2915 ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
2916 MaskedVal = MaskedVal.getOperand(0);
2917 } else if (MaskedVal.getOpcode() == ISD::SRL &&
2918 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2919 ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
2920 MaskedVal = MaskedVal.getOperand(0);
2923 if (ShiftRightRequired > 0)
2924 MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
2925 DAG.getConstant(ShiftRightRequired, MVT::i64));
2926 else if (ShiftRightRequired < 0) {
2927 // We could actually end up with a residual left shift, for example with
2928 // "struc.bitfield = val << 1".
2929 MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
2930 DAG.getConstant(-ShiftRightRequired, MVT::i64));
2936 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
2937 /// a mask and an extension. Returns true if a BFI was found and provides
2938 /// information on its surroundings.
2939 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
2942 if (N.getOpcode() == ISD::ZERO_EXTEND) {
2944 N = N.getOperand(0);
2947 if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
2948 Mask = N->getConstantOperandVal(1);
2949 N = N.getOperand(0);
2951 // Mask is the whole width.
2952 Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
2955 if (N.getOpcode() == AArch64ISD::BFI) {
2963 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
2964 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
2965 /// can often be further combined with a larger mask. Ultimately, we want mask
2966 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
2967 static SDValue tryCombineToBFI(SDNode *N,
2968 TargetLowering::DAGCombinerInfo &DCI,
2969 const AArch64Subtarget *Subtarget) {
2970 SelectionDAG &DAG = DCI.DAG;
2972 EVT VT = N->getValueType(0);
2974 assert(N->getOpcode() == ISD::OR && "Unexpected root");
2976 // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
2977 // abandon the effort.
2978 SDValue LHS = N->getOperand(0);
2979 if (LHS.getOpcode() != ISD::AND)
2983 if (isa<ConstantSDNode>(LHS.getOperand(1)))
2984 LHSMask = LHS->getConstantOperandVal(1);
2988 // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
2989 // is or abandon the effort.
2990 SDValue RHS = N->getOperand(1);
2991 if (RHS.getOpcode() != ISD::AND)
2995 if (isa<ConstantSDNode>(RHS.getOperand(1)))
2996 RHSMask = RHS->getConstantOperandVal(1);
3000 // Can't do anything if the masks are incompatible.
3001 if (LHSMask & RHSMask)
3004 // Now we need one of the masks to be a contiguous field. Without loss of
3005 // generality that should be the RHS one.
3006 SDValue Bitfield = LHS.getOperand(0);
3007 if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3008 // We know that LHS is a candidate new value, and RHS isn't already a better
3010 std::swap(LHS, RHS);
3011 std::swap(LHSMask, RHSMask);
3014 // We've done our best to put the right operands in the right places, all we
3015 // can do now is check whether a BFI exists.
3016 Bitfield = RHS.getOperand(0);
3017 int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3021 uint32_t Width = CountPopulation_64(RHSMask);
3022 assert(Width && "Expected non-zero bitfield width");
3024 SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3025 LHS.getOperand(0), Bitfield,
3026 DAG.getConstant(LSB, MVT::i64),
3027 DAG.getConstant(Width, MVT::i64));
3030 if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3033 return DAG.getNode(ISD::AND, DL, VT, BFI,
3034 DAG.getConstant(LHSMask | RHSMask, VT));
3037 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3038 /// original input. This is surprisingly common because SROA splits things up
3039 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3040 /// on the low (say) byte of a word. This is then orred into the rest of the
3041 /// word afterwards.
3043 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3045 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3046 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3048 static SDValue tryCombineToLargerBFI(SDNode *N,
3049 TargetLowering::DAGCombinerInfo &DCI,
3050 const AArch64Subtarget *Subtarget) {
3051 SelectionDAG &DAG = DCI.DAG;
3053 EVT VT = N->getValueType(0);
3055 // First job is to hunt for a MaskedBFI on either the left or right. Swap
3056 // operands if it's actually on the right.
3058 SDValue PossExtraMask;
3059 uint64_t ExistingMask = 0;
3060 bool Extended = false;
3061 if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3062 PossExtraMask = N->getOperand(1);
3063 else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3064 PossExtraMask = N->getOperand(0);
3068 // We can only combine a BFI with another compatible mask.
3069 if (PossExtraMask.getOpcode() != ISD::AND ||
3070 !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3073 uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3075 // Masks must be compatible.
3076 if (ExtraMask & ExistingMask)
3079 SDValue OldBFIVal = BFI.getOperand(0);
3080 SDValue NewBFIVal = BFI.getOperand(1);
3082 // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3083 // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3084 // need to be made compatible.
3085 assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3086 && "Invalid types for BFI");
3087 OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3088 NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3091 // We need the MaskedBFI to be combined with a mask of the *same* value.
3092 if (PossExtraMask.getOperand(0) != OldBFIVal)
3095 BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3096 OldBFIVal, NewBFIVal,
3097 BFI.getOperand(2), BFI.getOperand(3));
3099 // If the masking is trivial, we don't need to create it.
3100 if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3103 return DAG.getNode(ISD::AND, DL, VT, BFI,
3104 DAG.getConstant(ExtraMask | ExistingMask, VT));
3107 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3108 /// searches for and classifies those shifts.
3109 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3111 if (N.getOpcode() == ISD::SHL)
3113 else if (N.getOpcode() == ISD::SRL)
3118 if (!isa<ConstantSDNode>(N.getOperand(1)))
3121 ShiftAmount = N->getConstantOperandVal(1);
3122 Src = N->getOperand(0);
3126 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3127 /// registers viewed as a high/low pair. This function looks for the pattern:
3128 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3129 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3131 static SDValue tryCombineToEXTR(SDNode *N,
3132 TargetLowering::DAGCombinerInfo &DCI) {
3133 SelectionDAG &DAG = DCI.DAG;
3135 EVT VT = N->getValueType(0);
3137 assert(N->getOpcode() == ISD::OR && "Unexpected root");
3139 if (VT != MVT::i32 && VT != MVT::i64)
3143 uint32_t ShiftLHS = 0;
3145 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3149 uint32_t ShiftRHS = 0;
3151 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3154 // If they're both trying to come from the high part of the register, they're
3155 // not really an EXTR.
3156 if (LHSFromHi == RHSFromHi)
3159 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3163 std::swap(LHS, RHS);
3164 std::swap(ShiftLHS, ShiftRHS);
3167 return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3169 DAG.getConstant(ShiftRHS, MVT::i64));
3172 /// Target-specific dag combine xforms for ISD::OR
3173 static SDValue PerformORCombine(SDNode *N,
3174 TargetLowering::DAGCombinerInfo &DCI,
3175 const AArch64Subtarget *Subtarget) {
3177 SelectionDAG &DAG = DCI.DAG;
3179 EVT VT = N->getValueType(0);
3181 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3184 // Attempt to recognise bitfield-insert operations.
3185 SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3189 // Attempt to combine an existing MaskedBFI operation into one with a larger
3191 Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3195 Res = tryCombineToEXTR(N, DCI);
3199 if (!Subtarget->hasNEON())
3202 // Attempt to use vector immediate-form BSL
3203 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3205 SDValue N0 = N->getOperand(0);
3206 if (N0.getOpcode() != ISD::AND)
3209 SDValue N1 = N->getOperand(1);
3210 if (N1.getOpcode() != ISD::AND)
3213 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3215 unsigned SplatBitSize;
3217 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3219 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3222 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3224 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3226 !HasAnyUndefs && SplatBits0 == ~SplatBits1) {
3227 // Canonicalize the vector type to make instruction selection simpler.
3228 EVT CanonicalVT = VT.is128BitVector() ? MVT::v16i8 : MVT::v8i8;
3229 SDValue Result = DAG.getNode(AArch64ISD::NEON_BSL, DL, CanonicalVT,
3230 N0->getOperand(1), N0->getOperand(0),
3232 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
3240 /// Target-specific dag combine xforms for ISD::SRA
3241 static SDValue PerformSRACombine(SDNode *N,
3242 TargetLowering::DAGCombinerInfo &DCI) {
3244 SelectionDAG &DAG = DCI.DAG;
3246 EVT VT = N->getValueType(0);
3248 // We're looking for an SRA/SHL pair which form an SBFX.
3250 if (VT != MVT::i32 && VT != MVT::i64)
3253 if (!isa<ConstantSDNode>(N->getOperand(1)))
3256 uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3257 SDValue Shift = N->getOperand(0);
3259 if (Shift.getOpcode() != ISD::SHL)
3262 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3265 uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3266 uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3267 uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3269 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3272 return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3273 DAG.getConstant(LSB, MVT::i64),
3274 DAG.getConstant(LSB + Width - 1, MVT::i64));
3277 /// Check if this is a valid build_vector for the immediate operand of
3278 /// a vector shift operation, where all the elements of the build_vector
3279 /// must have the same constant integer value.
3280 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3281 // Ignore bit_converts.
3282 while (Op.getOpcode() == ISD::BITCAST)
3283 Op = Op.getOperand(0);
3284 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3285 APInt SplatBits, SplatUndef;
3286 unsigned SplatBitSize;
3288 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3289 HasAnyUndefs, ElementBits) ||
3290 SplatBitSize > ElementBits)
3292 Cnt = SplatBits.getSExtValue();
3296 /// Check if this is a valid build_vector for the immediate operand of
3297 /// a vector shift left operation. That value must be in the range:
3298 /// 0 <= Value < ElementBits
3299 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3300 assert(VT.isVector() && "vector shift count is not a vector type");
3301 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3302 if (!getVShiftImm(Op, ElementBits, Cnt))
3304 return (Cnt >= 0 && Cnt < ElementBits);
3307 /// Check if this is a valid build_vector for the immediate operand of a
3308 /// vector shift right operation. The value must be in the range:
3309 /// 1 <= Value <= ElementBits
3310 static bool isVShiftRImm(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 >= 1 && Cnt <= ElementBits);
3318 /// Checks for immediate versions of vector shifts and lowers them.
3319 static SDValue PerformShiftCombine(SDNode *N,
3320 TargetLowering::DAGCombinerInfo &DCI,
3321 const AArch64Subtarget *ST) {
3322 SelectionDAG &DAG = DCI.DAG;
3323 EVT VT = N->getValueType(0);
3324 if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3325 return PerformSRACombine(N, DCI);
3327 // Nothing to be done for scalar shifts.
3328 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3329 if (!VT.isVector() || !TLI.isTypeLegal(VT))
3332 assert(ST->hasNEON() && "unexpected vector shift");
3335 switch (N->getOpcode()) {
3337 llvm_unreachable("unexpected shift opcode");
3340 if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3342 DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3343 DAG.getConstant(Cnt, MVT::i32));
3344 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3350 if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
3352 DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3353 DAG.getConstant(Cnt, MVT::i32));
3354 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
3362 /// ARM-specific DAG combining for intrinsics.
3363 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3364 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3368 // Don't do anything for most intrinsics.
3371 case Intrinsic::arm_neon_vqshifts:
3372 case Intrinsic::arm_neon_vqshiftu:
3373 EVT VT = N->getOperand(1).getValueType();
3375 if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
3377 unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
3378 ? AArch64ISD::NEON_QSHLs
3379 : AArch64ISD::NEON_QSHLu;
3380 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
3381 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3388 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
3389 DAGCombinerInfo &DCI) const {
3390 switch (N->getOpcode()) {
3392 case ISD::AND: return PerformANDCombine(N, DCI);
3393 case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
3397 return PerformShiftCombine(N, DCI, getSubtarget());
3398 case ISD::INTRINSIC_WO_CHAIN:
3399 return PerformIntrinsicCombine(N, DCI.DAG);
3405 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3406 VT = VT.getScalarType();
3411 switch (VT.getSimpleVT().SimpleTy) {
3425 // If this is a case we can't handle, return null and let the default
3426 // expansion code take care of it.
3428 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3429 const AArch64Subtarget *ST) const {
3431 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3433 EVT VT = Op.getValueType();
3435 APInt SplatBits, SplatUndef;
3436 unsigned SplatBitSize;
3439 // Note we favor lowering MOVI over MVNI.
3440 // This has implications on the definition of patterns in TableGen to select
3441 // BIC immediate instructions but not ORR immediate instructions.
3442 // If this lowering order is changed, TableGen patterns for BIC immediate and
3443 // ORR immediate instructions have to be updated.
3444 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3445 if (SplatBitSize <= 64) {
3446 // First attempt to use vector immediate-form MOVI
3449 unsigned OpCmode = 0;
3451 if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
3452 SplatBitSize, DAG, VT.is128BitVector(),
3453 Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
3454 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3455 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3457 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3458 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
3459 ImmVal, OpCmodeVal);
3460 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3464 // Then attempt to use vector immediate-form MVNI
3465 uint64_t NegatedImm = (~SplatBits).getZExtValue();
3466 if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
3467 DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
3469 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3470 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3471 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3472 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
3473 ImmVal, OpCmodeVal);
3474 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3478 // Attempt to use vector immediate-form FMOV
3479 if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
3480 (VT == MVT::v2f64 && SplatBitSize == 64)) {
3482 SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
3485 if (A64Imms::isFPImm(RealVal, ImmVal)) {
3486 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
3487 return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
3496 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
3497 SelectionDAG &DAG) const {
3498 SDValue V1 = Op.getOperand(0);
3500 EVT VT = Op.getValueType();
3501 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
3503 // Convert shuffles that are directly supported on NEON to target-specific
3504 // DAG nodes, instead of keeping them as shuffles and matching them again
3505 // during code selection. This is more efficient and avoids the possibility
3506 // of inconsistencies between legalization and selection.
3507 ArrayRef<int> ShuffleMask = SVN->getMask();
3509 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3510 if (EltSize <= 64) {
3511 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
3512 int Lane = SVN->getSplatIndex();
3513 // If this is undef splat, generate it via "just" vdup, if possible.
3514 if (Lane == -1) Lane = 0;
3516 return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
3517 DAG.getConstant(Lane, MVT::i64));
3524 AArch64TargetLowering::ConstraintType
3525 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3526 if (Constraint.size() == 1) {
3527 switch (Constraint[0]) {
3529 case 'w': // An FP/SIMD vector register
3530 return C_RegisterClass;
3531 case 'I': // Constant that can be used with an ADD instruction
3532 case 'J': // Constant that can be used with a SUB instruction
3533 case 'K': // Constant that can be used with a 32-bit logical instruction
3534 case 'L': // Constant that can be used with a 64-bit logical instruction
3535 case 'M': // Constant that can be used as a 32-bit MOV immediate
3536 case 'N': // Constant that can be used as a 64-bit MOV immediate
3537 case 'Y': // Floating point constant zero
3538 case 'Z': // Integer constant zero
3540 case 'Q': // A memory reference with base register and no offset
3542 case 'S': // A symbolic address
3547 // FIXME: Ump, Utf, Usa, Ush
3548 // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
3549 // whatever they may be
3550 // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
3551 // Usa: An absolute symbolic address
3552 // Ush: The high part (bits 32:12) of a pc-relative symbolic address
3553 assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
3554 && Constraint != "Ush" && "Unimplemented constraints");
3556 return TargetLowering::getConstraintType(Constraint);
3559 TargetLowering::ConstraintWeight
3560 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
3561 const char *Constraint) const {
3563 llvm_unreachable("Constraint weight unimplemented");
3567 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3568 std::string &Constraint,
3569 std::vector<SDValue> &Ops,
3570 SelectionDAG &DAG) const {
3571 SDValue Result(0, 0);
3573 // Only length 1 constraints are C_Other.
3574 if (Constraint.size() != 1) return;
3576 // Only C_Other constraints get lowered like this. That means constants for us
3577 // so return early if there's no hope the constraint can be lowered.
3579 switch(Constraint[0]) {
3581 case 'I': case 'J': case 'K': case 'L':
3582 case 'M': case 'N': case 'Z': {
3583 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3587 uint64_t CVal = C->getZExtValue();
3590 switch (Constraint[0]) {
3592 // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
3593 // is a peculiarly useless SUB constraint.
3594 llvm_unreachable("Unimplemented C_Other constraint");
3600 if (A64Imms::isLogicalImm(32, CVal, Bits))
3604 if (A64Imms::isLogicalImm(64, CVal, Bits))
3613 Result = DAG.getTargetConstant(CVal, Op.getValueType());
3617 // An absolute symbolic address or label reference.
3618 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
3619 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
3620 GA->getValueType(0));
3621 } else if (const BlockAddressSDNode *BA
3622 = dyn_cast<BlockAddressSDNode>(Op)) {
3623 Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
3624 BA->getValueType(0));
3625 } else if (const ExternalSymbolSDNode *ES
3626 = dyn_cast<ExternalSymbolSDNode>(Op)) {
3627 Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
3628 ES->getValueType(0));
3634 if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
3635 if (CFP->isExactlyValue(0.0)) {
3636 Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
3643 if (Result.getNode()) {
3644 Ops.push_back(Result);
3648 // It's an unknown constraint for us. Let generic code have a go.
3649 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3652 std::pair<unsigned, const TargetRegisterClass*>
3653 AArch64TargetLowering::getRegForInlineAsmConstraint(
3654 const std::string &Constraint,
3656 if (Constraint.size() == 1) {
3657 switch (Constraint[0]) {
3659 if (VT.getSizeInBits() <= 32)
3660 return std::make_pair(0U, &AArch64::GPR32RegClass);
3661 else if (VT == MVT::i64)
3662 return std::make_pair(0U, &AArch64::GPR64RegClass);
3666 return std::make_pair(0U, &AArch64::FPR16RegClass);
3667 else if (VT == MVT::f32)
3668 return std::make_pair(0U, &AArch64::FPR32RegClass);
3669 else if (VT.getSizeInBits() == 64)
3670 return std::make_pair(0U, &AArch64::FPR64RegClass);
3671 else if (VT.getSizeInBits() == 128)
3672 return std::make_pair(0U, &AArch64::FPR128RegClass);
3677 // Use the default implementation in TargetLowering to convert the register
3678 // constraint into a member of a register class.
3679 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);