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 implements the AArch64TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.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/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
38 #define DEBUG_TYPE "aarch64-lower"
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
43 // Place holder until extr generation is tested fully.
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51 cl::desc("Allow AArch64 SLI/SRI formation"),
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
97 addDRTypeForNEON(MVT::v4f16);
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
105 addQRTypeForNEON(MVT::v8f16);
108 // Compute derived properties from the register classes
109 computeRegisterProperties(Subtarget->getRegisterInfo());
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
147 // Virtually no operation on f128 is legal, but LLVM can't expand them when
148 // there's a valid register class, so we need custom operations in most cases.
149 setOperationAction(ISD::FABS, MVT::f128, Expand);
150 setOperationAction(ISD::FADD, MVT::f128, Custom);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152 setOperationAction(ISD::FCOS, MVT::f128, Expand);
153 setOperationAction(ISD::FDIV, MVT::f128, Custom);
154 setOperationAction(ISD::FMA, MVT::f128, Expand);
155 setOperationAction(ISD::FMUL, MVT::f128, Custom);
156 setOperationAction(ISD::FNEG, MVT::f128, Expand);
157 setOperationAction(ISD::FPOW, MVT::f128, Expand);
158 setOperationAction(ISD::FREM, MVT::f128, Expand);
159 setOperationAction(ISD::FRINT, MVT::f128, Expand);
160 setOperationAction(ISD::FSIN, MVT::f128, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163 setOperationAction(ISD::FSUB, MVT::f128, Custom);
164 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165 setOperationAction(ISD::SETCC, MVT::f128, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167 setOperationAction(ISD::SELECT, MVT::f128, Custom);
168 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
171 // Lowering for many of the conversions is actually specified by the non-f128
172 // type. The LowerXXX function will be trivial when f128 isn't involved.
173 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
188 // Variable arguments.
189 setOperationAction(ISD::VASTART, MVT::Other, Custom);
190 setOperationAction(ISD::VAARG, MVT::Other, Custom);
191 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
194 // Variable-sized objects.
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
199 // Exception handling.
200 // FIXME: These are guesses. Has this been defined yet?
201 setExceptionPointerRegister(AArch64::X0);
202 setExceptionSelectorRegister(AArch64::X1);
204 // Constant pool entries
205 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
208 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
210 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
211 setOperationAction(ISD::ADDC, MVT::i32, Custom);
212 setOperationAction(ISD::ADDE, MVT::i32, Custom);
213 setOperationAction(ISD::SUBC, MVT::i32, Custom);
214 setOperationAction(ISD::SUBE, MVT::i32, Custom);
215 setOperationAction(ISD::ADDC, MVT::i64, Custom);
216 setOperationAction(ISD::ADDE, MVT::i64, Custom);
217 setOperationAction(ISD::SUBC, MVT::i64, Custom);
218 setOperationAction(ISD::SUBE, MVT::i64, Custom);
220 // AArch64 lacks both left-rotate and popcount instructions.
221 setOperationAction(ISD::ROTL, MVT::i32, Expand);
222 setOperationAction(ISD::ROTL, MVT::i64, Expand);
224 // AArch64 doesn't have {U|S}MUL_LOHI.
225 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
226 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
229 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
230 // counterparts, which AArch64 supports directly.
231 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
232 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
233 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
234 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
236 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
237 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
239 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
240 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
241 setOperationAction(ISD::SREM, MVT::i32, Expand);
242 setOperationAction(ISD::SREM, MVT::i64, Expand);
243 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
244 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245 setOperationAction(ISD::UREM, MVT::i32, Expand);
246 setOperationAction(ISD::UREM, MVT::i64, Expand);
248 // Custom lower Add/Sub/Mul with overflow.
249 setOperationAction(ISD::SADDO, MVT::i32, Custom);
250 setOperationAction(ISD::SADDO, MVT::i64, Custom);
251 setOperationAction(ISD::UADDO, MVT::i32, Custom);
252 setOperationAction(ISD::UADDO, MVT::i64, Custom);
253 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
254 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
255 setOperationAction(ISD::USUBO, MVT::i32, Custom);
256 setOperationAction(ISD::USUBO, MVT::i64, Custom);
257 setOperationAction(ISD::SMULO, MVT::i32, Custom);
258 setOperationAction(ISD::SMULO, MVT::i64, Custom);
259 setOperationAction(ISD::UMULO, MVT::i32, Custom);
260 setOperationAction(ISD::UMULO, MVT::i64, Custom);
262 setOperationAction(ISD::FSIN, MVT::f32, Expand);
263 setOperationAction(ISD::FSIN, MVT::f64, Expand);
264 setOperationAction(ISD::FCOS, MVT::f32, Expand);
265 setOperationAction(ISD::FCOS, MVT::f64, Expand);
266 setOperationAction(ISD::FPOW, MVT::f32, Expand);
267 setOperationAction(ISD::FPOW, MVT::f64, Expand);
268 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
269 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
271 // f16 is a storage-only type, always promote it to f32.
272 setOperationAction(ISD::SETCC, MVT::f16, Promote);
273 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
274 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
275 setOperationAction(ISD::SELECT, MVT::f16, Promote);
276 setOperationAction(ISD::FADD, MVT::f16, Promote);
277 setOperationAction(ISD::FSUB, MVT::f16, Promote);
278 setOperationAction(ISD::FMUL, MVT::f16, Promote);
279 setOperationAction(ISD::FDIV, MVT::f16, Promote);
280 setOperationAction(ISD::FREM, MVT::f16, Promote);
281 setOperationAction(ISD::FMA, MVT::f16, Promote);
282 setOperationAction(ISD::FNEG, MVT::f16, Promote);
283 setOperationAction(ISD::FABS, MVT::f16, Promote);
284 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
286 setOperationAction(ISD::FCOS, MVT::f16, Promote);
287 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
288 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
289 setOperationAction(ISD::FPOW, MVT::f16, Promote);
290 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
291 setOperationAction(ISD::FRINT, MVT::f16, Promote);
292 setOperationAction(ISD::FSIN, MVT::f16, Promote);
293 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
294 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
295 setOperationAction(ISD::FEXP, MVT::f16, Promote);
296 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
297 setOperationAction(ISD::FLOG, MVT::f16, Promote);
298 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
299 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
300 setOperationAction(ISD::FROUND, MVT::f16, Promote);
301 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
302 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
303 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
304 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
305 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
307 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
309 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
310 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
311 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
312 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
313 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
314 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
315 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
316 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
317 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
318 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
320 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
322 // Expand all other v4f16 operations.
323 // FIXME: We could generate better code by promoting some operations to
325 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
326 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
327 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
328 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
329 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
330 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
331 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
332 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
333 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
334 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
335 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
336 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
337 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
338 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
339 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
340 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
341 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
342 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
343 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
344 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
345 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
346 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
347 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
348 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
349 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
350 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
353 // v8f16 is also a storage-only type, so expand it.
354 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
355 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
356 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
357 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
358 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
359 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
360 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
361 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
362 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
363 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
364 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
365 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
366 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
367 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
368 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
369 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
370 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
371 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
372 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
374 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
375 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
376 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
377 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
378 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
379 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
380 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
381 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
382 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
383 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
384 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
386 // AArch64 has implementations of a lot of rounding-like FP operations.
387 for (MVT Ty : {MVT::f32, MVT::f64}) {
388 setOperationAction(ISD::FFLOOR, Ty, Legal);
389 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
390 setOperationAction(ISD::FCEIL, Ty, Legal);
391 setOperationAction(ISD::FRINT, Ty, Legal);
392 setOperationAction(ISD::FTRUNC, Ty, Legal);
393 setOperationAction(ISD::FROUND, Ty, Legal);
394 setOperationAction(ISD::FMINNUM, Ty, Legal);
395 setOperationAction(ISD::FMAXNUM, Ty, Legal);
396 setOperationAction(ISD::FMINNAN, Ty, Legal);
397 setOperationAction(ISD::FMAXNAN, Ty, Legal);
400 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
402 if (Subtarget->isTargetMachO()) {
403 // For iOS, we don't want to the normal expansion of a libcall to
404 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
406 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
407 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
409 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
410 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
413 // Make floating-point constants legal for the large code model, so they don't
414 // become loads from the constant pool.
415 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
416 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
417 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
420 // AArch64 does not have floating-point extending loads, i1 sign-extending
421 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
422 for (MVT VT : MVT::fp_valuetypes()) {
423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
424 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
425 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
426 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
428 for (MVT VT : MVT::integer_valuetypes())
429 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
431 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
432 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
433 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
434 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
435 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
436 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
437 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
439 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
440 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
442 // Indexed loads and stores are supported.
443 for (unsigned im = (unsigned)ISD::PRE_INC;
444 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
445 setIndexedLoadAction(im, MVT::i8, Legal);
446 setIndexedLoadAction(im, MVT::i16, Legal);
447 setIndexedLoadAction(im, MVT::i32, Legal);
448 setIndexedLoadAction(im, MVT::i64, Legal);
449 setIndexedLoadAction(im, MVT::f64, Legal);
450 setIndexedLoadAction(im, MVT::f32, Legal);
451 setIndexedLoadAction(im, MVT::f16, Legal);
452 setIndexedStoreAction(im, MVT::i8, Legal);
453 setIndexedStoreAction(im, MVT::i16, Legal);
454 setIndexedStoreAction(im, MVT::i32, Legal);
455 setIndexedStoreAction(im, MVT::i64, Legal);
456 setIndexedStoreAction(im, MVT::f64, Legal);
457 setIndexedStoreAction(im, MVT::f32, Legal);
458 setIndexedStoreAction(im, MVT::f16, Legal);
462 setOperationAction(ISD::TRAP, MVT::Other, Legal);
464 // We combine OR nodes for bitfield operations.
465 setTargetDAGCombine(ISD::OR);
467 // Vector add and sub nodes may conceal a high-half opportunity.
468 // Also, try to fold ADD into CSINC/CSINV..
469 setTargetDAGCombine(ISD::ADD);
470 setTargetDAGCombine(ISD::SUB);
472 setTargetDAGCombine(ISD::XOR);
473 setTargetDAGCombine(ISD::SINT_TO_FP);
474 setTargetDAGCombine(ISD::UINT_TO_FP);
476 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
478 setTargetDAGCombine(ISD::ANY_EXTEND);
479 setTargetDAGCombine(ISD::ZERO_EXTEND);
480 setTargetDAGCombine(ISD::SIGN_EXTEND);
481 setTargetDAGCombine(ISD::BITCAST);
482 setTargetDAGCombine(ISD::CONCAT_VECTORS);
483 setTargetDAGCombine(ISD::STORE);
485 setTargetDAGCombine(ISD::MUL);
487 setTargetDAGCombine(ISD::SELECT);
488 setTargetDAGCombine(ISD::VSELECT);
490 setTargetDAGCombine(ISD::INTRINSIC_VOID);
491 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
492 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
494 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
495 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
496 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
498 setStackPointerRegisterToSaveRestore(AArch64::SP);
500 setSchedulingPreference(Sched::Hybrid);
503 MaskAndBranchFoldingIsLegal = true;
504 EnableExtLdPromotion = true;
506 setMinFunctionAlignment(2);
508 setHasExtractBitsInsn(true);
510 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
512 if (Subtarget->hasNEON()) {
513 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
514 // silliness like this:
515 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
516 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
517 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
518 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
519 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
520 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
521 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
522 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
523 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
524 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
525 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
526 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
527 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
528 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
529 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
530 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
531 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
532 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
533 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
534 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
535 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
536 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
537 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
538 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
539 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
541 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
542 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
543 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
544 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
545 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
547 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
549 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
550 // elements smaller than i32, so promote the input to i32 first.
551 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
552 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
553 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
554 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
555 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
556 // -> v8f16 conversions.
557 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
559 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
560 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
561 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
562 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
564 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
565 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
566 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
567 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
569 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
571 // AArch64 doesn't have MUL.2d:
572 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
573 // Custom handling for some quad-vector types to detect MULL.
574 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
575 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
576 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
578 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
579 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
580 // Likewise, narrowing and extending vector loads/stores aren't handled
582 for (MVT VT : MVT::vector_valuetypes()) {
583 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
585 setOperationAction(ISD::MULHS, VT, Expand);
586 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
587 setOperationAction(ISD::MULHU, VT, Expand);
588 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
590 setOperationAction(ISD::BSWAP, VT, Expand);
592 for (MVT InnerVT : MVT::vector_valuetypes()) {
593 setTruncStoreAction(VT, InnerVT, Expand);
594 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
595 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
596 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
600 // AArch64 has implementations of a lot of rounding-like FP operations.
601 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
602 setOperationAction(ISD::FFLOOR, Ty, Legal);
603 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
604 setOperationAction(ISD::FCEIL, Ty, Legal);
605 setOperationAction(ISD::FRINT, Ty, Legal);
606 setOperationAction(ISD::FTRUNC, Ty, Legal);
607 setOperationAction(ISD::FROUND, Ty, Legal);
611 // Prefer likely predicted branches to selects on out-of-order cores.
612 if (Subtarget->isCortexA57())
613 PredictableSelectIsExpensive = true;
616 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
617 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
618 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
619 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
621 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
622 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
623 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
624 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
625 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
627 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
628 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
631 // Mark vector float intrinsics as expand.
632 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
633 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
634 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
635 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
636 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
637 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
638 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
639 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
640 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
641 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
643 // But we do support custom-lowering for FCOPYSIGN.
644 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
648 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
649 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
651 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
652 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
653 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
654 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
655 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
656 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
657 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
658 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
660 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
661 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
662 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
663 for (MVT InnerVT : MVT::all_valuetypes())
664 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
666 // CNT supports only B element sizes.
667 if (VT != MVT::v8i8 && VT != MVT::v16i8)
668 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
670 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
671 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
672 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
673 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
674 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
677 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
679 // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
681 if (!VT.isFloatingPoint() &&
682 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
683 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
684 ISD::SABSDIFF, ISD::UABSDIFF})
685 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
687 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
688 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
689 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
690 ISD::FMINNUM, ISD::FMAXNUM})
691 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
693 if (Subtarget->isLittleEndian()) {
694 for (unsigned im = (unsigned)ISD::PRE_INC;
695 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
696 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
697 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
702 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
703 addRegisterClass(VT, &AArch64::FPR64RegClass);
704 addTypeForNEON(VT, MVT::v2i32);
707 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
708 addRegisterClass(VT, &AArch64::FPR128RegClass);
709 addTypeForNEON(VT, MVT::v4i32);
712 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
716 return VT.changeVectorElementTypeToInteger();
719 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
720 /// Mask are known to be either zero or one and return them in the
721 /// KnownZero/KnownOne bitsets.
722 void AArch64TargetLowering::computeKnownBitsForTargetNode(
723 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
724 const SelectionDAG &DAG, unsigned Depth) const {
725 switch (Op.getOpcode()) {
728 case AArch64ISD::CSEL: {
729 APInt KnownZero2, KnownOne2;
730 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
731 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
732 KnownZero &= KnownZero2;
733 KnownOne &= KnownOne2;
736 case ISD::INTRINSIC_W_CHAIN: {
737 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
738 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
741 case Intrinsic::aarch64_ldaxr:
742 case Intrinsic::aarch64_ldxr: {
743 unsigned BitWidth = KnownOne.getBitWidth();
744 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
745 unsigned MemBits = VT.getScalarType().getSizeInBits();
746 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
752 case ISD::INTRINSIC_WO_CHAIN:
753 case ISD::INTRINSIC_VOID: {
754 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
758 case Intrinsic::aarch64_neon_umaxv:
759 case Intrinsic::aarch64_neon_uminv: {
760 // Figure out the datatype of the vector operand. The UMINV instruction
761 // will zero extend the result, so we can mark as known zero all the
762 // bits larger than the element datatype. 32-bit or larget doesn't need
763 // this as those are legal types and will be handled by isel directly.
764 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
765 unsigned BitWidth = KnownZero.getBitWidth();
766 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
767 assert(BitWidth >= 8 && "Unexpected width!");
768 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
770 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
771 assert(BitWidth >= 16 && "Unexpected width!");
772 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
782 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
787 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
791 if (Subtarget->requiresStrictAlign())
793 // FIXME: True for Cyclone, but not necessary others.
800 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
801 const TargetLibraryInfo *libInfo) const {
802 return AArch64::createFastISel(funcInfo, libInfo);
805 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
806 switch ((AArch64ISD::NodeType)Opcode) {
807 case AArch64ISD::FIRST_NUMBER: break;
808 case AArch64ISD::CALL: return "AArch64ISD::CALL";
809 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
810 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
811 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
812 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
813 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
814 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
815 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
816 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
817 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
818 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
819 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
820 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
821 case AArch64ISD::ADC: return "AArch64ISD::ADC";
822 case AArch64ISD::SBC: return "AArch64ISD::SBC";
823 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
824 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
825 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
826 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
827 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
828 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
829 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
830 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
831 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
832 case AArch64ISD::DUP: return "AArch64ISD::DUP";
833 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
834 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
835 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
836 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
837 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
838 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
839 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
840 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
841 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
842 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
843 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
844 case AArch64ISD::BICi: return "AArch64ISD::BICi";
845 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
846 case AArch64ISD::BSL: return "AArch64ISD::BSL";
847 case AArch64ISD::NEG: return "AArch64ISD::NEG";
848 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
849 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
850 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
851 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
852 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
853 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
854 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
855 case AArch64ISD::REV16: return "AArch64ISD::REV16";
856 case AArch64ISD::REV32: return "AArch64ISD::REV32";
857 case AArch64ISD::REV64: return "AArch64ISD::REV64";
858 case AArch64ISD::EXT: return "AArch64ISD::EXT";
859 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
860 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
861 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
862 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
863 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
864 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
865 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
866 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
867 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
868 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
869 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
870 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
871 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
872 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
873 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
874 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
875 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
876 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
877 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
878 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
879 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
880 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
881 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
882 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
883 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
884 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
885 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
886 case AArch64ISD::NOT: return "AArch64ISD::NOT";
887 case AArch64ISD::BIT: return "AArch64ISD::BIT";
888 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
889 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
890 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
891 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
892 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
893 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
894 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
895 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
896 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
897 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
898 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
899 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
900 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
901 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
902 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
903 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
904 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
905 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
906 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
907 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
908 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
909 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
910 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
911 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
912 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
913 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
914 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
915 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
916 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
917 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
918 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
919 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
920 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
921 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
922 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
923 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
924 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
925 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
926 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
927 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
933 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
934 MachineBasicBlock *MBB) const {
935 // We materialise the F128CSEL pseudo-instruction as some control flow and a
939 // [... previous instrs leading to comparison ...]
945 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
947 MachineFunction *MF = MBB->getParent();
948 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
949 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
950 DebugLoc DL = MI->getDebugLoc();
951 MachineFunction::iterator It = MBB;
954 unsigned DestReg = MI->getOperand(0).getReg();
955 unsigned IfTrueReg = MI->getOperand(1).getReg();
956 unsigned IfFalseReg = MI->getOperand(2).getReg();
957 unsigned CondCode = MI->getOperand(3).getImm();
958 bool NZCVKilled = MI->getOperand(4).isKill();
960 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
961 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
962 MF->insert(It, TrueBB);
963 MF->insert(It, EndBB);
965 // Transfer rest of current basic-block to EndBB
966 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
968 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
970 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
971 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
972 MBB->addSuccessor(TrueBB);
973 MBB->addSuccessor(EndBB);
975 // TrueBB falls through to the end.
976 TrueBB->addSuccessor(EndBB);
979 TrueBB->addLiveIn(AArch64::NZCV);
980 EndBB->addLiveIn(AArch64::NZCV);
983 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
989 MI->eraseFromParent();
994 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
995 MachineBasicBlock *BB) const {
996 switch (MI->getOpcode()) {
1001 llvm_unreachable("Unexpected instruction for custom inserter!");
1003 case AArch64::F128CSEL:
1004 return EmitF128CSEL(MI, BB);
1006 case TargetOpcode::STACKMAP:
1007 case TargetOpcode::PATCHPOINT:
1008 return emitPatchPoint(MI, BB);
1012 //===----------------------------------------------------------------------===//
1013 // AArch64 Lowering private implementation.
1014 //===----------------------------------------------------------------------===//
1016 //===----------------------------------------------------------------------===//
1018 //===----------------------------------------------------------------------===//
1020 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1022 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1025 llvm_unreachable("Unknown condition code!");
1027 return AArch64CC::NE;
1029 return AArch64CC::EQ;
1031 return AArch64CC::GT;
1033 return AArch64CC::GE;
1035 return AArch64CC::LT;
1037 return AArch64CC::LE;
1039 return AArch64CC::HI;
1041 return AArch64CC::HS;
1043 return AArch64CC::LO;
1045 return AArch64CC::LS;
1049 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1050 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1051 AArch64CC::CondCode &CondCode,
1052 AArch64CC::CondCode &CondCode2) {
1053 CondCode2 = AArch64CC::AL;
1056 llvm_unreachable("Unknown FP condition!");
1059 CondCode = AArch64CC::EQ;
1063 CondCode = AArch64CC::GT;
1067 CondCode = AArch64CC::GE;
1070 CondCode = AArch64CC::MI;
1073 CondCode = AArch64CC::LS;
1076 CondCode = AArch64CC::MI;
1077 CondCode2 = AArch64CC::GT;
1080 CondCode = AArch64CC::VC;
1083 CondCode = AArch64CC::VS;
1086 CondCode = AArch64CC::EQ;
1087 CondCode2 = AArch64CC::VS;
1090 CondCode = AArch64CC::HI;
1093 CondCode = AArch64CC::PL;
1097 CondCode = AArch64CC::LT;
1101 CondCode = AArch64CC::LE;
1105 CondCode = AArch64CC::NE;
1110 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1111 /// CC usable with the vector instructions. Fewer operations are available
1112 /// without a real NZCV register, so we have to use less efficient combinations
1113 /// to get the same effect.
1114 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1115 AArch64CC::CondCode &CondCode,
1116 AArch64CC::CondCode &CondCode2,
1121 // Mostly the scalar mappings work fine.
1122 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1125 Invert = true; // Fallthrough
1127 CondCode = AArch64CC::MI;
1128 CondCode2 = AArch64CC::GE;
1135 // All of the compare-mask comparisons are ordered, but we can switch
1136 // between the two by a double inversion. E.g. ULE == !OGT.
1138 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1143 static bool isLegalArithImmed(uint64_t C) {
1144 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1145 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1148 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1149 SDLoc dl, SelectionDAG &DAG) {
1150 EVT VT = LHS.getValueType();
1152 if (VT.isFloatingPoint())
1153 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1155 // The CMP instruction is just an alias for SUBS, and representing it as
1156 // SUBS means that it's possible to get CSE with subtract operations.
1157 // A later phase can perform the optimization of setting the destination
1158 // register to WZR/XZR if it ends up being unused.
1159 unsigned Opcode = AArch64ISD::SUBS;
1161 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1162 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1163 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1164 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1165 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1166 // can be set differently by this operation. It comes down to whether
1167 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1168 // everything is fine. If not then the optimization is wrong. Thus general
1169 // comparisons are only valid if op2 != 0.
1171 // So, finally, the only LLVM-native comparisons that don't mention C and V
1172 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1173 // the absence of information about op2.
1174 Opcode = AArch64ISD::ADDS;
1175 RHS = RHS.getOperand(1);
1176 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1177 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1178 !isUnsignedIntSetCC(CC)) {
1179 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1180 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1181 // of the signed comparisons.
1182 Opcode = AArch64ISD::ANDS;
1183 RHS = LHS.getOperand(1);
1184 LHS = LHS.getOperand(0);
1187 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1191 /// \defgroup AArch64CCMP CMP;CCMP matching
1193 /// These functions deal with the formation of CMP;CCMP;... sequences.
1194 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1195 /// a comparison. They set the NZCV flags to a predefined value if their
1196 /// predicate is false. This allows to express arbitrary conjunctions, for
1197 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1200 /// ccmp B, inv(CB), CA
1201 /// check for CB flags
1203 /// In general we can create code for arbitrary "... (and (and A B) C)"
1204 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1205 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1206 /// negation operations:
1207 /// We can negate the results of a single comparison by inverting the flags
1208 /// used when the predicate fails and inverting the flags tested in the next
1209 /// instruction; We can also negate the results of the whole previous
1210 /// conditional compare sequence by inverting the flags tested in the next
1211 /// instruction. However there is no way to negate the result of a partial
1214 /// Therefore on encountering an "or" expression we can negate the subtree on
1215 /// one side and have to be able to push the negate to the leafs of the subtree
1216 /// on the other side (see also the comments in code). As complete example:
1217 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1218 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1219 /// is transformed to
1220 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1221 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1222 /// and implemented as:
1224 /// ccmp D, inv(CD), CC
1225 /// ccmp A, CA, inv(CD)
1226 /// ccmp B, CB, inv(CA)
1227 /// check for CB flags
1228 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1229 /// by conditional compare sequences.
1232 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1233 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1234 ISD::CondCode CC, SDValue CCOp,
1235 SDValue Condition, unsigned NZCV,
1236 SDLoc DL, SelectionDAG &DAG) {
1237 unsigned Opcode = 0;
1238 if (LHS.getValueType().isFloatingPoint())
1239 Opcode = AArch64ISD::FCCMP;
1240 else if (RHS.getOpcode() == ISD::SUB) {
1241 SDValue SubOp0 = RHS.getOperand(0);
1242 if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1243 if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1244 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1245 Opcode = AArch64ISD::CCMN;
1246 RHS = RHS.getOperand(1);
1250 Opcode = AArch64ISD::CCMP;
1252 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1253 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1256 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1257 /// CanPushNegate is set to true if we can push a negate operation through
1258 /// the tree in a was that we are left with AND operations and negate operations
1259 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1260 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1261 /// brought into such a form.
1262 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1263 unsigned Depth = 0) {
1264 if (!Val.hasOneUse())
1266 unsigned Opcode = Val->getOpcode();
1267 if (Opcode == ISD::SETCC) {
1268 CanPushNegate = true;
1271 // Protect against stack overflow.
1274 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1275 SDValue O0 = Val->getOperand(0);
1276 SDValue O1 = Val->getOperand(1);
1277 bool CanPushNegateL;
1278 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1280 bool CanPushNegateR;
1281 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1283 // We cannot push a negate through an AND operation (it would become an OR),
1284 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1285 // push the negate through the x/y subtrees.
1286 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1292 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1293 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1294 /// Tries to transform the given i1 producing node @p Val to a series compare
1295 /// and conditional compare operations. @returns an NZCV flags producing node
1296 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1297 /// transformation was not possible.
1298 /// On recursive invocations @p PushNegate may be set to true to have negation
1299 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1300 /// for the comparisons in the current subtree; @p Depth limits the search
1301 /// depth to avoid stack overflow.
1302 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1303 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1304 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1305 unsigned Depth = 0) {
1306 // We're at a tree leaf, produce a conditional comparison operation.
1307 unsigned Opcode = Val->getOpcode();
1308 if (Opcode == ISD::SETCC) {
1309 SDValue LHS = Val->getOperand(0);
1310 SDValue RHS = Val->getOperand(1);
1311 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1312 bool isInteger = LHS.getValueType().isInteger();
1314 CC = getSetCCInverse(CC, isInteger);
1316 // Determine OutCC and handle FP special case.
1318 OutCC = changeIntCCToAArch64CC(CC);
1320 assert(LHS.getValueType().isFloatingPoint());
1321 AArch64CC::CondCode ExtraCC;
1322 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1323 // Surpisingly some floating point conditions can't be tested with a
1324 // single condition code. Construct an additional comparison in this case.
1325 // See comment below on how we deal with OR conditions.
1326 if (ExtraCC != AArch64CC::AL) {
1328 if (!CCOp.getNode())
1329 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1331 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1332 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1333 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1334 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1338 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1339 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1343 // Produce a normal comparison if we are first in the chain
1344 if (!CCOp.getNode())
1345 return emitComparison(LHS, RHS, CC, DL, DAG);
1346 // Otherwise produce a ccmp.
1347 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1348 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1349 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1350 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1352 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1355 assert((Opcode == ISD::OR || !PushNegate)
1356 && "Can only push negate through OR operation");
1358 // Check if both sides can be transformed.
1359 SDValue LHS = Val->getOperand(0);
1360 SDValue RHS = Val->getOperand(1);
1361 bool CanPushNegateL;
1362 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1364 bool CanPushNegateR;
1365 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1368 // Do we need to negate our operands?
1369 bool NegateOperands = Opcode == ISD::OR;
1370 // We can negate the results of all previous operations by inverting the
1371 // predicate flags giving us a free negation for one side. For the other side
1372 // we need to be able to push the negation to the leafs of the tree.
1373 if (NegateOperands) {
1374 if (!CanPushNegateL && !CanPushNegateR)
1376 // Order the side where we can push the negate through to LHS.
1377 if (!CanPushNegateL && CanPushNegateR)
1378 std::swap(LHS, RHS);
1380 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1381 bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1382 if (NeedsNegOutL && NeedsNegOutR)
1384 // Order the side where we need to negate the output flags to RHS so it
1385 // gets emitted first.
1387 std::swap(LHS, RHS);
1390 // Emit RHS. If we want to negate the tree we only need to push a negate
1391 // through if we are already in a PushNegate case, otherwise we can negate
1392 // the "flags to test" afterwards.
1393 AArch64CC::CondCode RHSCC;
1394 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1395 CCOp, Predicate, Depth+1);
1396 if (NegateOperands && !PushNegate)
1397 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1398 // Emit LHS. We must push the negate through if we need to negate it.
1399 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1400 CmpR, RHSCC, Depth+1);
1401 // If we transformed an OR to and AND then we have to negate the result
1402 // (or absorb a PushNegate resulting in a double negation).
1403 if (Opcode == ISD::OR && !PushNegate)
1404 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1410 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1411 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1412 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1413 EVT VT = RHS.getValueType();
1414 uint64_t C = RHSC->getZExtValue();
1415 if (!isLegalArithImmed(C)) {
1416 // Constant does not fit, try adjusting it by one?
1422 if ((VT == MVT::i32 && C != 0x80000000 &&
1423 isLegalArithImmed((uint32_t)(C - 1))) ||
1424 (VT == MVT::i64 && C != 0x80000000ULL &&
1425 isLegalArithImmed(C - 1ULL))) {
1426 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1427 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1428 RHS = DAG.getConstant(C, dl, VT);
1433 if ((VT == MVT::i32 && C != 0 &&
1434 isLegalArithImmed((uint32_t)(C - 1))) ||
1435 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1436 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1437 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1438 RHS = DAG.getConstant(C, dl, VT);
1443 if ((VT == MVT::i32 && C != INT32_MAX &&
1444 isLegalArithImmed((uint32_t)(C + 1))) ||
1445 (VT == MVT::i64 && C != INT64_MAX &&
1446 isLegalArithImmed(C + 1ULL))) {
1447 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1448 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1449 RHS = DAG.getConstant(C, dl, VT);
1454 if ((VT == MVT::i32 && C != UINT32_MAX &&
1455 isLegalArithImmed((uint32_t)(C + 1))) ||
1456 (VT == MVT::i64 && C != UINT64_MAX &&
1457 isLegalArithImmed(C + 1ULL))) {
1458 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1459 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1460 RHS = DAG.getConstant(C, dl, VT);
1467 AArch64CC::CondCode AArch64CC;
1468 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1469 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1471 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1472 // For the i8 operand, the largest immediate is 255, so this can be easily
1473 // encoded in the compare instruction. For the i16 operand, however, the
1474 // largest immediate cannot be encoded in the compare.
1475 // Therefore, use a sign extending load and cmn to avoid materializing the
1476 // -1 constant. For example,
1478 // ldrh w0, [x0, #0]
1481 // ldrsh w0, [x0, #0]
1483 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1484 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1485 // ensure both the LHS and RHS are truly zero extended and to make sure the
1486 // transformation is profitable.
1487 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1488 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1489 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1490 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1491 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1492 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1494 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1495 DAG.getValueType(MVT::i16));
1496 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1497 RHS.getValueType()),
1499 AArch64CC = changeIntCCToAArch64CC(CC);
1503 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1504 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1505 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1506 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1512 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1513 AArch64CC = changeIntCCToAArch64CC(CC);
1515 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1519 static std::pair<SDValue, SDValue>
1520 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1521 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1522 "Unsupported value type");
1523 SDValue Value, Overflow;
1525 SDValue LHS = Op.getOperand(0);
1526 SDValue RHS = Op.getOperand(1);
1528 switch (Op.getOpcode()) {
1530 llvm_unreachable("Unknown overflow instruction!");
1532 Opc = AArch64ISD::ADDS;
1536 Opc = AArch64ISD::ADDS;
1540 Opc = AArch64ISD::SUBS;
1544 Opc = AArch64ISD::SUBS;
1547 // Multiply needs a little bit extra work.
1551 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1552 if (Op.getValueType() == MVT::i32) {
1553 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1554 // For a 32 bit multiply with overflow check we want the instruction
1555 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1556 // need to generate the following pattern:
1557 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1558 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1559 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1560 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1561 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1562 DAG.getConstant(0, DL, MVT::i64));
1563 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1564 // operation. We need to clear out the upper 32 bits, because we used a
1565 // widening multiply that wrote all 64 bits. In the end this should be a
1567 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1569 // The signed overflow check requires more than just a simple check for
1570 // any bit set in the upper 32 bits of the result. These bits could be
1571 // just the sign bits of a negative number. To perform the overflow
1572 // check we have to arithmetic shift right the 32nd bit of the result by
1573 // 31 bits. Then we compare the result to the upper 32 bits.
1574 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1575 DAG.getConstant(32, DL, MVT::i64));
1576 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1577 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1578 DAG.getConstant(31, DL, MVT::i64));
1579 // It is important that LowerBits is last, otherwise the arithmetic
1580 // shift will not be folded into the compare (SUBS).
1581 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1582 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1585 // The overflow check for unsigned multiply is easy. We only need to
1586 // check if any of the upper 32 bits are set. This can be done with a
1587 // CMP (shifted register). For that we need to generate the following
1589 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1590 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1591 DAG.getConstant(32, DL, MVT::i64));
1592 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1594 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1595 DAG.getConstant(0, DL, MVT::i64),
1596 UpperBits).getValue(1);
1600 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1601 // For the 64 bit multiply
1602 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1604 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1605 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1606 DAG.getConstant(63, DL, MVT::i64));
1607 // It is important that LowerBits is last, otherwise the arithmetic
1608 // shift will not be folded into the compare (SUBS).
1609 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1610 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1613 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1614 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1616 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1617 DAG.getConstant(0, DL, MVT::i64),
1618 UpperBits).getValue(1);
1625 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1627 // Emit the AArch64 operation with overflow check.
1628 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1629 Overflow = Value.getValue(1);
1631 return std::make_pair(Value, Overflow);
1634 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1635 RTLIB::Libcall Call) const {
1636 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1637 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1641 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1642 SDValue Sel = Op.getOperand(0);
1643 SDValue Other = Op.getOperand(1);
1645 // If neither operand is a SELECT_CC, give up.
1646 if (Sel.getOpcode() != ISD::SELECT_CC)
1647 std::swap(Sel, Other);
1648 if (Sel.getOpcode() != ISD::SELECT_CC)
1651 // The folding we want to perform is:
1652 // (xor x, (select_cc a, b, cc, 0, -1) )
1654 // (csel x, (xor x, -1), cc ...)
1656 // The latter will get matched to a CSINV instruction.
1658 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1659 SDValue LHS = Sel.getOperand(0);
1660 SDValue RHS = Sel.getOperand(1);
1661 SDValue TVal = Sel.getOperand(2);
1662 SDValue FVal = Sel.getOperand(3);
1665 // FIXME: This could be generalized to non-integer comparisons.
1666 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1669 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1670 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1672 // The values aren't constants, this isn't the pattern we're looking for.
1673 if (!CFVal || !CTVal)
1676 // We can commute the SELECT_CC by inverting the condition. This
1677 // might be needed to make this fit into a CSINV pattern.
1678 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1679 std::swap(TVal, FVal);
1680 std::swap(CTVal, CFVal);
1681 CC = ISD::getSetCCInverse(CC, true);
1684 // If the constants line up, perform the transform!
1685 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1687 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1690 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1691 DAG.getConstant(-1ULL, dl, Other.getValueType()));
1693 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1700 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1701 EVT VT = Op.getValueType();
1703 // Let legalize expand this if it isn't a legal type yet.
1704 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1707 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1710 bool ExtraOp = false;
1711 switch (Op.getOpcode()) {
1713 llvm_unreachable("Invalid code");
1715 Opc = AArch64ISD::ADDS;
1718 Opc = AArch64ISD::SUBS;
1721 Opc = AArch64ISD::ADCS;
1725 Opc = AArch64ISD::SBCS;
1731 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1732 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1736 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1737 // Let legalize expand this if it isn't a legal type yet.
1738 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1742 AArch64CC::CondCode CC;
1743 // The actual operation that sets the overflow or carry flag.
1744 SDValue Value, Overflow;
1745 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1747 // We use 0 and 1 as false and true values.
1748 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1749 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1751 // We use an inverted condition, because the conditional select is inverted
1752 // too. This will allow it to be selected to a single instruction:
1753 // CSINC Wd, WZR, WZR, invert(cond).
1754 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1755 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1758 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1759 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1762 // Prefetch operands are:
1763 // 1: Address to prefetch
1765 // 3: int locality (0 = no locality ... 3 = extreme locality)
1766 // 4: bool isDataCache
1767 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1769 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1770 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1771 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1773 bool IsStream = !Locality;
1774 // When the locality number is set
1776 // The front-end should have filtered out the out-of-range values
1777 assert(Locality <= 3 && "Prefetch locality out-of-range");
1778 // The locality degree is the opposite of the cache speed.
1779 // Put the number the other way around.
1780 // The encoding starts at 0 for level 1
1781 Locality = 3 - Locality;
1784 // built the mask value encoding the expected behavior.
1785 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1786 (!IsData << 3) | // IsDataCache bit
1787 (Locality << 1) | // Cache level bits
1788 (unsigned)IsStream; // Stream bit
1789 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1790 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1793 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1794 SelectionDAG &DAG) const {
1795 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1798 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1800 return LowerF128Call(Op, DAG, LC);
1803 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1804 SelectionDAG &DAG) const {
1805 if (Op.getOperand(0).getValueType() != MVT::f128) {
1806 // It's legal except when f128 is involved
1811 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1813 // FP_ROUND node has a second operand indicating whether it is known to be
1814 // precise. That doesn't take part in the LibCall so we can't directly use
1816 SDValue SrcVal = Op.getOperand(0);
1817 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1818 /*isSigned*/ false, SDLoc(Op)).first;
1821 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1822 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1823 // Any additional optimization in this function should be recorded
1824 // in the cost tables.
1825 EVT InVT = Op.getOperand(0).getValueType();
1826 EVT VT = Op.getValueType();
1828 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1831 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1833 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1836 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1839 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1840 VT.getVectorNumElements());
1841 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1842 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1845 // Type changing conversions are illegal.
1849 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1850 SelectionDAG &DAG) const {
1851 if (Op.getOperand(0).getValueType().isVector())
1852 return LowerVectorFP_TO_INT(Op, DAG);
1854 // f16 conversions are promoted to f32.
1855 if (Op.getOperand(0).getValueType() == MVT::f16) {
1858 Op.getOpcode(), dl, Op.getValueType(),
1859 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1862 if (Op.getOperand(0).getValueType() != MVT::f128) {
1863 // It's legal except when f128 is involved
1868 if (Op.getOpcode() == ISD::FP_TO_SINT)
1869 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1871 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1873 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1874 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1878 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1879 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1880 // Any additional optimization in this function should be recorded
1881 // in the cost tables.
1882 EVT VT = Op.getValueType();
1884 SDValue In = Op.getOperand(0);
1885 EVT InVT = In.getValueType();
1887 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1889 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1890 InVT.getVectorNumElements());
1891 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1892 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1895 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1897 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1898 EVT CastVT = VT.changeVectorElementTypeToInteger();
1899 In = DAG.getNode(CastOpc, dl, CastVT, In);
1900 return DAG.getNode(Op.getOpcode(), dl, VT, In);
1906 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1907 SelectionDAG &DAG) const {
1908 if (Op.getValueType().isVector())
1909 return LowerVectorINT_TO_FP(Op, DAG);
1911 // f16 conversions are promoted to f32.
1912 if (Op.getValueType() == MVT::f16) {
1915 ISD::FP_ROUND, dl, MVT::f16,
1916 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1917 DAG.getIntPtrConstant(0, dl));
1920 // i128 conversions are libcalls.
1921 if (Op.getOperand(0).getValueType() == MVT::i128)
1924 // Other conversions are legal, unless it's to the completely software-based
1926 if (Op.getValueType() != MVT::f128)
1930 if (Op.getOpcode() == ISD::SINT_TO_FP)
1931 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1933 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1935 return LowerF128Call(Op, DAG, LC);
1938 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1939 SelectionDAG &DAG) const {
1940 // For iOS, we want to call an alternative entry point: __sincos_stret,
1941 // which returns the values in two S / D registers.
1943 SDValue Arg = Op.getOperand(0);
1944 EVT ArgVT = Arg.getValueType();
1945 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1952 Entry.isSExt = false;
1953 Entry.isZExt = false;
1954 Args.push_back(Entry);
1956 const char *LibcallName =
1957 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1959 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1961 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1962 TargetLowering::CallLoweringInfo CLI(DAG);
1963 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1964 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1966 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1967 return CallResult.first;
1970 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1971 if (Op.getValueType() != MVT::f16)
1974 assert(Op.getOperand(0).getValueType() == MVT::i16);
1977 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1978 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1980 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1981 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
1985 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1986 if (OrigVT.getSizeInBits() >= 64)
1989 assert(OrigVT.isSimple() && "Expecting a simple value type");
1991 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1992 switch (OrigSimpleTy) {
1993 default: llvm_unreachable("Unexpected Vector Type");
2002 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2005 unsigned ExtOpcode) {
2006 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2007 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2008 // 64-bits we need to insert a new extension so that it will be 64-bits.
2009 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2010 if (OrigTy.getSizeInBits() >= 64)
2013 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2014 EVT NewVT = getExtensionTo64Bits(OrigTy);
2016 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2019 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2021 EVT VT = N->getValueType(0);
2023 if (N->getOpcode() != ISD::BUILD_VECTOR)
2026 for (const SDValue &Elt : N->op_values()) {
2027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2028 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2029 unsigned HalfSize = EltSize / 2;
2031 if (!isIntN(HalfSize, C->getSExtValue()))
2034 if (!isUIntN(HalfSize, C->getZExtValue()))
2045 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2046 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2047 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2048 N->getOperand(0)->getValueType(0),
2052 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2053 EVT VT = N->getValueType(0);
2055 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2056 unsigned NumElts = VT.getVectorNumElements();
2057 MVT TruncVT = MVT::getIntegerVT(EltSize);
2058 SmallVector<SDValue, 8> Ops;
2059 for (unsigned i = 0; i != NumElts; ++i) {
2060 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2061 const APInt &CInt = C->getAPIntValue();
2062 // Element types smaller than 32 bits are not legal, so use i32 elements.
2063 // The values are implicitly truncated so sext vs. zext doesn't matter.
2064 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2066 return DAG.getNode(ISD::BUILD_VECTOR, dl,
2067 MVT::getVectorVT(TruncVT, NumElts), Ops);
2070 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2071 if (N->getOpcode() == ISD::SIGN_EXTEND)
2073 if (isExtendedBUILD_VECTOR(N, DAG, true))
2078 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2079 if (N->getOpcode() == ISD::ZERO_EXTEND)
2081 if (isExtendedBUILD_VECTOR(N, DAG, false))
2086 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2087 unsigned Opcode = N->getOpcode();
2088 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2089 SDNode *N0 = N->getOperand(0).getNode();
2090 SDNode *N1 = N->getOperand(1).getNode();
2091 return N0->hasOneUse() && N1->hasOneUse() &&
2092 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2097 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2098 unsigned Opcode = N->getOpcode();
2099 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2100 SDNode *N0 = N->getOperand(0).getNode();
2101 SDNode *N1 = N->getOperand(1).getNode();
2102 return N0->hasOneUse() && N1->hasOneUse() &&
2103 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2108 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2109 // Multiplications are only custom-lowered for 128-bit vectors so that
2110 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2111 EVT VT = Op.getValueType();
2112 assert(VT.is128BitVector() && VT.isInteger() &&
2113 "unexpected type for custom-lowering ISD::MUL");
2114 SDNode *N0 = Op.getOperand(0).getNode();
2115 SDNode *N1 = Op.getOperand(1).getNode();
2116 unsigned NewOpc = 0;
2118 bool isN0SExt = isSignExtended(N0, DAG);
2119 bool isN1SExt = isSignExtended(N1, DAG);
2120 if (isN0SExt && isN1SExt)
2121 NewOpc = AArch64ISD::SMULL;
2123 bool isN0ZExt = isZeroExtended(N0, DAG);
2124 bool isN1ZExt = isZeroExtended(N1, DAG);
2125 if (isN0ZExt && isN1ZExt)
2126 NewOpc = AArch64ISD::UMULL;
2127 else if (isN1SExt || isN1ZExt) {
2128 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2129 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2130 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2131 NewOpc = AArch64ISD::SMULL;
2133 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2134 NewOpc = AArch64ISD::UMULL;
2136 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2138 NewOpc = AArch64ISD::UMULL;
2144 if (VT == MVT::v2i64)
2145 // Fall through to expand this. It is not legal.
2148 // Other vector multiplications are legal.
2153 // Legalize to a S/UMULL instruction
2156 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2158 Op0 = skipExtensionForVectorMULL(N0, DAG);
2159 assert(Op0.getValueType().is64BitVector() &&
2160 Op1.getValueType().is64BitVector() &&
2161 "unexpected types for extended operands to VMULL");
2162 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2164 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2165 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2166 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2167 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2168 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2169 EVT Op1VT = Op1.getValueType();
2170 return DAG.getNode(N0->getOpcode(), DL, VT,
2171 DAG.getNode(NewOpc, DL, VT,
2172 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2173 DAG.getNode(NewOpc, DL, VT,
2174 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2177 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2178 SelectionDAG &DAG) const {
2179 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2182 default: return SDValue(); // Don't custom lower most intrinsics.
2183 case Intrinsic::aarch64_thread_pointer: {
2184 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2185 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2190 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2191 SelectionDAG &DAG) const {
2192 switch (Op.getOpcode()) {
2194 llvm_unreachable("unimplemented operand");
2197 return LowerBITCAST(Op, DAG);
2198 case ISD::GlobalAddress:
2199 return LowerGlobalAddress(Op, DAG);
2200 case ISD::GlobalTLSAddress:
2201 return LowerGlobalTLSAddress(Op, DAG);
2203 return LowerSETCC(Op, DAG);
2205 return LowerBR_CC(Op, DAG);
2207 return LowerSELECT(Op, DAG);
2208 case ISD::SELECT_CC:
2209 return LowerSELECT_CC(Op, DAG);
2210 case ISD::JumpTable:
2211 return LowerJumpTable(Op, DAG);
2212 case ISD::ConstantPool:
2213 return LowerConstantPool(Op, DAG);
2214 case ISD::BlockAddress:
2215 return LowerBlockAddress(Op, DAG);
2217 return LowerVASTART(Op, DAG);
2219 return LowerVACOPY(Op, DAG);
2221 return LowerVAARG(Op, DAG);
2226 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2233 return LowerXALUO(Op, DAG);
2235 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2237 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2239 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2241 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2243 return LowerFP_ROUND(Op, DAG);
2244 case ISD::FP_EXTEND:
2245 return LowerFP_EXTEND(Op, DAG);
2246 case ISD::FRAMEADDR:
2247 return LowerFRAMEADDR(Op, DAG);
2248 case ISD::RETURNADDR:
2249 return LowerRETURNADDR(Op, DAG);
2250 case ISD::INSERT_VECTOR_ELT:
2251 return LowerINSERT_VECTOR_ELT(Op, DAG);
2252 case ISD::EXTRACT_VECTOR_ELT:
2253 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2254 case ISD::BUILD_VECTOR:
2255 return LowerBUILD_VECTOR(Op, DAG);
2256 case ISD::VECTOR_SHUFFLE:
2257 return LowerVECTOR_SHUFFLE(Op, DAG);
2258 case ISD::EXTRACT_SUBVECTOR:
2259 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2263 return LowerVectorSRA_SRL_SHL(Op, DAG);
2264 case ISD::SHL_PARTS:
2265 return LowerShiftLeftParts(Op, DAG);
2266 case ISD::SRL_PARTS:
2267 case ISD::SRA_PARTS:
2268 return LowerShiftRightParts(Op, DAG);
2270 return LowerCTPOP(Op, DAG);
2271 case ISD::FCOPYSIGN:
2272 return LowerFCOPYSIGN(Op, DAG);
2274 return LowerVectorAND(Op, DAG);
2276 return LowerVectorOR(Op, DAG);
2278 return LowerXOR(Op, DAG);
2280 return LowerPREFETCH(Op, DAG);
2281 case ISD::SINT_TO_FP:
2282 case ISD::UINT_TO_FP:
2283 return LowerINT_TO_FP(Op, DAG);
2284 case ISD::FP_TO_SINT:
2285 case ISD::FP_TO_UINT:
2286 return LowerFP_TO_INT(Op, DAG);
2288 return LowerFSINCOS(Op, DAG);
2290 return LowerMUL(Op, DAG);
2291 case ISD::INTRINSIC_WO_CHAIN:
2292 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2296 /// getFunctionAlignment - Return the Log2 alignment of this function.
2297 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2301 //===----------------------------------------------------------------------===//
2302 // Calling Convention Implementation
2303 //===----------------------------------------------------------------------===//
2305 #include "AArch64GenCallingConv.inc"
2307 /// Selects the correct CCAssignFn for a given CallingConvention value.
2308 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2309 bool IsVarArg) const {
2312 llvm_unreachable("Unsupported calling convention.");
2313 case CallingConv::WebKit_JS:
2314 return CC_AArch64_WebKit_JS;
2315 case CallingConv::GHC:
2316 return CC_AArch64_GHC;
2317 case CallingConv::C:
2318 case CallingConv::Fast:
2319 if (!Subtarget->isTargetDarwin())
2320 return CC_AArch64_AAPCS;
2321 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2325 SDValue AArch64TargetLowering::LowerFormalArguments(
2326 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2327 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2328 SmallVectorImpl<SDValue> &InVals) const {
2329 MachineFunction &MF = DAG.getMachineFunction();
2330 MachineFrameInfo *MFI = MF.getFrameInfo();
2332 // Assign locations to all of the incoming arguments.
2333 SmallVector<CCValAssign, 16> ArgLocs;
2334 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2337 // At this point, Ins[].VT may already be promoted to i32. To correctly
2338 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2339 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2340 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2341 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2343 unsigned NumArgs = Ins.size();
2344 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2345 unsigned CurArgIdx = 0;
2346 for (unsigned i = 0; i != NumArgs; ++i) {
2347 MVT ValVT = Ins[i].VT;
2348 if (Ins[i].isOrigArg()) {
2349 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2350 CurArgIdx = Ins[i].getOrigArgIndex();
2352 // Get type of the original argument.
2353 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2354 /*AllowUnknown*/ true);
2355 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2356 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2357 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2359 else if (ActualMVT == MVT::i16)
2362 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2364 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2365 assert(!Res && "Call operand has unhandled type");
2368 assert(ArgLocs.size() == Ins.size());
2369 SmallVector<SDValue, 16> ArgValues;
2370 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2371 CCValAssign &VA = ArgLocs[i];
2373 if (Ins[i].Flags.isByVal()) {
2374 // Byval is used for HFAs in the PCS, but the system should work in a
2375 // non-compliant manner for larger structs.
2376 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2377 int Size = Ins[i].Flags.getByValSize();
2378 unsigned NumRegs = (Size + 7) / 8;
2380 // FIXME: This works on big-endian for composite byvals, which are the common
2381 // case. It should also work for fundamental types too.
2383 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2384 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2385 InVals.push_back(FrameIdxN);
2390 if (VA.isRegLoc()) {
2391 // Arguments stored in registers.
2392 EVT RegVT = VA.getLocVT();
2395 const TargetRegisterClass *RC;
2397 if (RegVT == MVT::i32)
2398 RC = &AArch64::GPR32RegClass;
2399 else if (RegVT == MVT::i64)
2400 RC = &AArch64::GPR64RegClass;
2401 else if (RegVT == MVT::f16)
2402 RC = &AArch64::FPR16RegClass;
2403 else if (RegVT == MVT::f32)
2404 RC = &AArch64::FPR32RegClass;
2405 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2406 RC = &AArch64::FPR64RegClass;
2407 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2408 RC = &AArch64::FPR128RegClass;
2410 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2412 // Transform the arguments in physical registers into virtual ones.
2413 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2414 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2416 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2417 // to 64 bits. Insert an assert[sz]ext to capture this, then
2418 // truncate to the right size.
2419 switch (VA.getLocInfo()) {
2421 llvm_unreachable("Unknown loc info!");
2422 case CCValAssign::Full:
2424 case CCValAssign::BCvt:
2425 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2427 case CCValAssign::AExt:
2428 case CCValAssign::SExt:
2429 case CCValAssign::ZExt:
2430 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2431 // nodes after our lowering.
2432 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2436 InVals.push_back(ArgValue);
2438 } else { // VA.isRegLoc()
2439 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2440 unsigned ArgOffset = VA.getLocMemOffset();
2441 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2443 uint32_t BEAlign = 0;
2444 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2445 !Ins[i].Flags.isInConsecutiveRegs())
2446 BEAlign = 8 - ArgSize;
2448 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2450 // Create load nodes to retrieve arguments from the stack.
2451 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2454 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2455 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2456 MVT MemVT = VA.getValVT();
2458 switch (VA.getLocInfo()) {
2461 case CCValAssign::BCvt:
2462 MemVT = VA.getLocVT();
2464 case CCValAssign::SExt:
2465 ExtType = ISD::SEXTLOAD;
2467 case CCValAssign::ZExt:
2468 ExtType = ISD::ZEXTLOAD;
2470 case CCValAssign::AExt:
2471 ExtType = ISD::EXTLOAD;
2475 ArgValue = DAG.getExtLoad(
2476 ExtType, DL, VA.getLocVT(), Chain, FIN,
2477 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2478 MemVT, false, false, false, 0);
2480 InVals.push_back(ArgValue);
2486 if (!Subtarget->isTargetDarwin()) {
2487 // The AAPCS variadic function ABI is identical to the non-variadic
2488 // one. As a result there may be more arguments in registers and we should
2489 // save them for future reference.
2490 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2493 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2494 // This will point to the next argument passed via stack.
2495 unsigned StackOffset = CCInfo.getNextStackOffset();
2496 // We currently pass all varargs at 8-byte alignment.
2497 StackOffset = ((StackOffset + 7) & ~7);
2498 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2501 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2502 unsigned StackArgSize = CCInfo.getNextStackOffset();
2503 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2504 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2505 // This is a non-standard ABI so by fiat I say we're allowed to make full
2506 // use of the stack area to be popped, which must be aligned to 16 bytes in
2508 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2510 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2511 // a multiple of 16.
2512 FuncInfo->setArgumentStackToRestore(StackArgSize);
2514 // This realignment carries over to the available bytes below. Our own
2515 // callers will guarantee the space is free by giving an aligned value to
2518 // Even if we're not expected to free up the space, it's useful to know how
2519 // much is there while considering tail calls (because we can reuse it).
2520 FuncInfo->setBytesInStackArgArea(StackArgSize);
2525 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2526 SelectionDAG &DAG, SDLoc DL,
2527 SDValue &Chain) const {
2528 MachineFunction &MF = DAG.getMachineFunction();
2529 MachineFrameInfo *MFI = MF.getFrameInfo();
2530 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2531 auto PtrVT = getPointerTy(DAG.getDataLayout());
2533 SmallVector<SDValue, 8> MemOps;
2535 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2536 AArch64::X3, AArch64::X4, AArch64::X5,
2537 AArch64::X6, AArch64::X7 };
2538 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2539 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2541 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2543 if (GPRSaveSize != 0) {
2544 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2546 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2548 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2549 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2550 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2551 SDValue Store = DAG.getStore(
2552 Val.getValue(1), DL, Val, FIN,
2553 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2555 MemOps.push_back(Store);
2557 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2560 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2561 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2563 if (Subtarget->hasFPARMv8()) {
2564 static const MCPhysReg FPRArgRegs[] = {
2565 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2566 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2567 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2568 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2570 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2572 if (FPRSaveSize != 0) {
2573 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2575 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2577 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2578 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2579 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2581 SDValue Store = DAG.getStore(
2582 Val.getValue(1), DL, Val, FIN,
2583 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2585 MemOps.push_back(Store);
2586 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2587 DAG.getConstant(16, DL, PtrVT));
2590 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2591 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2594 if (!MemOps.empty()) {
2595 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2599 /// LowerCallResult - Lower the result values of a call into the
2600 /// appropriate copies out of appropriate physical registers.
2601 SDValue AArch64TargetLowering::LowerCallResult(
2602 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2603 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2604 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2605 SDValue ThisVal) const {
2606 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2607 ? RetCC_AArch64_WebKit_JS
2608 : RetCC_AArch64_AAPCS;
2609 // Assign locations to each value returned by this call.
2610 SmallVector<CCValAssign, 16> RVLocs;
2611 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2613 CCInfo.AnalyzeCallResult(Ins, RetCC);
2615 // Copy all of the result registers out of their specified physreg.
2616 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2617 CCValAssign VA = RVLocs[i];
2619 // Pass 'this' value directly from the argument to return value, to avoid
2620 // reg unit interference
2621 if (i == 0 && isThisReturn) {
2622 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2623 "unexpected return calling convention register assignment");
2624 InVals.push_back(ThisVal);
2629 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2630 Chain = Val.getValue(1);
2631 InFlag = Val.getValue(2);
2633 switch (VA.getLocInfo()) {
2635 llvm_unreachable("Unknown loc info!");
2636 case CCValAssign::Full:
2638 case CCValAssign::BCvt:
2639 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2643 InVals.push_back(Val);
2649 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2650 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2651 bool isCalleeStructRet, bool isCallerStructRet,
2652 const SmallVectorImpl<ISD::OutputArg> &Outs,
2653 const SmallVectorImpl<SDValue> &OutVals,
2654 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2655 // For CallingConv::C this function knows whether the ABI needs
2656 // changing. That's not true for other conventions so they will have to opt in
2658 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2661 const MachineFunction &MF = DAG.getMachineFunction();
2662 const Function *CallerF = MF.getFunction();
2663 CallingConv::ID CallerCC = CallerF->getCallingConv();
2664 bool CCMatch = CallerCC == CalleeCC;
2666 // Byval parameters hand the function a pointer directly into the stack area
2667 // we want to reuse during a tail call. Working around this *is* possible (see
2668 // X86) but less efficient and uglier in LowerCall.
2669 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2670 e = CallerF->arg_end();
2672 if (i->hasByValAttr())
2675 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2676 if (IsTailCallConvention(CalleeCC) && CCMatch)
2681 // Externally-defined functions with weak linkage should not be
2682 // tail-called on AArch64 when the OS does not support dynamic
2683 // pre-emption of symbols, as the AAELF spec requires normal calls
2684 // to undefined weak functions to be replaced with a NOP or jump to the
2685 // next instruction. The behaviour of branch instructions in this
2686 // situation (as used for tail calls) is implementation-defined, so we
2687 // cannot rely on the linker replacing the tail call with a return.
2688 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2689 const GlobalValue *GV = G->getGlobal();
2690 const Triple &TT = getTargetMachine().getTargetTriple();
2691 if (GV->hasExternalWeakLinkage() &&
2692 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2696 // Now we search for cases where we can use a tail call without changing the
2697 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2700 // I want anyone implementing a new calling convention to think long and hard
2701 // about this assert.
2702 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2703 "Unexpected variadic calling convention");
2705 if (isVarArg && !Outs.empty()) {
2706 // At least two cases here: if caller is fastcc then we can't have any
2707 // memory arguments (we'd be expected to clean up the stack afterwards). If
2708 // caller is C then we could potentially use its argument area.
2710 // FIXME: for now we take the most conservative of these in both cases:
2711 // disallow all variadic memory operands.
2712 SmallVector<CCValAssign, 16> ArgLocs;
2713 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2716 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2717 for (const CCValAssign &ArgLoc : ArgLocs)
2718 if (!ArgLoc.isRegLoc())
2722 // If the calling conventions do not match, then we'd better make sure the
2723 // results are returned in the same way as what the caller expects.
2725 SmallVector<CCValAssign, 16> RVLocs1;
2726 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2728 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2730 SmallVector<CCValAssign, 16> RVLocs2;
2731 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2733 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2735 if (RVLocs1.size() != RVLocs2.size())
2737 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2738 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2740 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2742 if (RVLocs1[i].isRegLoc()) {
2743 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2746 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2752 // Nothing more to check if the callee is taking no arguments
2756 SmallVector<CCValAssign, 16> ArgLocs;
2757 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2760 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2762 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2764 // If the stack arguments for this call would fit into our own save area then
2765 // the call can be made tail.
2766 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2769 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2771 MachineFrameInfo *MFI,
2772 int ClobberedFI) const {
2773 SmallVector<SDValue, 8> ArgChains;
2774 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2775 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2777 // Include the original chain at the beginning of the list. When this is
2778 // used by target LowerCall hooks, this helps legalize find the
2779 // CALLSEQ_BEGIN node.
2780 ArgChains.push_back(Chain);
2782 // Add a chain value for each stack argument corresponding
2783 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2784 UE = DAG.getEntryNode().getNode()->use_end();
2786 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2787 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2788 if (FI->getIndex() < 0) {
2789 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2790 int64_t InLastByte = InFirstByte;
2791 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2793 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2794 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2795 ArgChains.push_back(SDValue(L, 1));
2798 // Build a tokenfactor for all the chains.
2799 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2802 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2803 bool TailCallOpt) const {
2804 return CallCC == CallingConv::Fast && TailCallOpt;
2807 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2808 return CallCC == CallingConv::Fast;
2811 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2812 /// and add input and output parameter nodes.
2814 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2815 SmallVectorImpl<SDValue> &InVals) const {
2816 SelectionDAG &DAG = CLI.DAG;
2818 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2819 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2820 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2821 SDValue Chain = CLI.Chain;
2822 SDValue Callee = CLI.Callee;
2823 bool &IsTailCall = CLI.IsTailCall;
2824 CallingConv::ID CallConv = CLI.CallConv;
2825 bool IsVarArg = CLI.IsVarArg;
2827 MachineFunction &MF = DAG.getMachineFunction();
2828 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2829 bool IsThisReturn = false;
2831 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2832 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2833 bool IsSibCall = false;
2836 // Check if it's really possible to do a tail call.
2837 IsTailCall = isEligibleForTailCallOptimization(
2838 Callee, CallConv, IsVarArg, IsStructRet,
2839 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2840 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2841 report_fatal_error("failed to perform tail call elimination on a call "
2842 "site marked musttail");
2844 // A sibling call is one where we're under the usual C ABI and not planning
2845 // to change that but can still do a tail call:
2846 if (!TailCallOpt && IsTailCall)
2853 // Analyze operands of the call, assigning locations to each operand.
2854 SmallVector<CCValAssign, 16> ArgLocs;
2855 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2859 // Handle fixed and variable vector arguments differently.
2860 // Variable vector arguments always go into memory.
2861 unsigned NumArgs = Outs.size();
2863 for (unsigned i = 0; i != NumArgs; ++i) {
2864 MVT ArgVT = Outs[i].VT;
2865 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2866 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2867 /*IsVarArg=*/ !Outs[i].IsFixed);
2868 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2869 assert(!Res && "Call operand has unhandled type");
2873 // At this point, Outs[].VT may already be promoted to i32. To correctly
2874 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2875 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2876 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2877 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2879 unsigned NumArgs = Outs.size();
2880 for (unsigned i = 0; i != NumArgs; ++i) {
2881 MVT ValVT = Outs[i].VT;
2882 // Get type of the original argument.
2883 EVT ActualVT = getValueType(DAG.getDataLayout(),
2884 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2885 /*AllowUnknown*/ true);
2886 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2887 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2888 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2889 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2891 else if (ActualMVT == MVT::i16)
2894 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2895 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2896 assert(!Res && "Call operand has unhandled type");
2901 // Get a count of how many bytes are to be pushed on the stack.
2902 unsigned NumBytes = CCInfo.getNextStackOffset();
2905 // Since we're not changing the ABI to make this a tail call, the memory
2906 // operands are already available in the caller's incoming argument space.
2910 // FPDiff is the byte offset of the call's argument area from the callee's.
2911 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2912 // by this amount for a tail call. In a sibling call it must be 0 because the
2913 // caller will deallocate the entire stack and the callee still expects its
2914 // arguments to begin at SP+0. Completely unused for non-tail calls.
2917 if (IsTailCall && !IsSibCall) {
2918 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2920 // Since callee will pop argument stack as a tail call, we must keep the
2921 // popped size 16-byte aligned.
2922 NumBytes = RoundUpToAlignment(NumBytes, 16);
2924 // FPDiff will be negative if this tail call requires more space than we
2925 // would automatically have in our incoming argument space. Positive if we
2926 // can actually shrink the stack.
2927 FPDiff = NumReusableBytes - NumBytes;
2929 // The stack pointer must be 16-byte aligned at all times it's used for a
2930 // memory operation, which in practice means at *all* times and in
2931 // particular across call boundaries. Therefore our own arguments started at
2932 // a 16-byte aligned SP and the delta applied for the tail call should
2933 // satisfy the same constraint.
2934 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2937 // Adjust the stack pointer for the new arguments...
2938 // These operations are automatically eliminated by the prolog/epilog pass
2940 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2944 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2945 getPointerTy(DAG.getDataLayout()));
2947 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2948 SmallVector<SDValue, 8> MemOpChains;
2949 auto PtrVT = getPointerTy(DAG.getDataLayout());
2951 // Walk the register/memloc assignments, inserting copies/loads.
2952 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2953 ++i, ++realArgIdx) {
2954 CCValAssign &VA = ArgLocs[i];
2955 SDValue Arg = OutVals[realArgIdx];
2956 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2958 // Promote the value if needed.
2959 switch (VA.getLocInfo()) {
2961 llvm_unreachable("Unknown loc info!");
2962 case CCValAssign::Full:
2964 case CCValAssign::SExt:
2965 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2967 case CCValAssign::ZExt:
2968 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2970 case CCValAssign::AExt:
2971 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2972 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2973 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2974 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2976 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2978 case CCValAssign::BCvt:
2979 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2981 case CCValAssign::FPExt:
2982 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2986 if (VA.isRegLoc()) {
2987 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2988 assert(VA.getLocVT() == MVT::i64 &&
2989 "unexpected calling convention register assignment");
2990 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2991 "unexpected use of 'returned'");
2992 IsThisReturn = true;
2994 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2996 assert(VA.isMemLoc());
2999 MachinePointerInfo DstInfo;
3001 // FIXME: This works on big-endian for composite byvals, which are the
3002 // common case. It should also work for fundamental types too.
3003 uint32_t BEAlign = 0;
3004 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3005 : VA.getValVT().getSizeInBits();
3006 OpSize = (OpSize + 7) / 8;
3007 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3008 !Flags.isInConsecutiveRegs()) {
3010 BEAlign = 8 - OpSize;
3012 unsigned LocMemOffset = VA.getLocMemOffset();
3013 int32_t Offset = LocMemOffset + BEAlign;
3014 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3015 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3018 Offset = Offset + FPDiff;
3019 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3021 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3023 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3025 // Make sure any stack arguments overlapping with where we're storing
3026 // are loaded before this eventual operation. Otherwise they'll be
3028 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3030 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3032 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3033 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3037 if (Outs[i].Flags.isByVal()) {
3039 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3040 SDValue Cpy = DAG.getMemcpy(
3041 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3042 /*isVol = */ false, /*AlwaysInline = */ false,
3043 /*isTailCall = */ false,
3044 DstInfo, MachinePointerInfo());
3046 MemOpChains.push_back(Cpy);
3048 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3049 // promoted to a legal register type i32, we should truncate Arg back to
3051 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3052 VA.getValVT() == MVT::i16)
3053 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3056 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3057 MemOpChains.push_back(Store);
3062 if (!MemOpChains.empty())
3063 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3065 // Build a sequence of copy-to-reg nodes chained together with token chain
3066 // and flag operands which copy the outgoing args into the appropriate regs.
3068 for (auto &RegToPass : RegsToPass) {
3069 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3070 RegToPass.second, InFlag);
3071 InFlag = Chain.getValue(1);
3074 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3075 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3076 // node so that legalize doesn't hack it.
3077 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3078 Subtarget->isTargetMachO()) {
3079 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3080 const GlobalValue *GV = G->getGlobal();
3081 bool InternalLinkage = GV->hasInternalLinkage();
3082 if (InternalLinkage)
3083 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3086 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3087 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3089 } else if (ExternalSymbolSDNode *S =
3090 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3091 const char *Sym = S->getSymbol();
3092 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3093 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3095 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3096 const GlobalValue *GV = G->getGlobal();
3097 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3098 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3099 const char *Sym = S->getSymbol();
3100 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3103 // We don't usually want to end the call-sequence here because we would tidy
3104 // the frame up *after* the call, however in the ABI-changing tail-call case
3105 // we've carefully laid out the parameters so that when sp is reset they'll be
3106 // in the correct location.
3107 if (IsTailCall && !IsSibCall) {
3108 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3109 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3110 InFlag = Chain.getValue(1);
3113 std::vector<SDValue> Ops;
3114 Ops.push_back(Chain);
3115 Ops.push_back(Callee);
3118 // Each tail call may have to adjust the stack by a different amount, so
3119 // this information must travel along with the operation for eventual
3120 // consumption by emitEpilogue.
3121 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3124 // Add argument registers to the end of the list so that they are known live
3126 for (auto &RegToPass : RegsToPass)
3127 Ops.push_back(DAG.getRegister(RegToPass.first,
3128 RegToPass.second.getValueType()));
3130 // Add a register mask operand representing the call-preserved registers.
3131 const uint32_t *Mask;
3132 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3134 // For 'this' returns, use the X0-preserving mask if applicable
3135 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3137 IsThisReturn = false;
3138 Mask = TRI->getCallPreservedMask(MF, CallConv);
3141 Mask = TRI->getCallPreservedMask(MF, CallConv);
3143 assert(Mask && "Missing call preserved mask for calling convention");
3144 Ops.push_back(DAG.getRegisterMask(Mask));
3146 if (InFlag.getNode())
3147 Ops.push_back(InFlag);
3149 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3151 // If we're doing a tall call, use a TC_RETURN here rather than an
3152 // actual call instruction.
3154 MF.getFrameInfo()->setHasTailCall();
3155 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3158 // Returns a chain and a flag for retval copy to use.
3159 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3160 InFlag = Chain.getValue(1);
3162 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3163 ? RoundUpToAlignment(NumBytes, 16)
3166 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3167 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3170 InFlag = Chain.getValue(1);
3172 // Handle result values, copying them out of physregs into vregs that we
3174 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3175 InVals, IsThisReturn,
3176 IsThisReturn ? OutVals[0] : SDValue());
3179 bool AArch64TargetLowering::CanLowerReturn(
3180 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3181 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3182 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3183 ? RetCC_AArch64_WebKit_JS
3184 : RetCC_AArch64_AAPCS;
3185 SmallVector<CCValAssign, 16> RVLocs;
3186 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3187 return CCInfo.CheckReturn(Outs, RetCC);
3191 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3193 const SmallVectorImpl<ISD::OutputArg> &Outs,
3194 const SmallVectorImpl<SDValue> &OutVals,
3195 SDLoc DL, SelectionDAG &DAG) const {
3196 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3197 ? RetCC_AArch64_WebKit_JS
3198 : RetCC_AArch64_AAPCS;
3199 SmallVector<CCValAssign, 16> RVLocs;
3200 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3202 CCInfo.AnalyzeReturn(Outs, RetCC);
3204 // Copy the result values into the output registers.
3206 SmallVector<SDValue, 4> RetOps(1, Chain);
3207 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3208 ++i, ++realRVLocIdx) {
3209 CCValAssign &VA = RVLocs[i];
3210 assert(VA.isRegLoc() && "Can only return in registers!");
3211 SDValue Arg = OutVals[realRVLocIdx];
3213 switch (VA.getLocInfo()) {
3215 llvm_unreachable("Unknown loc info!");
3216 case CCValAssign::Full:
3217 if (Outs[i].ArgVT == MVT::i1) {
3218 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3219 // value. This is strictly redundant on Darwin (which uses "zeroext
3220 // i1"), but will be optimised out before ISel.
3221 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3222 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3225 case CCValAssign::BCvt:
3226 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3230 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3231 Flag = Chain.getValue(1);
3232 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3235 RetOps[0] = Chain; // Update chain.
3237 // Add the flag if we have it.
3239 RetOps.push_back(Flag);
3241 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3244 //===----------------------------------------------------------------------===//
3245 // Other Lowering Code
3246 //===----------------------------------------------------------------------===//
3248 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3249 SelectionDAG &DAG) const {
3250 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3252 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3253 const GlobalValue *GV = GN->getGlobal();
3254 unsigned char OpFlags =
3255 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3257 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3258 "unexpected offset in global node");
3260 // This also catched the large code model case for Darwin.
3261 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3262 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3263 // FIXME: Once remat is capable of dealing with instructions with register
3264 // operands, expand this into two nodes instead of using a wrapper node.
3265 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3268 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3269 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3270 "use of MO_CONSTPOOL only supported on small model");
3271 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3272 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3273 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3274 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3275 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3276 SDValue GlobalAddr = DAG.getLoad(
3277 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3278 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3279 /*isVolatile=*/false,
3280 /*isNonTemporal=*/true,
3281 /*isInvariant=*/true, 8);
3282 if (GN->getOffset() != 0)
3283 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3284 DAG.getConstant(GN->getOffset(), DL, PtrVT));
3288 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3289 const unsigned char MO_NC = AArch64II::MO_NC;
3291 AArch64ISD::WrapperLarge, DL, PtrVT,
3292 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3293 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3294 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3295 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3297 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3298 // the only correct model on Darwin.
3299 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3300 OpFlags | AArch64II::MO_PAGE);
3301 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3302 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3304 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3305 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3309 /// \brief Convert a TLS address reference into the correct sequence of loads
3310 /// and calls to compute the variable's address (for Darwin, currently) and
3311 /// return an SDValue containing the final node.
3313 /// Darwin only has one TLS scheme which must be capable of dealing with the
3314 /// fully general situation, in the worst case. This means:
3315 /// + "extern __thread" declaration.
3316 /// + Defined in a possibly unknown dynamic library.
3318 /// The general system is that each __thread variable has a [3 x i64] descriptor
3319 /// which contains information used by the runtime to calculate the address. The
3320 /// only part of this the compiler needs to know about is the first xword, which
3321 /// contains a function pointer that must be called with the address of the
3322 /// entire descriptor in "x0".
3324 /// Since this descriptor may be in a different unit, in general even the
3325 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3327 /// adrp x0, _var@TLVPPAGE
3328 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3329 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3330 /// ; the function pointer
3331 /// blr x1 ; Uses descriptor address in x0
3332 /// ; Address of _var is now in x0.
3334 /// If the address of _var's descriptor *is* known to the linker, then it can
3335 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3336 /// a slight efficiency gain.
3338 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3339 SelectionDAG &DAG) const {
3340 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3343 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3344 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3347 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3348 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3350 // The first entry in the descriptor is a function pointer that we must call
3351 // to obtain the address of the variable.
3352 SDValue Chain = DAG.getEntryNode();
3353 SDValue FuncTLVGet =
3354 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3355 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3357 Chain = FuncTLVGet.getValue(1);
3359 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3360 MFI->setAdjustsStack(true);
3362 // TLS calls preserve all registers except those that absolutely must be
3363 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3365 const uint32_t *Mask =
3366 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3368 // Finally, we can make the call. This is just a degenerate version of a
3369 // normal AArch64 call node: x0 takes the address of the descriptor, and
3370 // returns the address of the variable in this thread.
3371 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3373 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3374 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3375 DAG.getRegisterMask(Mask), Chain.getValue(1));
3376 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3379 /// When accessing thread-local variables under either the general-dynamic or
3380 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3381 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3382 /// is a function pointer to carry out the resolution.
3384 /// The sequence is:
3385 /// adrp x0, :tlsdesc:var
3386 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3387 /// add x0, x0, #:tlsdesc_lo12:var
3388 /// .tlsdesccall var
3390 /// (TPIDR_EL0 offset now in x0)
3392 /// The above sequence must be produced unscheduled, to enable the linker to
3393 /// optimize/relax this sequence.
3394 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3395 /// above sequence, and expanded really late in the compilation flow, to ensure
3396 /// the sequence is produced as per above.
3397 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3398 SelectionDAG &DAG) const {
3399 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3401 SDValue Chain = DAG.getEntryNode();
3402 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3404 SmallVector<SDValue, 2> Ops;
3405 Ops.push_back(Chain);
3406 Ops.push_back(SymAddr);
3408 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3409 SDValue Glue = Chain.getValue(1);
3411 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3415 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3416 SelectionDAG &DAG) const {
3417 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3418 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3419 "ELF TLS only supported in small memory model");
3420 // Different choices can be made for the maximum size of the TLS area for a
3421 // module. For the small address model, the default TLS size is 16MiB and the
3422 // maximum TLS size is 4GiB.
3423 // FIXME: add -mtls-size command line option and make it control the 16MiB
3424 // vs. 4GiB code sequence generation.
3425 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3427 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3429 if (DAG.getTarget().Options.EmulatedTLS)
3430 return LowerToTLSEmulatedModel(GA, DAG);
3432 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3433 if (Model == TLSModel::LocalDynamic)
3434 Model = TLSModel::GeneralDynamic;
3438 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3440 const GlobalValue *GV = GA->getGlobal();
3442 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3444 if (Model == TLSModel::LocalExec) {
3445 SDValue HiVar = DAG.getTargetGlobalAddress(
3446 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3447 SDValue LoVar = DAG.getTargetGlobalAddress(
3449 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3451 SDValue TPWithOff_lo =
3452 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3454 DAG.getTargetConstant(0, DL, MVT::i32)),
3457 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3459 DAG.getTargetConstant(0, DL, MVT::i32)),
3462 } else if (Model == TLSModel::InitialExec) {
3463 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3464 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3465 } else if (Model == TLSModel::LocalDynamic) {
3466 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3467 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3468 // the beginning of the module's TLS region, followed by a DTPREL offset
3471 // These accesses will need deduplicating if there's more than one.
3472 AArch64FunctionInfo *MFI =
3473 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3474 MFI->incNumLocalDynamicTLSAccesses();
3476 // The call needs a relocation too for linker relaxation. It doesn't make
3477 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3479 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3482 // Now we can calculate the offset from TPIDR_EL0 to this module's
3483 // thread-local area.
3484 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3486 // Now use :dtprel_whatever: operations to calculate this variable's offset
3487 // in its thread-storage area.
3488 SDValue HiVar = DAG.getTargetGlobalAddress(
3489 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3490 SDValue LoVar = DAG.getTargetGlobalAddress(
3491 GV, DL, MVT::i64, 0,
3492 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3494 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3495 DAG.getTargetConstant(0, DL, MVT::i32)),
3497 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3498 DAG.getTargetConstant(0, DL, MVT::i32)),
3500 } else if (Model == TLSModel::GeneralDynamic) {
3501 // The call needs a relocation too for linker relaxation. It doesn't make
3502 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3505 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3507 // Finally we can make a call to calculate the offset from tpidr_el0.
3508 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3510 llvm_unreachable("Unsupported ELF TLS access model");
3512 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3515 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3516 SelectionDAG &DAG) const {
3517 if (Subtarget->isTargetDarwin())
3518 return LowerDarwinGlobalTLSAddress(Op, DAG);
3519 else if (Subtarget->isTargetELF())
3520 return LowerELFGlobalTLSAddress(Op, DAG);
3522 llvm_unreachable("Unexpected platform trying to use TLS");
3524 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3525 SDValue Chain = Op.getOperand(0);
3526 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3527 SDValue LHS = Op.getOperand(2);
3528 SDValue RHS = Op.getOperand(3);
3529 SDValue Dest = Op.getOperand(4);
3532 // Handle f128 first, since lowering it will result in comparing the return
3533 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3534 // is expecting to deal with.
3535 if (LHS.getValueType() == MVT::f128) {
3536 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3538 // If softenSetCCOperands returned a scalar, we need to compare the result
3539 // against zero to select between true and false values.
3540 if (!RHS.getNode()) {
3541 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3546 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3548 unsigned Opc = LHS.getOpcode();
3549 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3550 cast<ConstantSDNode>(RHS)->isOne() &&
3551 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3552 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3553 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3554 "Unexpected condition code.");
3555 // Only lower legal XALUO ops.
3556 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3559 // The actual operation with overflow check.
3560 AArch64CC::CondCode OFCC;
3561 SDValue Value, Overflow;
3562 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3564 if (CC == ISD::SETNE)
3565 OFCC = getInvertedCondCode(OFCC);
3566 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3568 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3572 if (LHS.getValueType().isInteger()) {
3573 assert((LHS.getValueType() == RHS.getValueType()) &&
3574 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3576 // If the RHS of the comparison is zero, we can potentially fold this
3577 // to a specialized branch.
3578 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3579 if (RHSC && RHSC->getZExtValue() == 0) {
3580 if (CC == ISD::SETEQ) {
3581 // See if we can use a TBZ to fold in an AND as well.
3582 // TBZ has a smaller branch displacement than CBZ. If the offset is
3583 // out of bounds, a late MI-layer pass rewrites branches.
3584 // 403.gcc is an example that hits this case.
3585 if (LHS.getOpcode() == ISD::AND &&
3586 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3587 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3588 SDValue Test = LHS.getOperand(0);
3589 uint64_t Mask = LHS.getConstantOperandVal(1);
3590 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3591 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3595 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3596 } else if (CC == ISD::SETNE) {
3597 // See if we can use a TBZ to fold in an AND as well.
3598 // TBZ has a smaller branch displacement than CBZ. If the offset is
3599 // out of bounds, a late MI-layer pass rewrites branches.
3600 // 403.gcc is an example that hits this case.
3601 if (LHS.getOpcode() == ISD::AND &&
3602 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3603 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3604 SDValue Test = LHS.getOperand(0);
3605 uint64_t Mask = LHS.getConstantOperandVal(1);
3606 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3607 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3611 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3612 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3613 // Don't combine AND since emitComparison converts the AND to an ANDS
3614 // (a.k.a. TST) and the test in the test bit and branch instruction
3615 // becomes redundant. This would also increase register pressure.
3616 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3617 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3618 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3621 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3622 LHS.getOpcode() != ISD::AND) {
3623 // Don't combine AND since emitComparison converts the AND to an ANDS
3624 // (a.k.a. TST) and the test in the test bit and branch instruction
3625 // becomes redundant. This would also increase register pressure.
3626 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3627 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3628 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3632 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3633 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3637 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3639 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3640 // clean. Some of them require two branches to implement.
3641 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3642 AArch64CC::CondCode CC1, CC2;
3643 changeFPCCToAArch64CC(CC, CC1, CC2);
3644 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3646 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3647 if (CC2 != AArch64CC::AL) {
3648 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3649 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3656 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3657 SelectionDAG &DAG) const {
3658 EVT VT = Op.getValueType();
3661 SDValue In1 = Op.getOperand(0);
3662 SDValue In2 = Op.getOperand(1);
3663 EVT SrcVT = In2.getValueType();
3665 if (SrcVT.bitsLT(VT))
3666 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3667 else if (SrcVT.bitsGT(VT))
3668 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3673 SDValue VecVal1, VecVal2;
3674 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3676 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3677 EltMask = 0x80000000ULL;
3679 if (!VT.isVector()) {
3680 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3681 DAG.getUNDEF(VecVT), In1);
3682 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3683 DAG.getUNDEF(VecVT), In2);
3685 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3686 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3688 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3692 // We want to materialize a mask with the high bit set, but the AdvSIMD
3693 // immediate moves cannot materialize that in a single instruction for
3694 // 64-bit elements. Instead, materialize zero and then negate it.
3697 if (!VT.isVector()) {
3698 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3699 DAG.getUNDEF(VecVT), In1);
3700 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3701 DAG.getUNDEF(VecVT), In2);
3703 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3704 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3707 llvm_unreachable("Invalid type for copysign!");
3710 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3712 // If we couldn't materialize the mask above, then the mask vector will be
3713 // the zero vector, and we need to negate it here.
3714 if (VT == MVT::f64 || VT == MVT::v2f64) {
3715 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3716 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3717 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3721 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3724 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3725 else if (VT == MVT::f64)
3726 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3728 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3731 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3732 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3733 Attribute::NoImplicitFloat))
3736 if (!Subtarget->hasNEON())
3739 // While there is no integer popcount instruction, it can
3740 // be more efficiently lowered to the following sequence that uses
3741 // AdvSIMD registers/instructions as long as the copies to/from
3742 // the AdvSIMD registers are cheap.
3743 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3744 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3745 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3746 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3747 SDValue Val = Op.getOperand(0);
3749 EVT VT = Op.getValueType();
3752 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3753 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3755 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3756 SDValue UaddLV = DAG.getNode(
3757 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3758 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3761 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3765 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3767 if (Op.getValueType().isVector())
3768 return LowerVSETCC(Op, DAG);
3770 SDValue LHS = Op.getOperand(0);
3771 SDValue RHS = Op.getOperand(1);
3772 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3775 // We chose ZeroOrOneBooleanContents, so use zero and one.
3776 EVT VT = Op.getValueType();
3777 SDValue TVal = DAG.getConstant(1, dl, VT);
3778 SDValue FVal = DAG.getConstant(0, dl, VT);
3780 // Handle f128 first, since one possible outcome is a normal integer
3781 // comparison which gets picked up by the next if statement.
3782 if (LHS.getValueType() == MVT::f128) {
3783 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3785 // If softenSetCCOperands returned a scalar, use it.
3786 if (!RHS.getNode()) {
3787 assert(LHS.getValueType() == Op.getValueType() &&
3788 "Unexpected setcc expansion!");
3793 if (LHS.getValueType().isInteger()) {
3796 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3798 // Note that we inverted the condition above, so we reverse the order of
3799 // the true and false operands here. This will allow the setcc to be
3800 // matched to a single CSINC instruction.
3801 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3804 // Now we know we're dealing with FP values.
3805 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3807 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3808 // and do the comparison.
3809 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3811 AArch64CC::CondCode CC1, CC2;
3812 changeFPCCToAArch64CC(CC, CC1, CC2);
3813 if (CC2 == AArch64CC::AL) {
3814 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3815 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3817 // Note that we inverted the condition above, so we reverse the order of
3818 // the true and false operands here. This will allow the setcc to be
3819 // matched to a single CSINC instruction.
3820 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3822 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3823 // totally clean. Some of them require two CSELs to implement. As is in
3824 // this case, we emit the first CSEL and then emit a second using the output
3825 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3827 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3828 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3830 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3832 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3833 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3837 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3838 SDValue RHS, SDValue TVal,
3839 SDValue FVal, SDLoc dl,
3840 SelectionDAG &DAG) const {
3841 // Handle f128 first, because it will result in a comparison of some RTLIB
3842 // call result against zero.
3843 if (LHS.getValueType() == MVT::f128) {
3844 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3846 // If softenSetCCOperands returned a scalar, we need to compare the result
3847 // against zero to select between true and false values.
3848 if (!RHS.getNode()) {
3849 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3854 // Handle integers first.
3855 if (LHS.getValueType().isInteger()) {
3856 assert((LHS.getValueType() == RHS.getValueType()) &&
3857 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3859 unsigned Opcode = AArch64ISD::CSEL;
3861 // If both the TVal and the FVal are constants, see if we can swap them in
3862 // order to for a CSINV or CSINC out of them.
3863 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3864 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3866 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3867 std::swap(TVal, FVal);
3868 std::swap(CTVal, CFVal);
3869 CC = ISD::getSetCCInverse(CC, true);
3870 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3871 std::swap(TVal, FVal);
3872 std::swap(CTVal, CFVal);
3873 CC = ISD::getSetCCInverse(CC, true);
3874 } else if (TVal.getOpcode() == ISD::XOR) {
3875 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3876 // with a CSINV rather than a CSEL.
3877 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3879 if (CVal && CVal->isAllOnesValue()) {
3880 std::swap(TVal, FVal);
3881 std::swap(CTVal, CFVal);
3882 CC = ISD::getSetCCInverse(CC, true);
3884 } else if (TVal.getOpcode() == ISD::SUB) {
3885 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3886 // that we can match with a CSNEG rather than a CSEL.
3887 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3889 if (CVal && CVal->isNullValue()) {
3890 std::swap(TVal, FVal);
3891 std::swap(CTVal, CFVal);
3892 CC = ISD::getSetCCInverse(CC, true);
3894 } else if (CTVal && CFVal) {
3895 const int64_t TrueVal = CTVal->getSExtValue();
3896 const int64_t FalseVal = CFVal->getSExtValue();
3899 // If both TVal and FVal are constants, see if FVal is the
3900 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3901 // instead of a CSEL in that case.
3902 if (TrueVal == ~FalseVal) {
3903 Opcode = AArch64ISD::CSINV;
3904 } else if (TrueVal == -FalseVal) {
3905 Opcode = AArch64ISD::CSNEG;
3906 } else if (TVal.getValueType() == MVT::i32) {
3907 // If our operands are only 32-bit wide, make sure we use 32-bit
3908 // arithmetic for the check whether we can use CSINC. This ensures that
3909 // the addition in the check will wrap around properly in case there is
3910 // an overflow (which would not be the case if we do the check with
3911 // 64-bit arithmetic).
3912 const uint32_t TrueVal32 = CTVal->getZExtValue();
3913 const uint32_t FalseVal32 = CFVal->getZExtValue();
3915 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3916 Opcode = AArch64ISD::CSINC;
3918 if (TrueVal32 > FalseVal32) {
3922 // 64-bit check whether we can use CSINC.
3923 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3924 Opcode = AArch64ISD::CSINC;
3926 if (TrueVal > FalseVal) {
3931 // Swap TVal and FVal if necessary.
3933 std::swap(TVal, FVal);
3934 std::swap(CTVal, CFVal);
3935 CC = ISD::getSetCCInverse(CC, true);
3938 if (Opcode != AArch64ISD::CSEL) {
3939 // Drop FVal since we can get its value by simply inverting/negating
3946 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3948 EVT VT = TVal.getValueType();
3949 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3952 // Now we know we're dealing with FP values.
3953 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3954 assert(LHS.getValueType() == RHS.getValueType());
3955 EVT VT = TVal.getValueType();
3956 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3958 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3959 // clean. Some of them require two CSELs to implement.
3960 AArch64CC::CondCode CC1, CC2;
3961 changeFPCCToAArch64CC(CC, CC1, CC2);
3962 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3963 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3965 // If we need a second CSEL, emit it, using the output of the first as the
3966 // RHS. We're effectively OR'ing the two CC's together.
3967 if (CC2 != AArch64CC::AL) {
3968 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3969 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3972 // Otherwise, return the output of the first CSEL.
3976 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3977 SelectionDAG &DAG) const {
3978 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3979 SDValue LHS = Op.getOperand(0);
3980 SDValue RHS = Op.getOperand(1);
3981 SDValue TVal = Op.getOperand(2);
3982 SDValue FVal = Op.getOperand(3);
3984 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3987 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3988 SelectionDAG &DAG) const {
3989 SDValue CCVal = Op->getOperand(0);
3990 SDValue TVal = Op->getOperand(1);
3991 SDValue FVal = Op->getOperand(2);
3994 unsigned Opc = CCVal.getOpcode();
3995 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3997 if (CCVal.getResNo() == 1 &&
3998 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3999 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4000 // Only lower legal XALUO ops.
4001 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4004 AArch64CC::CondCode OFCC;
4005 SDValue Value, Overflow;
4006 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4007 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4009 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4013 // Lower it the same way as we would lower a SELECT_CC node.
4016 if (CCVal.getOpcode() == ISD::SETCC) {
4017 LHS = CCVal.getOperand(0);
4018 RHS = CCVal.getOperand(1);
4019 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4022 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4025 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4028 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4029 SelectionDAG &DAG) const {
4030 // Jump table entries as PC relative offsets. No additional tweaking
4031 // is necessary here. Just get the address of the jump table.
4032 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4033 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4036 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4037 !Subtarget->isTargetMachO()) {
4038 const unsigned char MO_NC = AArch64II::MO_NC;
4040 AArch64ISD::WrapperLarge, DL, PtrVT,
4041 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4042 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4043 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4044 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4045 AArch64II::MO_G0 | MO_NC));
4049 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4050 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4051 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4052 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4053 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4056 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4057 SelectionDAG &DAG) const {
4058 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4059 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4062 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4063 // Use the GOT for the large code model on iOS.
4064 if (Subtarget->isTargetMachO()) {
4065 SDValue GotAddr = DAG.getTargetConstantPool(
4066 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4068 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4071 const unsigned char MO_NC = AArch64II::MO_NC;
4073 AArch64ISD::WrapperLarge, DL, PtrVT,
4074 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4075 CP->getOffset(), AArch64II::MO_G3),
4076 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4077 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4078 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4079 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4080 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4081 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4083 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4084 // ELF, the only valid one on Darwin.
4086 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4087 CP->getOffset(), AArch64II::MO_PAGE);
4088 SDValue Lo = DAG.getTargetConstantPool(
4089 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4090 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4092 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4093 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4097 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4098 SelectionDAG &DAG) const {
4099 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4100 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4102 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4103 !Subtarget->isTargetMachO()) {
4104 const unsigned char MO_NC = AArch64II::MO_NC;
4106 AArch64ISD::WrapperLarge, DL, PtrVT,
4107 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4108 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4109 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4110 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4112 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4113 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4115 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4116 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4120 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4121 SelectionDAG &DAG) const {
4122 AArch64FunctionInfo *FuncInfo =
4123 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4126 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4127 getPointerTy(DAG.getDataLayout()));
4128 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4129 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4130 MachinePointerInfo(SV), false, false, 0);
4133 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4134 SelectionDAG &DAG) const {
4135 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4136 // Standard, section B.3.
4137 MachineFunction &MF = DAG.getMachineFunction();
4138 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4139 auto PtrVT = getPointerTy(DAG.getDataLayout());
4142 SDValue Chain = Op.getOperand(0);
4143 SDValue VAList = Op.getOperand(1);
4144 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4145 SmallVector<SDValue, 4> MemOps;
4147 // void *__stack at offset 0
4148 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4149 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4150 MachinePointerInfo(SV), false, false, 8));
4152 // void *__gr_top at offset 8
4153 int GPRSize = FuncInfo->getVarArgsGPRSize();
4155 SDValue GRTop, GRTopAddr;
4158 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4160 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4161 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4162 DAG.getConstant(GPRSize, DL, PtrVT));
4164 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4165 MachinePointerInfo(SV, 8), false, false, 8));
4168 // void *__vr_top at offset 16
4169 int FPRSize = FuncInfo->getVarArgsFPRSize();
4171 SDValue VRTop, VRTopAddr;
4172 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4173 DAG.getConstant(16, DL, PtrVT));
4175 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4176 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4177 DAG.getConstant(FPRSize, DL, PtrVT));
4179 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4180 MachinePointerInfo(SV, 16), false, false, 8));
4183 // int __gr_offs at offset 24
4184 SDValue GROffsAddr =
4185 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4186 MemOps.push_back(DAG.getStore(Chain, DL,
4187 DAG.getConstant(-GPRSize, DL, MVT::i32),
4188 GROffsAddr, MachinePointerInfo(SV, 24), false,
4191 // int __vr_offs at offset 28
4192 SDValue VROffsAddr =
4193 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4194 MemOps.push_back(DAG.getStore(Chain, DL,
4195 DAG.getConstant(-FPRSize, DL, MVT::i32),
4196 VROffsAddr, MachinePointerInfo(SV, 28), false,
4199 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4202 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4203 SelectionDAG &DAG) const {
4204 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4205 : LowerAAPCS_VASTART(Op, DAG);
4208 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4209 SelectionDAG &DAG) const {
4210 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4213 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4214 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4215 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4217 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4219 DAG.getConstant(VaListSize, DL, MVT::i32),
4220 8, false, false, false, MachinePointerInfo(DestSV),
4221 MachinePointerInfo(SrcSV));
4224 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4225 assert(Subtarget->isTargetDarwin() &&
4226 "automatic va_arg instruction only works on Darwin");
4228 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4229 EVT VT = Op.getValueType();
4231 SDValue Chain = Op.getOperand(0);
4232 SDValue Addr = Op.getOperand(1);
4233 unsigned Align = Op.getConstantOperandVal(3);
4234 auto PtrVT = getPointerTy(DAG.getDataLayout());
4236 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4237 false, false, false, 0);
4238 Chain = VAList.getValue(1);
4241 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4242 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4243 DAG.getConstant(Align - 1, DL, PtrVT));
4244 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4245 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4248 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4249 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4251 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4252 // up to 64 bits. At the very least, we have to increase the striding of the
4253 // vaargs list to match this, and for FP values we need to introduce
4254 // FP_ROUND nodes as well.
4255 if (VT.isInteger() && !VT.isVector())
4257 bool NeedFPTrunc = false;
4258 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4263 // Increment the pointer, VAList, to the next vaarg
4264 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4265 DAG.getConstant(ArgSize, DL, PtrVT));
4266 // Store the incremented VAList to the legalized pointer
4267 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4270 // Load the actual argument out of the pointer VAList
4272 // Load the value as an f64.
4273 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4274 MachinePointerInfo(), false, false, false, 0);
4275 // Round the value down to an f32.
4276 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4277 DAG.getIntPtrConstant(1, DL));
4278 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4279 // Merge the rounded value with the chain output of the load.
4280 return DAG.getMergeValues(Ops, DL);
4283 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4287 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4288 SelectionDAG &DAG) const {
4289 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4290 MFI->setFrameAddressIsTaken(true);
4292 EVT VT = Op.getValueType();
4294 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4296 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4298 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4299 MachinePointerInfo(), false, false, false, 0);
4303 // FIXME? Maybe this could be a TableGen attribute on some registers and
4304 // this table could be generated automatically from RegInfo.
4305 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4306 SelectionDAG &DAG) const {
4307 unsigned Reg = StringSwitch<unsigned>(RegName)
4308 .Case("sp", AArch64::SP)
4312 report_fatal_error(Twine("Invalid register name \""
4313 + StringRef(RegName) + "\"."));
4316 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4317 SelectionDAG &DAG) const {
4318 MachineFunction &MF = DAG.getMachineFunction();
4319 MachineFrameInfo *MFI = MF.getFrameInfo();
4320 MFI->setReturnAddressIsTaken(true);
4322 EVT VT = Op.getValueType();
4324 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4326 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4327 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4328 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4329 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4330 MachinePointerInfo(), false, false, false, 0);
4333 // Return LR, which contains the return address. Mark it an implicit live-in.
4334 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4335 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4338 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4339 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4340 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4341 SelectionDAG &DAG) const {
4342 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4343 EVT VT = Op.getValueType();
4344 unsigned VTBits = VT.getSizeInBits();
4346 SDValue ShOpLo = Op.getOperand(0);
4347 SDValue ShOpHi = Op.getOperand(1);
4348 SDValue ShAmt = Op.getOperand(2);
4350 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4352 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4354 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4355 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4356 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4357 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4358 DAG.getConstant(VTBits, dl, MVT::i64));
4359 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4361 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4362 ISD::SETGE, dl, DAG);
4363 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4365 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4366 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4368 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4370 // AArch64 shifts larger than the register width are wrapped rather than
4371 // clamped, so we can't just emit "hi >> x".
4372 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4373 SDValue TrueValHi = Opc == ISD::SRA
4374 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4375 DAG.getConstant(VTBits - 1, dl,
4377 : DAG.getConstant(0, dl, VT);
4379 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4381 SDValue Ops[2] = { Lo, Hi };
4382 return DAG.getMergeValues(Ops, dl);
4385 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4386 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4387 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4388 SelectionDAG &DAG) const {
4389 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4390 EVT VT = Op.getValueType();
4391 unsigned VTBits = VT.getSizeInBits();
4393 SDValue ShOpLo = Op.getOperand(0);
4394 SDValue ShOpHi = Op.getOperand(1);
4395 SDValue ShAmt = Op.getOperand(2);
4398 assert(Op.getOpcode() == ISD::SHL_PARTS);
4399 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4400 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4401 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4402 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4403 DAG.getConstant(VTBits, dl, MVT::i64));
4404 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4405 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4407 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4409 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4410 ISD::SETGE, dl, DAG);
4411 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4413 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4415 // AArch64 shifts of larger than register sizes are wrapped rather than
4416 // clamped, so we can't just emit "lo << a" if a is too big.
4417 SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4418 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4420 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4422 SDValue Ops[2] = { Lo, Hi };
4423 return DAG.getMergeValues(Ops, dl);
4426 bool AArch64TargetLowering::isOffsetFoldingLegal(
4427 const GlobalAddressSDNode *GA) const {
4428 // The AArch64 target doesn't support folding offsets into global addresses.
4432 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4433 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4434 // FIXME: We should be able to handle f128 as well with a clever lowering.
4435 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4439 return AArch64_AM::getFP64Imm(Imm) != -1;
4440 else if (VT == MVT::f32)
4441 return AArch64_AM::getFP32Imm(Imm) != -1;
4445 //===----------------------------------------------------------------------===//
4446 // AArch64 Optimization Hooks
4447 //===----------------------------------------------------------------------===//
4449 //===----------------------------------------------------------------------===//
4450 // AArch64 Inline Assembly Support
4451 //===----------------------------------------------------------------------===//
4453 // Table of Constraints
4454 // TODO: This is the current set of constraints supported by ARM for the
4455 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4457 // r - A general register
4458 // w - An FP/SIMD register of some size in the range v0-v31
4459 // x - An FP/SIMD register of some size in the range v0-v15
4460 // I - Constant that can be used with an ADD instruction
4461 // J - Constant that can be used with a SUB instruction
4462 // K - Constant that can be used with a 32-bit logical instruction
4463 // L - Constant that can be used with a 64-bit logical instruction
4464 // M - Constant that can be used as a 32-bit MOV immediate
4465 // N - Constant that can be used as a 64-bit MOV immediate
4466 // Q - A memory reference with base register and no offset
4467 // S - A symbolic address
4468 // Y - Floating point constant zero
4469 // Z - Integer constant zero
4471 // Note that general register operands will be output using their 64-bit x
4472 // register name, whatever the size of the variable, unless the asm operand
4473 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4474 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4477 /// getConstraintType - Given a constraint letter, return the type of
4478 /// constraint it is for this target.
4479 AArch64TargetLowering::ConstraintType
4480 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4481 if (Constraint.size() == 1) {
4482 switch (Constraint[0]) {
4489 return C_RegisterClass;
4490 // An address with a single base register. Due to the way we
4491 // currently handle addresses it is the same as 'r'.
4496 return TargetLowering::getConstraintType(Constraint);
4499 /// Examine constraint type and operand type and determine a weight value.
4500 /// This object must already have been set up with the operand type
4501 /// and the current alternative constraint selected.
4502 TargetLowering::ConstraintWeight
4503 AArch64TargetLowering::getSingleConstraintMatchWeight(
4504 AsmOperandInfo &info, const char *constraint) const {
4505 ConstraintWeight weight = CW_Invalid;
4506 Value *CallOperandVal = info.CallOperandVal;
4507 // If we don't have a value, we can't do a match,
4508 // but allow it at the lowest weight.
4509 if (!CallOperandVal)
4511 Type *type = CallOperandVal->getType();
4512 // Look at the constraint type.
4513 switch (*constraint) {
4515 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4519 if (type->isFloatingPointTy() || type->isVectorTy())
4520 weight = CW_Register;
4523 weight = CW_Constant;
4529 std::pair<unsigned, const TargetRegisterClass *>
4530 AArch64TargetLowering::getRegForInlineAsmConstraint(
4531 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4532 if (Constraint.size() == 1) {
4533 switch (Constraint[0]) {
4535 if (VT.getSizeInBits() == 64)
4536 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4537 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4540 return std::make_pair(0U, &AArch64::FPR32RegClass);
4541 if (VT.getSizeInBits() == 64)
4542 return std::make_pair(0U, &AArch64::FPR64RegClass);
4543 if (VT.getSizeInBits() == 128)
4544 return std::make_pair(0U, &AArch64::FPR128RegClass);
4546 // The instructions that this constraint is designed for can
4547 // only take 128-bit registers so just use that regclass.
4549 if (VT.getSizeInBits() == 128)
4550 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4554 if (StringRef("{cc}").equals_lower(Constraint))
4555 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4557 // Use the default implementation in TargetLowering to convert the register
4558 // constraint into a member of a register class.
4559 std::pair<unsigned, const TargetRegisterClass *> Res;
4560 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4562 // Not found as a standard register?
4564 unsigned Size = Constraint.size();
4565 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4566 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4568 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4569 if (!Failed && RegNo >= 0 && RegNo <= 31) {
4570 // v0 - v31 are aliases of q0 - q31.
4571 // By default we'll emit v0-v31 for this unless there's a modifier where
4572 // we'll emit the correct register as well.
4573 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4574 Res.second = &AArch64::FPR128RegClass;
4582 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4583 /// vector. If it is invalid, don't add anything to Ops.
4584 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4585 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4586 SelectionDAG &DAG) const {
4589 // Currently only support length 1 constraints.
4590 if (Constraint.length() != 1)
4593 char ConstraintLetter = Constraint[0];
4594 switch (ConstraintLetter) {
4598 // This set of constraints deal with valid constants for various instructions.
4599 // Validate and return a target constant for them if we can.
4601 // 'z' maps to xzr or wzr so it needs an input of 0.
4602 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4603 if (!C || C->getZExtValue() != 0)
4606 if (Op.getValueType() == MVT::i64)
4607 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4609 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4619 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4623 // Grab the value and do some validation.
4624 uint64_t CVal = C->getZExtValue();
4625 switch (ConstraintLetter) {
4626 // The I constraint applies only to simple ADD or SUB immediate operands:
4627 // i.e. 0 to 4095 with optional shift by 12
4628 // The J constraint applies only to ADD or SUB immediates that would be
4629 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4630 // instruction [or vice versa], in other words -1 to -4095 with optional
4631 // left shift by 12.
4633 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4637 uint64_t NVal = -C->getSExtValue();
4638 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4639 CVal = C->getSExtValue();
4644 // The K and L constraints apply *only* to logical immediates, including
4645 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4646 // been removed and MOV should be used). So these constraints have to
4647 // distinguish between bit patterns that are valid 32-bit or 64-bit
4648 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4649 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4652 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4656 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4659 // The M and N constraints are a superset of K and L respectively, for use
4660 // with the MOV (immediate) alias. As well as the logical immediates they
4661 // also match 32 or 64-bit immediates that can be loaded either using a
4662 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4663 // (M) or 64-bit 0x1234000000000000 (N) etc.
4664 // As a note some of this code is liberally stolen from the asm parser.
4666 if (!isUInt<32>(CVal))
4668 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4670 if ((CVal & 0xFFFF) == CVal)
4672 if ((CVal & 0xFFFF0000ULL) == CVal)
4674 uint64_t NCVal = ~(uint32_t)CVal;
4675 if ((NCVal & 0xFFFFULL) == NCVal)
4677 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4682 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4684 if ((CVal & 0xFFFFULL) == CVal)
4686 if ((CVal & 0xFFFF0000ULL) == CVal)
4688 if ((CVal & 0xFFFF00000000ULL) == CVal)
4690 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4692 uint64_t NCVal = ~CVal;
4693 if ((NCVal & 0xFFFFULL) == NCVal)
4695 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4697 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4699 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4707 // All assembler immediates are 64-bit integers.
4708 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4712 if (Result.getNode()) {
4713 Ops.push_back(Result);
4717 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4720 //===----------------------------------------------------------------------===//
4721 // AArch64 Advanced SIMD Support
4722 //===----------------------------------------------------------------------===//
4724 /// WidenVector - Given a value in the V64 register class, produce the
4725 /// equivalent value in the V128 register class.
4726 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4727 EVT VT = V64Reg.getValueType();
4728 unsigned NarrowSize = VT.getVectorNumElements();
4729 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4730 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4733 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4734 V64Reg, DAG.getConstant(0, DL, MVT::i32));
4737 /// getExtFactor - Determine the adjustment factor for the position when
4738 /// generating an "extract from vector registers" instruction.
4739 static unsigned getExtFactor(SDValue &V) {
4740 EVT EltType = V.getValueType().getVectorElementType();
4741 return EltType.getSizeInBits() / 8;
4744 /// NarrowVector - Given a value in the V128 register class, produce the
4745 /// equivalent value in the V64 register class.
4746 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4747 EVT VT = V128Reg.getValueType();
4748 unsigned WideSize = VT.getVectorNumElements();
4749 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4750 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4753 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4756 // Gather data to see if the operation can be modelled as a
4757 // shuffle in combination with VEXTs.
4758 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4759 SelectionDAG &DAG) const {
4760 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4762 EVT VT = Op.getValueType();
4763 unsigned NumElts = VT.getVectorNumElements();
4765 struct ShuffleSourceInfo {
4770 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4771 // be compatible with the shuffle we intend to construct. As a result
4772 // ShuffleVec will be some sliding window into the original Vec.
4775 // Code should guarantee that element i in Vec starts at element "WindowBase
4776 // + i * WindowScale in ShuffleVec".
4780 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4781 ShuffleSourceInfo(SDValue Vec)
4782 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4786 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4788 SmallVector<ShuffleSourceInfo, 2> Sources;
4789 for (unsigned i = 0; i < NumElts; ++i) {
4790 SDValue V = Op.getOperand(i);
4791 if (V.getOpcode() == ISD::UNDEF)
4793 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4794 // A shuffle can only come from building a vector from various
4795 // elements of other vectors.
4799 // Add this element source to the list if it's not already there.
4800 SDValue SourceVec = V.getOperand(0);
4801 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4802 if (Source == Sources.end())
4803 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4805 // Update the minimum and maximum lane number seen.
4806 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4807 Source->MinElt = std::min(Source->MinElt, EltNo);
4808 Source->MaxElt = std::max(Source->MaxElt, EltNo);
4811 // Currently only do something sane when at most two source vectors
4813 if (Sources.size() > 2)
4816 // Find out the smallest element size among result and two sources, and use
4817 // it as element size to build the shuffle_vector.
4818 EVT SmallestEltTy = VT.getVectorElementType();
4819 for (auto &Source : Sources) {
4820 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4821 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4822 SmallestEltTy = SrcEltTy;
4825 unsigned ResMultiplier =
4826 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4827 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4828 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4830 // If the source vector is too wide or too narrow, we may nevertheless be able
4831 // to construct a compatible shuffle either by concatenating it with UNDEF or
4832 // extracting a suitable range of elements.
4833 for (auto &Src : Sources) {
4834 EVT SrcVT = Src.ShuffleVec.getValueType();
4836 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4839 // This stage of the search produces a source with the same element type as
4840 // the original, but with a total width matching the BUILD_VECTOR output.
4841 EVT EltVT = SrcVT.getVectorElementType();
4842 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4843 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4845 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4846 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4847 // We can pad out the smaller vector for free, so if it's part of a
4850 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4851 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4855 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4857 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4858 // Span too large for a VEXT to cope
4862 if (Src.MinElt >= NumSrcElts) {
4863 // The extraction can just take the second half
4865 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4866 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4867 Src.WindowBase = -NumSrcElts;
4868 } else if (Src.MaxElt < NumSrcElts) {
4869 // The extraction can just take the first half
4871 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4872 DAG.getConstant(0, dl, MVT::i64));
4874 // An actual VEXT is needed
4876 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4877 DAG.getConstant(0, dl, MVT::i64));
4879 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4880 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4881 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4883 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4885 DAG.getConstant(Imm, dl, MVT::i32));
4886 Src.WindowBase = -Src.MinElt;
4890 // Another possible incompatibility occurs from the vector element types. We
4891 // can fix this by bitcasting the source vectors to the same type we intend
4893 for (auto &Src : Sources) {
4894 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4895 if (SrcEltTy == SmallestEltTy)
4897 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4898 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4899 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4900 Src.WindowBase *= Src.WindowScale;
4903 // Final sanity check before we try to actually produce a shuffle.
4905 for (auto Src : Sources)
4906 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4909 // The stars all align, our next step is to produce the mask for the shuffle.
4910 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4911 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4912 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4913 SDValue Entry = Op.getOperand(i);
4914 if (Entry.getOpcode() == ISD::UNDEF)
4917 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4918 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4920 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4921 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4923 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4924 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4925 VT.getVectorElementType().getSizeInBits());
4926 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4928 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4929 // starting at the appropriate offset.
4930 int *LaneMask = &Mask[i * ResMultiplier];
4932 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4933 ExtractBase += NumElts * (Src - Sources.begin());
4934 for (int j = 0; j < LanesDefined; ++j)
4935 LaneMask[j] = ExtractBase + j;
4938 // Final check before we try to produce nonsense...
4939 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4942 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4943 for (unsigned i = 0; i < Sources.size(); ++i)
4944 ShuffleOps[i] = Sources[i].ShuffleVec;
4946 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4947 ShuffleOps[1], &Mask[0]);
4948 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4951 // check if an EXT instruction can handle the shuffle mask when the
4952 // vector sources of the shuffle are the same.
4953 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4954 unsigned NumElts = VT.getVectorNumElements();
4956 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4962 // If this is a VEXT shuffle, the immediate value is the index of the first
4963 // element. The other shuffle indices must be the successive elements after
4965 unsigned ExpectedElt = Imm;
4966 for (unsigned i = 1; i < NumElts; ++i) {
4967 // Increment the expected index. If it wraps around, just follow it
4968 // back to index zero and keep going.
4970 if (ExpectedElt == NumElts)
4974 continue; // ignore UNDEF indices
4975 if (ExpectedElt != static_cast<unsigned>(M[i]))
4982 // check if an EXT instruction can handle the shuffle mask when the
4983 // vector sources of the shuffle are different.
4984 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4986 // Look for the first non-undef element.
4987 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4988 [](int Elt) {return Elt >= 0;});
4990 // Benefit form APInt to handle overflow when calculating expected element.
4991 unsigned NumElts = VT.getVectorNumElements();
4992 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4993 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4994 // The following shuffle indices must be the successive elements after the
4995 // first real element.
4996 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4997 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4998 if (FirstWrongElt != M.end())
5001 // The index of an EXT is the first element if it is not UNDEF.
5002 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5003 // value of the first element. E.g.
5004 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5005 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5006 // ExpectedElt is the last mask index plus 1.
5007 Imm = ExpectedElt.getZExtValue();
5009 // There are two difference cases requiring to reverse input vectors.
5010 // For example, for vector <4 x i32> we have the following cases,
5011 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5012 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5013 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5014 // to reverse two input vectors.
5023 /// isREVMask - Check if a vector shuffle corresponds to a REV
5024 /// instruction with the specified blocksize. (The order of the elements
5025 /// within each block of the vector is reversed.)
5026 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5027 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5028 "Only possible block sizes for REV are: 16, 32, 64");
5030 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5034 unsigned NumElts = VT.getVectorNumElements();
5035 unsigned BlockElts = M[0] + 1;
5036 // If the first shuffle index is UNDEF, be optimistic.
5038 BlockElts = BlockSize / EltSz;
5040 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5043 for (unsigned i = 0; i < NumElts; ++i) {
5045 continue; // ignore UNDEF indices
5046 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5053 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5054 unsigned NumElts = VT.getVectorNumElements();
5055 WhichResult = (M[0] == 0 ? 0 : 1);
5056 unsigned Idx = WhichResult * NumElts / 2;
5057 for (unsigned i = 0; i != NumElts; i += 2) {
5058 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5059 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5067 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5068 unsigned NumElts = VT.getVectorNumElements();
5069 WhichResult = (M[0] == 0 ? 0 : 1);
5070 for (unsigned i = 0; i != NumElts; ++i) {
5072 continue; // ignore UNDEF indices
5073 if ((unsigned)M[i] != 2 * i + WhichResult)
5080 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5081 unsigned NumElts = VT.getVectorNumElements();
5082 WhichResult = (M[0] == 0 ? 0 : 1);
5083 for (unsigned i = 0; i < NumElts; i += 2) {
5084 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5085 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5091 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5092 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5093 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5094 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5095 unsigned NumElts = VT.getVectorNumElements();
5096 WhichResult = (M[0] == 0 ? 0 : 1);
5097 unsigned Idx = WhichResult * NumElts / 2;
5098 for (unsigned i = 0; i != NumElts; i += 2) {
5099 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5100 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5108 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5109 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5110 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5111 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5112 unsigned Half = VT.getVectorNumElements() / 2;
5113 WhichResult = (M[0] == 0 ? 0 : 1);
5114 for (unsigned j = 0; j != 2; ++j) {
5115 unsigned Idx = WhichResult;
5116 for (unsigned i = 0; i != Half; ++i) {
5117 int MIdx = M[i + j * Half];
5118 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5127 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5128 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5129 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5130 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5131 unsigned NumElts = VT.getVectorNumElements();
5132 WhichResult = (M[0] == 0 ? 0 : 1);
5133 for (unsigned i = 0; i < NumElts; i += 2) {
5134 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5135 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5141 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5142 bool &DstIsLeft, int &Anomaly) {
5143 if (M.size() != static_cast<size_t>(NumInputElements))
5146 int NumLHSMatch = 0, NumRHSMatch = 0;
5147 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5149 for (int i = 0; i < NumInputElements; ++i) {
5159 LastLHSMismatch = i;
5161 if (M[i] == i + NumInputElements)
5164 LastRHSMismatch = i;
5167 if (NumLHSMatch == NumInputElements - 1) {
5169 Anomaly = LastLHSMismatch;
5171 } else if (NumRHSMatch == NumInputElements - 1) {
5173 Anomaly = LastRHSMismatch;
5180 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5181 if (VT.getSizeInBits() != 128)
5184 unsigned NumElts = VT.getVectorNumElements();
5186 for (int I = 0, E = NumElts / 2; I != E; I++) {
5191 int Offset = NumElts / 2;
5192 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5193 if (Mask[I] != I + SplitLHS * Offset)
5200 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5202 EVT VT = Op.getValueType();
5203 SDValue V0 = Op.getOperand(0);
5204 SDValue V1 = Op.getOperand(1);
5205 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5207 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5208 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5211 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5213 if (!isConcatMask(Mask, VT, SplitV0))
5216 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5217 VT.getVectorNumElements() / 2);
5219 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5220 DAG.getConstant(0, DL, MVT::i64));
5222 if (V1.getValueType().getSizeInBits() == 128) {
5223 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5224 DAG.getConstant(0, DL, MVT::i64));
5226 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5229 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5230 /// the specified operations to build the shuffle.
5231 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5232 SDValue RHS, SelectionDAG &DAG,
5234 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5235 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5236 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5239 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5248 OP_VUZPL, // VUZP, left result
5249 OP_VUZPR, // VUZP, right result
5250 OP_VZIPL, // VZIP, left result
5251 OP_VZIPR, // VZIP, right result
5252 OP_VTRNL, // VTRN, left result
5253 OP_VTRNR // VTRN, right result
5256 if (OpNum == OP_COPY) {
5257 if (LHSID == (1 * 9 + 2) * 9 + 3)
5259 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5263 SDValue OpLHS, OpRHS;
5264 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5265 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5266 EVT VT = OpLHS.getValueType();
5270 llvm_unreachable("Unknown shuffle opcode!");
5272 // VREV divides the vector in half and swaps within the half.
5273 if (VT.getVectorElementType() == MVT::i32 ||
5274 VT.getVectorElementType() == MVT::f32)
5275 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5276 // vrev <4 x i16> -> REV32
5277 if (VT.getVectorElementType() == MVT::i16 ||
5278 VT.getVectorElementType() == MVT::f16)
5279 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5280 // vrev <4 x i8> -> REV16
5281 assert(VT.getVectorElementType() == MVT::i8);
5282 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5287 EVT EltTy = VT.getVectorElementType();
5289 if (EltTy == MVT::i8)
5290 Opcode = AArch64ISD::DUPLANE8;
5291 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5292 Opcode = AArch64ISD::DUPLANE16;
5293 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5294 Opcode = AArch64ISD::DUPLANE32;
5295 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5296 Opcode = AArch64ISD::DUPLANE64;
5298 llvm_unreachable("Invalid vector element type?");
5300 if (VT.getSizeInBits() == 64)
5301 OpLHS = WidenVector(OpLHS, DAG);
5302 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5303 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5308 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5309 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5310 DAG.getConstant(Imm, dl, MVT::i32));
5313 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5316 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5319 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5322 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5325 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5328 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5333 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5334 SelectionDAG &DAG) {
5335 // Check to see if we can use the TBL instruction.
5336 SDValue V1 = Op.getOperand(0);
5337 SDValue V2 = Op.getOperand(1);
5340 EVT EltVT = Op.getValueType().getVectorElementType();
5341 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5343 SmallVector<SDValue, 8> TBLMask;
5344 for (int Val : ShuffleMask) {
5345 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5346 unsigned Offset = Byte + Val * BytesPerElt;
5347 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5351 MVT IndexVT = MVT::v8i8;
5352 unsigned IndexLen = 8;
5353 if (Op.getValueType().getSizeInBits() == 128) {
5354 IndexVT = MVT::v16i8;
5358 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5359 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5362 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5364 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5365 Shuffle = DAG.getNode(
5366 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5367 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5368 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5369 makeArrayRef(TBLMask.data(), IndexLen)));
5371 if (IndexLen == 8) {
5372 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5373 Shuffle = DAG.getNode(
5374 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5375 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5376 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5377 makeArrayRef(TBLMask.data(), IndexLen)));
5379 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5380 // cannot currently represent the register constraints on the input
5382 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5383 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5384 // &TBLMask[0], IndexLen));
5385 Shuffle = DAG.getNode(
5386 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5387 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5389 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5390 makeArrayRef(TBLMask.data(), IndexLen)));
5393 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5396 static unsigned getDUPLANEOp(EVT EltType) {
5397 if (EltType == MVT::i8)
5398 return AArch64ISD::DUPLANE8;
5399 if (EltType == MVT::i16 || EltType == MVT::f16)
5400 return AArch64ISD::DUPLANE16;
5401 if (EltType == MVT::i32 || EltType == MVT::f32)
5402 return AArch64ISD::DUPLANE32;
5403 if (EltType == MVT::i64 || EltType == MVT::f64)
5404 return AArch64ISD::DUPLANE64;
5406 llvm_unreachable("Invalid vector element type?");
5409 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5410 SelectionDAG &DAG) const {
5412 EVT VT = Op.getValueType();
5414 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5416 // Convert shuffles that are directly supported on NEON to target-specific
5417 // DAG nodes, instead of keeping them as shuffles and matching them again
5418 // during code selection. This is more efficient and avoids the possibility
5419 // of inconsistencies between legalization and selection.
5420 ArrayRef<int> ShuffleMask = SVN->getMask();
5422 SDValue V1 = Op.getOperand(0);
5423 SDValue V2 = Op.getOperand(1);
5425 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5426 V1.getValueType().getSimpleVT())) {
5427 int Lane = SVN->getSplatIndex();
5428 // If this is undef splat, generate it via "just" vdup, if possible.
5432 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5433 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5435 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5436 // constant. If so, we can just reference the lane's definition directly.
5437 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5438 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5439 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5441 // Otherwise, duplicate from the lane of the input vector.
5442 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5444 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5445 // to make a vector of the same size as this SHUFFLE. We can ignore the
5446 // extract entirely, and canonicalise the concat using WidenVector.
5447 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5448 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5449 V1 = V1.getOperand(0);
5450 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5451 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5452 Lane -= Idx * VT.getVectorNumElements() / 2;
5453 V1 = WidenVector(V1.getOperand(Idx), DAG);
5454 } else if (VT.getSizeInBits() == 64)
5455 V1 = WidenVector(V1, DAG);
5457 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5460 if (isREVMask(ShuffleMask, VT, 64))
5461 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5462 if (isREVMask(ShuffleMask, VT, 32))
5463 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5464 if (isREVMask(ShuffleMask, VT, 16))
5465 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5467 bool ReverseEXT = false;
5469 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5472 Imm *= getExtFactor(V1);
5473 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5474 DAG.getConstant(Imm, dl, MVT::i32));
5475 } else if (V2->getOpcode() == ISD::UNDEF &&
5476 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5477 Imm *= getExtFactor(V1);
5478 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5479 DAG.getConstant(Imm, dl, MVT::i32));
5482 unsigned WhichResult;
5483 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5484 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5485 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5487 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5488 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5489 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5491 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5492 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5493 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5496 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5497 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5498 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5500 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5501 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5502 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5504 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5505 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5506 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5509 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5510 if (Concat.getNode())
5515 int NumInputElements = V1.getValueType().getVectorNumElements();
5516 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5517 SDValue DstVec = DstIsLeft ? V1 : V2;
5518 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5520 SDValue SrcVec = V1;
5521 int SrcLane = ShuffleMask[Anomaly];
5522 if (SrcLane >= NumInputElements) {
5524 SrcLane -= VT.getVectorNumElements();
5526 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5528 EVT ScalarVT = VT.getVectorElementType();
5530 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5531 ScalarVT = MVT::i32;
5534 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5535 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5539 // If the shuffle is not directly supported and it has 4 elements, use
5540 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5541 unsigned NumElts = VT.getVectorNumElements();
5543 unsigned PFIndexes[4];
5544 for (unsigned i = 0; i != 4; ++i) {
5545 if (ShuffleMask[i] < 0)
5548 PFIndexes[i] = ShuffleMask[i];
5551 // Compute the index in the perfect shuffle table.
5552 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5553 PFIndexes[2] * 9 + PFIndexes[3];
5554 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5555 unsigned Cost = (PFEntry >> 30);
5558 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5561 return GenerateTBL(Op, ShuffleMask, DAG);
5564 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5566 EVT VT = BVN->getValueType(0);
5567 APInt SplatBits, SplatUndef;
5568 unsigned SplatBitSize;
5570 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5571 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5573 for (unsigned i = 0; i < NumSplats; ++i) {
5574 CnstBits <<= SplatBitSize;
5575 UndefBits <<= SplatBitSize;
5576 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5577 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5586 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5587 SelectionDAG &DAG) const {
5588 BuildVectorSDNode *BVN =
5589 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5590 SDValue LHS = Op.getOperand(0);
5592 EVT VT = Op.getValueType();
5597 APInt CnstBits(VT.getSizeInBits(), 0);
5598 APInt UndefBits(VT.getSizeInBits(), 0);
5599 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5600 // We only have BIC vector immediate instruction, which is and-not.
5601 CnstBits = ~CnstBits;
5603 // We make use of a little bit of goto ickiness in order to avoid having to
5604 // duplicate the immediate matching logic for the undef toggled case.
5605 bool SecondTry = false;
5608 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5609 CnstBits = CnstBits.zextOrTrunc(64);
5610 uint64_t CnstVal = CnstBits.getZExtValue();
5612 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5613 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5614 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5615 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5616 DAG.getConstant(CnstVal, dl, MVT::i32),
5617 DAG.getConstant(0, dl, MVT::i32));
5618 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5621 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5622 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5623 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5624 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5625 DAG.getConstant(CnstVal, dl, MVT::i32),
5626 DAG.getConstant(8, dl, MVT::i32));
5627 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5630 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5631 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5632 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5633 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5634 DAG.getConstant(CnstVal, dl, MVT::i32),
5635 DAG.getConstant(16, dl, MVT::i32));
5636 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5639 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5640 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5641 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5642 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5643 DAG.getConstant(CnstVal, dl, MVT::i32),
5644 DAG.getConstant(24, dl, MVT::i32));
5645 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5648 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5649 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5650 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5651 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5652 DAG.getConstant(CnstVal, dl, MVT::i32),
5653 DAG.getConstant(0, dl, MVT::i32));
5654 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5657 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5658 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5659 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5660 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5661 DAG.getConstant(CnstVal, dl, MVT::i32),
5662 DAG.getConstant(8, dl, MVT::i32));
5663 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5670 CnstBits = ~UndefBits;
5674 // We can always fall back to a non-immediate AND.
5679 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5680 // consists of only the same constant int value, returned in reference arg
5682 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5683 uint64_t &ConstVal) {
5684 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5687 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5690 EVT VT = Bvec->getValueType(0);
5691 unsigned NumElts = VT.getVectorNumElements();
5692 for (unsigned i = 1; i < NumElts; ++i)
5693 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5695 ConstVal = FirstElt->getZExtValue();
5699 static unsigned getIntrinsicID(const SDNode *N) {
5700 unsigned Opcode = N->getOpcode();
5703 return Intrinsic::not_intrinsic;
5704 case ISD::INTRINSIC_WO_CHAIN: {
5705 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5706 if (IID < Intrinsic::num_intrinsics)
5708 return Intrinsic::not_intrinsic;
5713 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5714 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5715 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5716 // Also, logical shift right -> sri, with the same structure.
5717 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5718 EVT VT = N->getValueType(0);
5725 // Is the first op an AND?
5726 const SDValue And = N->getOperand(0);
5727 if (And.getOpcode() != ISD::AND)
5730 // Is the second op an shl or lshr?
5731 SDValue Shift = N->getOperand(1);
5732 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5733 // or AArch64ISD::VLSHR vector, #shift
5734 unsigned ShiftOpc = Shift.getOpcode();
5735 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5737 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5739 // Is the shift amount constant?
5740 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5744 // Is the and mask vector all constant?
5746 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5749 // Is C1 == ~C2, taking into account how much one can shift elements of a
5751 uint64_t C2 = C2node->getZExtValue();
5752 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5753 if (C2 > ElemSizeInBits)
5755 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5756 if ((C1 & ElemMask) != (~C2 & ElemMask))
5759 SDValue X = And.getOperand(0);
5760 SDValue Y = Shift.getOperand(0);
5763 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5765 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5766 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5767 Shift.getOperand(1));
5769 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5770 DEBUG(N->dump(&DAG));
5771 DEBUG(dbgs() << "into: \n");
5772 DEBUG(ResultSLI->dump(&DAG));
5778 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5779 SelectionDAG &DAG) const {
5780 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5781 if (EnableAArch64SlrGeneration) {
5782 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5787 BuildVectorSDNode *BVN =
5788 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5789 SDValue LHS = Op.getOperand(1);
5791 EVT VT = Op.getValueType();
5793 // OR commutes, so try swapping the operands.
5795 LHS = Op.getOperand(0);
5796 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5801 APInt CnstBits(VT.getSizeInBits(), 0);
5802 APInt UndefBits(VT.getSizeInBits(), 0);
5803 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5804 // We make use of a little bit of goto ickiness in order to avoid having to
5805 // duplicate the immediate matching logic for the undef toggled case.
5806 bool SecondTry = false;
5809 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5810 CnstBits = CnstBits.zextOrTrunc(64);
5811 uint64_t CnstVal = CnstBits.getZExtValue();
5813 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5814 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5815 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5816 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5817 DAG.getConstant(CnstVal, dl, MVT::i32),
5818 DAG.getConstant(0, dl, MVT::i32));
5819 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5822 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5823 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5824 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5825 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5826 DAG.getConstant(CnstVal, dl, MVT::i32),
5827 DAG.getConstant(8, dl, MVT::i32));
5828 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5831 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5832 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5833 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5834 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5835 DAG.getConstant(CnstVal, dl, MVT::i32),
5836 DAG.getConstant(16, dl, MVT::i32));
5837 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5840 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5841 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5842 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5843 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5844 DAG.getConstant(CnstVal, dl, MVT::i32),
5845 DAG.getConstant(24, dl, MVT::i32));
5846 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5849 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5850 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5851 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5852 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5853 DAG.getConstant(CnstVal, dl, MVT::i32),
5854 DAG.getConstant(0, dl, MVT::i32));
5855 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5858 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5859 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5860 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5861 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5862 DAG.getConstant(CnstVal, dl, MVT::i32),
5863 DAG.getConstant(8, dl, MVT::i32));
5864 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5871 CnstBits = UndefBits;
5875 // We can always fall back to a non-immediate OR.
5880 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5881 // be truncated to fit element width.
5882 static SDValue NormalizeBuildVector(SDValue Op,
5883 SelectionDAG &DAG) {
5884 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5886 EVT VT = Op.getValueType();
5887 EVT EltTy= VT.getVectorElementType();
5889 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5892 SmallVector<SDValue, 16> Ops;
5893 for (SDValue Lane : Op->ops()) {
5894 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5895 APInt LowBits(EltTy.getSizeInBits(),
5896 CstLane->getZExtValue());
5897 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5899 Ops.push_back(Lane);
5901 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5904 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5905 SelectionDAG &DAG) const {
5907 EVT VT = Op.getValueType();
5908 Op = NormalizeBuildVector(Op, DAG);
5909 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5911 APInt CnstBits(VT.getSizeInBits(), 0);
5912 APInt UndefBits(VT.getSizeInBits(), 0);
5913 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5914 // We make use of a little bit of goto ickiness in order to avoid having to
5915 // duplicate the immediate matching logic for the undef toggled case.
5916 bool SecondTry = false;
5919 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5920 CnstBits = CnstBits.zextOrTrunc(64);
5921 uint64_t CnstVal = CnstBits.getZExtValue();
5923 // Certain magic vector constants (used to express things like NOT
5924 // and NEG) are passed through unmodified. This allows codegen patterns
5925 // for these operations to match. Special-purpose patterns will lower
5926 // these immediates to MOVIs if it proves necessary.
5927 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5930 // The many faces of MOVI...
5931 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5932 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5933 if (VT.getSizeInBits() == 128) {
5934 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5935 DAG.getConstant(CnstVal, dl, MVT::i32));
5936 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5939 // Support the V64 version via subregister insertion.
5940 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5941 DAG.getConstant(CnstVal, dl, MVT::i32));
5942 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5945 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5946 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5947 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5948 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5949 DAG.getConstant(CnstVal, dl, MVT::i32),
5950 DAG.getConstant(0, dl, MVT::i32));
5951 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5954 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5955 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5956 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5957 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5958 DAG.getConstant(CnstVal, dl, MVT::i32),
5959 DAG.getConstant(8, dl, MVT::i32));
5960 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5963 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5964 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5965 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5966 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5967 DAG.getConstant(CnstVal, dl, MVT::i32),
5968 DAG.getConstant(16, dl, MVT::i32));
5969 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5972 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5973 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5974 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5975 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5976 DAG.getConstant(CnstVal, dl, MVT::i32),
5977 DAG.getConstant(24, dl, MVT::i32));
5978 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5981 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5982 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5983 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5984 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5985 DAG.getConstant(CnstVal, dl, MVT::i32),
5986 DAG.getConstant(0, dl, MVT::i32));
5987 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5990 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5991 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5992 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5993 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5994 DAG.getConstant(CnstVal, dl, MVT::i32),
5995 DAG.getConstant(8, dl, MVT::i32));
5996 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5999 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6000 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6001 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6002 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6003 DAG.getConstant(CnstVal, dl, MVT::i32),
6004 DAG.getConstant(264, dl, MVT::i32));
6005 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6008 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6009 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6010 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6011 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6012 DAG.getConstant(CnstVal, dl, MVT::i32),
6013 DAG.getConstant(272, dl, MVT::i32));
6014 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6017 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6018 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6019 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6020 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6021 DAG.getConstant(CnstVal, dl, MVT::i32));
6022 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6025 // The few faces of FMOV...
6026 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6027 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6028 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6029 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6030 DAG.getConstant(CnstVal, dl, MVT::i32));
6031 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6034 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6035 VT.getSizeInBits() == 128) {
6036 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6037 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6038 DAG.getConstant(CnstVal, dl, MVT::i32));
6039 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6042 // The many faces of MVNI...
6044 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6045 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6046 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6047 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6048 DAG.getConstant(CnstVal, dl, MVT::i32),
6049 DAG.getConstant(0, dl, MVT::i32));
6050 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6053 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6054 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6055 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6056 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6057 DAG.getConstant(CnstVal, dl, MVT::i32),
6058 DAG.getConstant(8, dl, MVT::i32));
6059 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6062 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6063 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6064 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6065 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6066 DAG.getConstant(CnstVal, dl, MVT::i32),
6067 DAG.getConstant(16, dl, MVT::i32));
6068 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6071 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6072 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6073 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6074 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6075 DAG.getConstant(CnstVal, dl, MVT::i32),
6076 DAG.getConstant(24, dl, MVT::i32));
6077 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6080 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6081 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6082 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6083 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6084 DAG.getConstant(CnstVal, dl, MVT::i32),
6085 DAG.getConstant(0, dl, MVT::i32));
6086 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6089 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6090 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6091 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6092 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6093 DAG.getConstant(CnstVal, dl, MVT::i32),
6094 DAG.getConstant(8, dl, MVT::i32));
6095 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6098 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6099 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6100 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6101 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6102 DAG.getConstant(CnstVal, dl, MVT::i32),
6103 DAG.getConstant(264, dl, MVT::i32));
6104 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6107 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6108 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6109 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6110 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6111 DAG.getConstant(CnstVal, dl, MVT::i32),
6112 DAG.getConstant(272, dl, MVT::i32));
6113 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6120 CnstBits = UndefBits;
6125 // Scan through the operands to find some interesting properties we can
6127 // 1) If only one value is used, we can use a DUP, or
6128 // 2) if only the low element is not undef, we can just insert that, or
6129 // 3) if only one constant value is used (w/ some non-constant lanes),
6130 // we can splat the constant value into the whole vector then fill
6131 // in the non-constant lanes.
6132 // 4) FIXME: If different constant values are used, but we can intelligently
6133 // select the values we'll be overwriting for the non-constant
6134 // lanes such that we can directly materialize the vector
6135 // some other way (MOVI, e.g.), we can be sneaky.
6136 unsigned NumElts = VT.getVectorNumElements();
6137 bool isOnlyLowElement = true;
6138 bool usesOnlyOneValue = true;
6139 bool usesOnlyOneConstantValue = true;
6140 bool isConstant = true;
6141 unsigned NumConstantLanes = 0;
6143 SDValue ConstantValue;
6144 for (unsigned i = 0; i < NumElts; ++i) {
6145 SDValue V = Op.getOperand(i);
6146 if (V.getOpcode() == ISD::UNDEF)
6149 isOnlyLowElement = false;
6150 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6153 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6155 if (!ConstantValue.getNode())
6157 else if (ConstantValue != V)
6158 usesOnlyOneConstantValue = false;
6161 if (!Value.getNode())
6163 else if (V != Value)
6164 usesOnlyOneValue = false;
6167 if (!Value.getNode())
6168 return DAG.getUNDEF(VT);
6170 if (isOnlyLowElement)
6171 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6173 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6174 // i32 and try again.
6175 if (usesOnlyOneValue) {
6177 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6178 Value.getValueType() != VT)
6179 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6181 // This is actually a DUPLANExx operation, which keeps everything vectory.
6183 // DUPLANE works on 128-bit vectors, widen it if necessary.
6184 SDValue Lane = Value.getOperand(1);
6185 Value = Value.getOperand(0);
6186 if (Value.getValueType().getSizeInBits() == 64)
6187 Value = WidenVector(Value, DAG);
6189 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6190 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6193 if (VT.getVectorElementType().isFloatingPoint()) {
6194 SmallVector<SDValue, 8> Ops;
6195 EVT EltTy = VT.getVectorElementType();
6196 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6197 "Unsupported floating-point vector type");
6198 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6199 for (unsigned i = 0; i < NumElts; ++i)
6200 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6201 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6202 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6203 Val = LowerBUILD_VECTOR(Val, DAG);
6205 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6209 // If there was only one constant value used and for more than one lane,
6210 // start by splatting that value, then replace the non-constant lanes. This
6211 // is better than the default, which will perform a separate initialization
6213 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6214 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6215 // Now insert the non-constant lanes.
6216 for (unsigned i = 0; i < NumElts; ++i) {
6217 SDValue V = Op.getOperand(i);
6218 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6219 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6220 // Note that type legalization likely mucked about with the VT of the
6221 // source operand, so we may have to convert it here before inserting.
6222 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6228 // If all elements are constants and the case above didn't get hit, fall back
6229 // to the default expansion, which will generate a load from the constant
6234 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6236 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6240 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6241 // know the default expansion would otherwise fall back on something even
6242 // worse. For a vector with one or two non-undef values, that's
6243 // scalar_to_vector for the elements followed by a shuffle (provided the
6244 // shuffle is valid for the target) and materialization element by element
6245 // on the stack followed by a load for everything else.
6246 if (!isConstant && !usesOnlyOneValue) {
6247 SDValue Vec = DAG.getUNDEF(VT);
6248 SDValue Op0 = Op.getOperand(0);
6249 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6251 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6252 // a) Avoid a RMW dependency on the full vector register, and
6253 // b) Allow the register coalescer to fold away the copy if the
6254 // value is already in an S or D register.
6255 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6256 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6258 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6259 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6260 Vec = SDValue(N, 0);
6263 for (; i < NumElts; ++i) {
6264 SDValue V = Op.getOperand(i);
6265 if (V.getOpcode() == ISD::UNDEF)
6267 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6268 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6273 // Just use the default expansion. We failed to find a better alternative.
6277 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6278 SelectionDAG &DAG) const {
6279 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6281 // Check for non-constant or out of range lane.
6282 EVT VT = Op.getOperand(0).getValueType();
6283 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6284 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6288 // Insertion/extraction are legal for V128 types.
6289 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6290 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6294 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6295 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6298 // For V64 types, we perform insertion by expanding the value
6299 // to a V128 type and perform the insertion on that.
6301 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6302 EVT WideTy = WideVec.getValueType();
6304 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6305 Op.getOperand(1), Op.getOperand(2));
6306 // Re-narrow the resultant vector.
6307 return NarrowVector(Node, DAG);
6311 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6312 SelectionDAG &DAG) const {
6313 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6315 // Check for non-constant or out of range lane.
6316 EVT VT = Op.getOperand(0).getValueType();
6317 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6318 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6322 // Insertion/extraction are legal for V128 types.
6323 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6324 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6328 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6329 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6332 // For V64 types, we perform extraction by expanding the value
6333 // to a V128 type and perform the extraction on that.
6335 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6336 EVT WideTy = WideVec.getValueType();
6338 EVT ExtrTy = WideTy.getVectorElementType();
6339 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6342 // For extractions, we just return the result directly.
6343 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6347 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6348 SelectionDAG &DAG) const {
6349 EVT VT = Op.getOperand(0).getValueType();
6355 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6358 unsigned Val = Cst->getZExtValue();
6360 unsigned Size = Op.getValueType().getSizeInBits();
6364 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6367 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6370 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6373 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6376 llvm_unreachable("Unexpected vector type in extract_subvector!");
6379 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6381 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6387 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6389 if (VT.getVectorNumElements() == 4 &&
6390 (VT.is128BitVector() || VT.is64BitVector())) {
6391 unsigned PFIndexes[4];
6392 for (unsigned i = 0; i != 4; ++i) {
6396 PFIndexes[i] = M[i];
6399 // Compute the index in the perfect shuffle table.
6400 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6401 PFIndexes[2] * 9 + PFIndexes[3];
6402 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6403 unsigned Cost = (PFEntry >> 30);
6411 unsigned DummyUnsigned;
6413 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6414 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6415 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6416 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6417 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6418 isZIPMask(M, VT, DummyUnsigned) ||
6419 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6420 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6421 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6422 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6423 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6426 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6427 /// operand of a vector shift operation, where all the elements of the
6428 /// build_vector must have the same constant integer value.
6429 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6430 // Ignore bit_converts.
6431 while (Op.getOpcode() == ISD::BITCAST)
6432 Op = Op.getOperand(0);
6433 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6434 APInt SplatBits, SplatUndef;
6435 unsigned SplatBitSize;
6437 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6438 HasAnyUndefs, ElementBits) ||
6439 SplatBitSize > ElementBits)
6441 Cnt = SplatBits.getSExtValue();
6445 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6446 /// operand of a vector shift left operation. That value must be in the range:
6447 /// 0 <= Value < ElementBits for a left shift; or
6448 /// 0 <= Value <= ElementBits for a long left shift.
6449 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6450 assert(VT.isVector() && "vector shift count is not a vector type");
6451 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6452 if (!getVShiftImm(Op, ElementBits, Cnt))
6454 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6457 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6458 /// operand of a vector shift right operation. The value must be in the range:
6459 /// 1 <= Value <= ElementBits for a right shift; or
6460 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6461 assert(VT.isVector() && "vector shift count is not a vector type");
6462 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6463 if (!getVShiftImm(Op, ElementBits, Cnt))
6465 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6468 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6469 SelectionDAG &DAG) const {
6470 EVT VT = Op.getValueType();
6474 if (!Op.getOperand(1).getValueType().isVector())
6476 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6478 switch (Op.getOpcode()) {
6480 llvm_unreachable("unexpected shift opcode");
6483 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6484 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6485 DAG.getConstant(Cnt, DL, MVT::i32));
6486 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6487 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6489 Op.getOperand(0), Op.getOperand(1));
6492 // Right shift immediate
6493 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6495 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6496 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6497 DAG.getConstant(Cnt, DL, MVT::i32));
6500 // Right shift register. Note, there is not a shift right register
6501 // instruction, but the shift left register instruction takes a signed
6502 // value, where negative numbers specify a right shift.
6503 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6504 : Intrinsic::aarch64_neon_ushl;
6505 // negate the shift amount
6506 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6507 SDValue NegShiftLeft =
6508 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6509 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6511 return NegShiftLeft;
6517 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6518 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6519 SDLoc dl, SelectionDAG &DAG) {
6520 EVT SrcVT = LHS.getValueType();
6521 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6522 "function only supposed to emit natural comparisons");
6524 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6525 APInt CnstBits(VT.getSizeInBits(), 0);
6526 APInt UndefBits(VT.getSizeInBits(), 0);
6527 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6528 bool IsZero = IsCnst && (CnstBits == 0);
6530 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6534 case AArch64CC::NE: {
6537 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6539 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6540 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6544 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6545 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6548 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6549 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6552 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6553 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6556 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6557 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6561 // If we ignore NaNs then we can use to the MI implementation.
6565 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6566 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6573 case AArch64CC::NE: {
6576 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6578 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6579 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6583 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6584 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6587 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6588 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6591 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6592 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6595 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6596 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6598 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6600 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6603 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6604 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6606 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6608 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6612 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6613 SelectionDAG &DAG) const {
6614 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6615 SDValue LHS = Op.getOperand(0);
6616 SDValue RHS = Op.getOperand(1);
6617 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6620 if (LHS.getValueType().getVectorElementType().isInteger()) {
6621 assert(LHS.getValueType() == RHS.getValueType());
6622 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6624 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6625 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6628 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6629 LHS.getValueType().getVectorElementType() == MVT::f64);
6631 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6632 // clean. Some of them require two branches to implement.
6633 AArch64CC::CondCode CC1, CC2;
6635 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6637 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6639 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6643 if (CC2 != AArch64CC::AL) {
6645 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6646 if (!Cmp2.getNode())
6649 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6652 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6655 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6660 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6661 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6662 /// specified in the intrinsic calls.
6663 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6665 unsigned Intrinsic) const {
6666 auto &DL = I.getModule()->getDataLayout();
6667 switch (Intrinsic) {
6668 case Intrinsic::aarch64_neon_ld2:
6669 case Intrinsic::aarch64_neon_ld3:
6670 case Intrinsic::aarch64_neon_ld4:
6671 case Intrinsic::aarch64_neon_ld1x2:
6672 case Intrinsic::aarch64_neon_ld1x3:
6673 case Intrinsic::aarch64_neon_ld1x4:
6674 case Intrinsic::aarch64_neon_ld2lane:
6675 case Intrinsic::aarch64_neon_ld3lane:
6676 case Intrinsic::aarch64_neon_ld4lane:
6677 case Intrinsic::aarch64_neon_ld2r:
6678 case Intrinsic::aarch64_neon_ld3r:
6679 case Intrinsic::aarch64_neon_ld4r: {
6680 Info.opc = ISD::INTRINSIC_W_CHAIN;
6681 // Conservatively set memVT to the entire set of vectors loaded.
6682 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6683 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6684 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6687 Info.vol = false; // volatile loads with NEON intrinsics not supported
6688 Info.readMem = true;
6689 Info.writeMem = false;
6692 case Intrinsic::aarch64_neon_st2:
6693 case Intrinsic::aarch64_neon_st3:
6694 case Intrinsic::aarch64_neon_st4:
6695 case Intrinsic::aarch64_neon_st1x2:
6696 case Intrinsic::aarch64_neon_st1x3:
6697 case Intrinsic::aarch64_neon_st1x4:
6698 case Intrinsic::aarch64_neon_st2lane:
6699 case Intrinsic::aarch64_neon_st3lane:
6700 case Intrinsic::aarch64_neon_st4lane: {
6701 Info.opc = ISD::INTRINSIC_VOID;
6702 // Conservatively set memVT to the entire set of vectors stored.
6703 unsigned NumElts = 0;
6704 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6705 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6706 if (!ArgTy->isVectorTy())
6708 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6710 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6711 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6714 Info.vol = false; // volatile stores with NEON intrinsics not supported
6715 Info.readMem = false;
6716 Info.writeMem = true;
6719 case Intrinsic::aarch64_ldaxr:
6720 case Intrinsic::aarch64_ldxr: {
6721 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6722 Info.opc = ISD::INTRINSIC_W_CHAIN;
6723 Info.memVT = MVT::getVT(PtrTy->getElementType());
6724 Info.ptrVal = I.getArgOperand(0);
6726 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6728 Info.readMem = true;
6729 Info.writeMem = false;
6732 case Intrinsic::aarch64_stlxr:
6733 case Intrinsic::aarch64_stxr: {
6734 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6735 Info.opc = ISD::INTRINSIC_W_CHAIN;
6736 Info.memVT = MVT::getVT(PtrTy->getElementType());
6737 Info.ptrVal = I.getArgOperand(1);
6739 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6741 Info.readMem = false;
6742 Info.writeMem = true;
6745 case Intrinsic::aarch64_ldaxp:
6746 case Intrinsic::aarch64_ldxp: {
6747 Info.opc = ISD::INTRINSIC_W_CHAIN;
6748 Info.memVT = MVT::i128;
6749 Info.ptrVal = I.getArgOperand(0);
6753 Info.readMem = true;
6754 Info.writeMem = false;
6757 case Intrinsic::aarch64_stlxp:
6758 case Intrinsic::aarch64_stxp: {
6759 Info.opc = ISD::INTRINSIC_W_CHAIN;
6760 Info.memVT = MVT::i128;
6761 Info.ptrVal = I.getArgOperand(2);
6765 Info.readMem = false;
6766 Info.writeMem = true;
6776 // Truncations from 64-bit GPR to 32-bit GPR is free.
6777 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6778 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6780 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6781 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6782 return NumBits1 > NumBits2;
6784 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6785 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6787 unsigned NumBits1 = VT1.getSizeInBits();
6788 unsigned NumBits2 = VT2.getSizeInBits();
6789 return NumBits1 > NumBits2;
6792 /// Check if it is profitable to hoist instruction in then/else to if.
6793 /// Not profitable if I and it's user can form a FMA instruction
6794 /// because we prefer FMSUB/FMADD.
6795 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6796 if (I->getOpcode() != Instruction::FMul)
6799 if (I->getNumUses() != 1)
6802 Instruction *User = I->user_back();
6805 !(User->getOpcode() == Instruction::FSub ||
6806 User->getOpcode() == Instruction::FAdd))
6809 const TargetOptions &Options = getTargetMachine().Options;
6810 const DataLayout &DL = I->getModule()->getDataLayout();
6811 EVT VT = getValueType(DL, User->getOperand(0)->getType());
6813 if (isFMAFasterThanFMulAndFAdd(VT) &&
6814 isOperationLegalOrCustom(ISD::FMA, VT) &&
6815 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6821 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6823 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6824 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6826 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6827 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6828 return NumBits1 == 32 && NumBits2 == 64;
6830 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6831 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6833 unsigned NumBits1 = VT1.getSizeInBits();
6834 unsigned NumBits2 = VT2.getSizeInBits();
6835 return NumBits1 == 32 && NumBits2 == 64;
6838 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6839 EVT VT1 = Val.getValueType();
6840 if (isZExtFree(VT1, VT2)) {
6844 if (Val.getOpcode() != ISD::LOAD)
6847 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6848 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6849 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6850 VT1.getSizeInBits() <= 32);
6853 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6854 if (isa<FPExtInst>(Ext))
6857 // Vector types are next free.
6858 if (Ext->getType()->isVectorTy())
6861 for (const Use &U : Ext->uses()) {
6862 // The extension is free if we can fold it with a left shift in an
6863 // addressing mode or an arithmetic operation: add, sub, and cmp.
6865 // Is there a shift?
6866 const Instruction *Instr = cast<Instruction>(U.getUser());
6868 // Is this a constant shift?
6869 switch (Instr->getOpcode()) {
6870 case Instruction::Shl:
6871 if (!isa<ConstantInt>(Instr->getOperand(1)))
6874 case Instruction::GetElementPtr: {
6875 gep_type_iterator GTI = gep_type_begin(Instr);
6876 auto &DL = Ext->getModule()->getDataLayout();
6877 std::advance(GTI, U.getOperandNo());
6879 // This extension will end up with a shift because of the scaling factor.
6880 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6881 // Get the shift amount based on the scaling factor:
6882 // log2(sizeof(IdxTy)) - log2(8).
6884 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6885 // Is the constant foldable in the shift of the addressing mode?
6886 // I.e., shift amount is between 1 and 4 inclusive.
6887 if (ShiftAmt == 0 || ShiftAmt > 4)
6891 case Instruction::Trunc:
6892 // Check if this is a noop.
6893 // trunc(sext ty1 to ty2) to ty1.
6894 if (Instr->getType() == Ext->getOperand(0)->getType())
6901 // At this point we can use the bfm family, so this extension is free
6907 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6908 unsigned &RequiredAligment) const {
6909 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6911 // Cyclone supports unaligned accesses.
6912 RequiredAligment = 0;
6913 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6914 return NumBits == 32 || NumBits == 64;
6917 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6918 unsigned &RequiredAligment) const {
6919 if (!LoadedType.isSimple() ||
6920 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6922 // Cyclone supports unaligned accesses.
6923 RequiredAligment = 0;
6924 unsigned NumBits = LoadedType.getSizeInBits();
6925 return NumBits == 32 || NumBits == 64;
6928 /// \brief Lower an interleaved load into a ldN intrinsic.
6930 /// E.g. Lower an interleaved load (Factor = 2):
6931 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6932 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
6933 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
6936 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6937 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6938 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6939 bool AArch64TargetLowering::lowerInterleavedLoad(
6940 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6941 ArrayRef<unsigned> Indices, unsigned Factor) const {
6942 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6943 "Invalid interleave factor");
6944 assert(!Shuffles.empty() && "Empty shufflevector input");
6945 assert(Shuffles.size() == Indices.size() &&
6946 "Unmatched number of shufflevectors and indices");
6948 const DataLayout &DL = LI->getModule()->getDataLayout();
6950 VectorType *VecTy = Shuffles[0]->getType();
6951 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6953 // Skip illegal vector types.
6954 if (VecSize != 64 && VecSize != 128)
6957 // A pointer vector can not be the return type of the ldN intrinsics. Need to
6958 // load integer vectors first and then convert to pointer vectors.
6959 Type *EltTy = VecTy->getVectorElementType();
6960 if (EltTy->isPointerTy())
6962 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
6964 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6965 Type *Tys[2] = {VecTy, PtrTy};
6966 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6967 Intrinsic::aarch64_neon_ld3,
6968 Intrinsic::aarch64_neon_ld4};
6970 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6972 IRBuilder<> Builder(LI);
6973 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6975 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6977 // Replace uses of each shufflevector with the corresponding vector loaded
6979 for (unsigned i = 0; i < Shuffles.size(); i++) {
6980 ShuffleVectorInst *SVI = Shuffles[i];
6981 unsigned Index = Indices[i];
6983 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
6985 // Convert the integer vector to pointer vector if the element is pointer.
6986 if (EltTy->isPointerTy())
6987 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
6989 SVI->replaceAllUsesWith(SubVec);
6995 /// \brief Get a mask consisting of sequential integers starting from \p Start.
6997 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
6998 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7000 SmallVector<Constant *, 16> Mask;
7001 for (unsigned i = 0; i < NumElts; i++)
7002 Mask.push_back(Builder.getInt32(Start + i));
7004 return ConstantVector::get(Mask);
7007 /// \brief Lower an interleaved store into a stN intrinsic.
7009 /// E.g. Lower an interleaved store (Factor = 3):
7010 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7011 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7012 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7015 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7016 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7017 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7018 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7020 /// Note that the new shufflevectors will be removed and we'll only generate one
7021 /// st3 instruction in CodeGen.
7022 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7023 ShuffleVectorInst *SVI,
7024 unsigned Factor) const {
7025 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7026 "Invalid interleave factor");
7028 VectorType *VecTy = SVI->getType();
7029 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7030 "Invalid interleaved store");
7032 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7033 Type *EltTy = VecTy->getVectorElementType();
7034 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7036 const DataLayout &DL = SI->getModule()->getDataLayout();
7037 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7039 // Skip illegal vector types.
7040 if (SubVecSize != 64 && SubVecSize != 128)
7043 Value *Op0 = SVI->getOperand(0);
7044 Value *Op1 = SVI->getOperand(1);
7045 IRBuilder<> Builder(SI);
7047 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7048 // vectors to integer vectors.
7049 if (EltTy->isPointerTy()) {
7050 Type *IntTy = DL.getIntPtrType(EltTy);
7051 unsigned NumOpElts =
7052 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7054 // Convert to the corresponding integer vector.
7055 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7056 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7057 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7059 SubVecTy = VectorType::get(IntTy, NumSubElts);
7062 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7063 Type *Tys[2] = {SubVecTy, PtrTy};
7064 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7065 Intrinsic::aarch64_neon_st3,
7066 Intrinsic::aarch64_neon_st4};
7068 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7070 SmallVector<Value *, 5> Ops;
7072 // Split the shufflevector operands into sub vectors for the new stN call.
7073 for (unsigned i = 0; i < Factor; i++)
7074 Ops.push_back(Builder.CreateShuffleVector(
7075 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7077 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7078 Builder.CreateCall(StNFunc, Ops);
7082 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7083 unsigned AlignCheck) {
7084 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7085 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7088 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7089 unsigned SrcAlign, bool IsMemset,
7092 MachineFunction &MF) const {
7093 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7094 // instruction to materialize the v2i64 zero and one store (with restrictive
7095 // addressing mode). Just do two i64 store of zero-registers.
7097 const Function *F = MF.getFunction();
7098 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7099 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7100 (memOpAlign(SrcAlign, DstAlign, 16) ||
7101 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7105 (memOpAlign(SrcAlign, DstAlign, 8) ||
7106 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7110 (memOpAlign(SrcAlign, DstAlign, 4) ||
7111 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7117 // 12-bit optionally shifted immediates are legal for adds.
7118 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7119 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7124 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7125 // immediates is the same as for an add or a sub.
7126 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7129 return isLegalAddImmediate(Immed);
7132 /// isLegalAddressingMode - Return true if the addressing mode represented
7133 /// by AM is legal for this target, for a load/store of the specified type.
7134 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7135 const AddrMode &AM, Type *Ty,
7136 unsigned AS) const {
7137 // AArch64 has five basic addressing modes:
7139 // reg + 9-bit signed offset
7140 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7142 // reg + SIZE_IN_BYTES * reg
7144 // No global is ever allowed as a base.
7148 // No reg+reg+imm addressing.
7149 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7152 // check reg + imm case:
7153 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7154 uint64_t NumBytes = 0;
7155 if (Ty->isSized()) {
7156 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7157 NumBytes = NumBits / 8;
7158 if (!isPowerOf2_64(NumBits))
7163 int64_t Offset = AM.BaseOffs;
7165 // 9-bit signed offset
7166 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7169 // 12-bit unsigned offset
7170 unsigned shift = Log2_64(NumBytes);
7171 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7172 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7173 (Offset >> shift) << shift == Offset)
7178 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7180 if (!AM.Scale || AM.Scale == 1 ||
7181 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7186 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7187 const AddrMode &AM, Type *Ty,
7188 unsigned AS) const {
7189 // Scaling factors are not free at all.
7190 // Operands | Rt Latency
7191 // -------------------------------------------
7193 // -------------------------------------------
7194 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7195 // Rt, [Xn, Wm, <extend> #imm] |
7196 if (isLegalAddressingMode(DL, AM, Ty, AS))
7197 // Scale represents reg2 * scale, thus account for 1 if
7198 // it is not equal to 0 or 1.
7199 return AM.Scale != 0 && AM.Scale != 1;
7203 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7204 VT = VT.getScalarType();
7209 switch (VT.getSimpleVT().SimpleTy) {
7221 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7222 // LR is a callee-save register, but we must treat it as clobbered by any call
7223 // site. Hence we include LR in the scratch registers, which are in turn added
7224 // as implicit-defs for stackmaps and patchpoints.
7225 static const MCPhysReg ScratchRegs[] = {
7226 AArch64::X16, AArch64::X17, AArch64::LR, 0
7232 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7233 EVT VT = N->getValueType(0);
7234 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7235 // it with shift to let it be lowered to UBFX.
7236 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7237 isa<ConstantSDNode>(N->getOperand(1))) {
7238 uint64_t TruncMask = N->getConstantOperandVal(1);
7239 if (isMask_64(TruncMask) &&
7240 N->getOperand(0).getOpcode() == ISD::SRL &&
7241 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7247 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7249 assert(Ty->isIntegerTy());
7251 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7255 int64_t Val = Imm.getSExtValue();
7256 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7259 if ((int64_t)Val < 0)
7262 Val &= (1LL << 32) - 1;
7264 unsigned LZ = countLeadingZeros((uint64_t)Val);
7265 unsigned Shift = (63 - LZ) / 16;
7266 // MOVZ is free so return true for one or fewer MOVK.
7270 // Generate SUBS and CSEL for integer abs.
7271 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7272 EVT VT = N->getValueType(0);
7274 SDValue N0 = N->getOperand(0);
7275 SDValue N1 = N->getOperand(1);
7278 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7279 // and change it to SUB and CSEL.
7280 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7281 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7282 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7283 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7284 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7285 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7287 // Generate SUBS & CSEL.
7289 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7290 N0.getOperand(0), DAG.getConstant(0, DL, VT));
7291 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7292 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7293 SDValue(Cmp.getNode(), 1));
7298 // performXorCombine - Attempts to handle integer ABS.
7299 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7300 TargetLowering::DAGCombinerInfo &DCI,
7301 const AArch64Subtarget *Subtarget) {
7302 if (DCI.isBeforeLegalizeOps())
7305 return performIntegerAbsCombine(N, DAG);
7309 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7311 std::vector<SDNode *> *Created) const {
7312 // fold (sdiv X, pow2)
7313 EVT VT = N->getValueType(0);
7314 if ((VT != MVT::i32 && VT != MVT::i64) ||
7315 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7319 SDValue N0 = N->getOperand(0);
7320 unsigned Lg2 = Divisor.countTrailingZeros();
7321 SDValue Zero = DAG.getConstant(0, DL, VT);
7322 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7324 // Add (N0 < 0) ? Pow2 - 1 : 0;
7326 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7327 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7328 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7331 Created->push_back(Cmp.getNode());
7332 Created->push_back(Add.getNode());
7333 Created->push_back(CSel.getNode());
7338 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7340 // If we're dividing by a positive value, we're done. Otherwise, we must
7341 // negate the result.
7342 if (Divisor.isNonNegative())
7346 Created->push_back(SRA.getNode());
7347 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7350 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7351 TargetLowering::DAGCombinerInfo &DCI,
7352 const AArch64Subtarget *Subtarget) {
7353 if (DCI.isBeforeLegalizeOps())
7356 // Multiplication of a power of two plus/minus one can be done more
7357 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7358 // future CPUs have a cheaper MADD instruction, this may need to be
7359 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7360 // 64-bit is 5 cycles, so this is always a win.
7361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7362 APInt Value = C->getAPIntValue();
7363 EVT VT = N->getValueType(0);
7365 if (Value.isNonNegative()) {
7366 // (mul x, 2^N + 1) => (add (shl x, N), x)
7367 APInt VM1 = Value - 1;
7368 if (VM1.isPowerOf2()) {
7369 SDValue ShiftedVal =
7370 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7371 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7372 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7375 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7376 APInt VP1 = Value + 1;
7377 if (VP1.isPowerOf2()) {
7378 SDValue ShiftedVal =
7379 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7380 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7381 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7385 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7386 APInt VNP1 = -Value + 1;
7387 if (VNP1.isPowerOf2()) {
7388 SDValue ShiftedVal =
7389 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7390 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7391 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7394 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7395 APInt VNM1 = -Value - 1;
7396 if (VNM1.isPowerOf2()) {
7397 SDValue ShiftedVal =
7398 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7399 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7401 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7402 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7409 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7410 SelectionDAG &DAG) {
7411 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7412 // optimize away operation when it's from a constant.
7414 // The general transformation is:
7415 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7416 // AND(VECTOR_CMP(x,y), constant2)
7417 // constant2 = UNARYOP(constant)
7419 // Early exit if this isn't a vector operation, the operand of the
7420 // unary operation isn't a bitwise AND, or if the sizes of the operations
7422 EVT VT = N->getValueType(0);
7423 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7424 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7425 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7428 // Now check that the other operand of the AND is a constant. We could
7429 // make the transformation for non-constant splats as well, but it's unclear
7430 // that would be a benefit as it would not eliminate any operations, just
7431 // perform one more step in scalar code before moving to the vector unit.
7432 if (BuildVectorSDNode *BV =
7433 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7434 // Bail out if the vector isn't a constant.
7435 if (!BV->isConstant())
7438 // Everything checks out. Build up the new and improved node.
7440 EVT IntVT = BV->getValueType(0);
7441 // Create a new constant of the appropriate type for the transformed
7443 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7444 // The AND node needs bitcasts to/from an integer vector type around it.
7445 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7446 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7447 N->getOperand(0)->getOperand(0), MaskConst);
7448 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7455 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7456 const AArch64Subtarget *Subtarget) {
7457 // First try to optimize away the conversion when it's conditionally from
7458 // a constant. Vectors only.
7459 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7462 EVT VT = N->getValueType(0);
7463 if (VT != MVT::f32 && VT != MVT::f64)
7466 // Only optimize when the source and destination types have the same width.
7467 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7470 // If the result of an integer load is only used by an integer-to-float
7471 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7472 // This eliminates an "integer-to-vector-move UOP and improve throughput.
7473 SDValue N0 = N->getOperand(0);
7474 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7475 // Do not change the width of a volatile load.
7476 !cast<LoadSDNode>(N0)->isVolatile()) {
7477 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7478 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7479 LN0->getPointerInfo(), LN0->isVolatile(),
7480 LN0->isNonTemporal(), LN0->isInvariant(),
7481 LN0->getAlignment());
7483 // Make sure successors of the original load stay after it by updating them
7484 // to use the new Chain.
7485 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7488 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7489 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7495 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7496 /// searches for and classifies those shifts.
7497 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7499 if (N.getOpcode() == ISD::SHL)
7501 else if (N.getOpcode() == ISD::SRL)
7506 if (!isa<ConstantSDNode>(N.getOperand(1)))
7509 ShiftAmount = N->getConstantOperandVal(1);
7510 Src = N->getOperand(0);
7514 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7515 /// registers viewed as a high/low pair. This function looks for the pattern:
7516 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7517 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7519 static SDValue tryCombineToEXTR(SDNode *N,
7520 TargetLowering::DAGCombinerInfo &DCI) {
7521 SelectionDAG &DAG = DCI.DAG;
7523 EVT VT = N->getValueType(0);
7525 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7527 if (VT != MVT::i32 && VT != MVT::i64)
7531 uint32_t ShiftLHS = 0;
7533 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7537 uint32_t ShiftRHS = 0;
7539 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7542 // If they're both trying to come from the high part of the register, they're
7543 // not really an EXTR.
7544 if (LHSFromHi == RHSFromHi)
7547 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7551 std::swap(LHS, RHS);
7552 std::swap(ShiftLHS, ShiftRHS);
7555 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7556 DAG.getConstant(ShiftRHS, DL, MVT::i64));
7559 static SDValue tryCombineToBSL(SDNode *N,
7560 TargetLowering::DAGCombinerInfo &DCI) {
7561 EVT VT = N->getValueType(0);
7562 SelectionDAG &DAG = DCI.DAG;
7568 SDValue N0 = N->getOperand(0);
7569 if (N0.getOpcode() != ISD::AND)
7572 SDValue N1 = N->getOperand(1);
7573 if (N1.getOpcode() != ISD::AND)
7576 // We only have to look for constant vectors here since the general, variable
7577 // case can be handled in TableGen.
7578 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7579 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7580 for (int i = 1; i >= 0; --i)
7581 for (int j = 1; j >= 0; --j) {
7582 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7583 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7587 bool FoundMatch = true;
7588 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7589 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7590 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7592 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7599 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7600 N0->getOperand(1 - i), N1->getOperand(1 - j));
7606 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7607 const AArch64Subtarget *Subtarget) {
7608 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7609 if (!EnableAArch64ExtrGeneration)
7611 SelectionDAG &DAG = DCI.DAG;
7612 EVT VT = N->getValueType(0);
7614 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7617 SDValue Res = tryCombineToEXTR(N, DCI);
7621 Res = tryCombineToBSL(N, DCI);
7628 static SDValue performBitcastCombine(SDNode *N,
7629 TargetLowering::DAGCombinerInfo &DCI,
7630 SelectionDAG &DAG) {
7631 // Wait 'til after everything is legalized to try this. That way we have
7632 // legal vector types and such.
7633 if (DCI.isBeforeLegalizeOps())
7636 // Remove extraneous bitcasts around an extract_subvector.
7638 // (v4i16 (bitconvert
7639 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7641 // (extract_subvector ((v8i16 ...), (i64 4)))
7643 // Only interested in 64-bit vectors as the ultimate result.
7644 EVT VT = N->getValueType(0);
7647 if (VT.getSimpleVT().getSizeInBits() != 64)
7649 // Is the operand an extract_subvector starting at the beginning or halfway
7650 // point of the vector? A low half may also come through as an
7651 // EXTRACT_SUBREG, so look for that, too.
7652 SDValue Op0 = N->getOperand(0);
7653 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7654 !(Op0->isMachineOpcode() &&
7655 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7657 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7658 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7659 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7661 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7662 if (idx != AArch64::dsub)
7664 // The dsub reference is equivalent to a lane zero subvector reference.
7667 // Look through the bitcast of the input to the extract.
7668 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7670 SDValue Source = Op0->getOperand(0)->getOperand(0);
7671 // If the source type has twice the number of elements as our destination
7672 // type, we know this is an extract of the high or low half of the vector.
7673 EVT SVT = Source->getValueType(0);
7674 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7677 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7679 // Create the simplified form to just extract the low or high half of the
7680 // vector directly rather than bothering with the bitcasts.
7682 unsigned NumElements = VT.getVectorNumElements();
7684 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7685 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7687 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7688 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7694 static SDValue performConcatVectorsCombine(SDNode *N,
7695 TargetLowering::DAGCombinerInfo &DCI,
7696 SelectionDAG &DAG) {
7698 EVT VT = N->getValueType(0);
7699 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7701 // Optimize concat_vectors of truncated vectors, where the intermediate
7702 // type is illegal, to avoid said illegality, e.g.,
7703 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7704 // (v2i16 (truncate (v2i64)))))
7706 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7707 // (v4i32 (bitcast (v2i64))),
7709 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7710 // on both input and result type, so we might generate worse code.
7711 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7712 if (N->getNumOperands() == 2 &&
7713 N0->getOpcode() == ISD::TRUNCATE &&
7714 N1->getOpcode() == ISD::TRUNCATE) {
7715 SDValue N00 = N0->getOperand(0);
7716 SDValue N10 = N1->getOperand(0);
7717 EVT N00VT = N00.getValueType();
7719 if (N00VT == N10.getValueType() &&
7720 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7721 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7722 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7723 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7724 for (size_t i = 0; i < Mask.size(); ++i)
7726 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7727 DAG.getVectorShuffle(
7729 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7730 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7734 // Wait 'til after everything is legalized to try this. That way we have
7735 // legal vector types and such.
7736 if (DCI.isBeforeLegalizeOps())
7739 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7740 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7741 // canonicalise to that.
7742 if (N0 == N1 && VT.getVectorNumElements() == 2) {
7743 assert(VT.getVectorElementType().getSizeInBits() == 64);
7744 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7745 DAG.getConstant(0, dl, MVT::i64));
7748 // Canonicalise concat_vectors so that the right-hand vector has as few
7749 // bit-casts as possible before its real operation. The primary matching
7750 // destination for these operations will be the narrowing "2" instructions,
7751 // which depend on the operation being performed on this right-hand vector.
7753 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7755 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7757 if (N1->getOpcode() != ISD::BITCAST)
7759 SDValue RHS = N1->getOperand(0);
7760 MVT RHSTy = RHS.getValueType().getSimpleVT();
7761 // If the RHS is not a vector, this is not the pattern we're looking for.
7762 if (!RHSTy.isVector())
7765 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7767 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7768 RHSTy.getVectorNumElements() * 2);
7769 return DAG.getNode(ISD::BITCAST, dl, VT,
7770 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7771 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7775 static SDValue tryCombineFixedPointConvert(SDNode *N,
7776 TargetLowering::DAGCombinerInfo &DCI,
7777 SelectionDAG &DAG) {
7778 // Wait 'til after everything is legalized to try this. That way we have
7779 // legal vector types and such.
7780 if (DCI.isBeforeLegalizeOps())
7782 // Transform a scalar conversion of a value from a lane extract into a
7783 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7784 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7785 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7787 // The second form interacts better with instruction selection and the
7788 // register allocator to avoid cross-class register copies that aren't
7789 // coalescable due to a lane reference.
7791 // Check the operand and see if it originates from a lane extract.
7792 SDValue Op1 = N->getOperand(1);
7793 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7794 // Yep, no additional predication needed. Perform the transform.
7795 SDValue IID = N->getOperand(0);
7796 SDValue Shift = N->getOperand(2);
7797 SDValue Vec = Op1.getOperand(0);
7798 SDValue Lane = Op1.getOperand(1);
7799 EVT ResTy = N->getValueType(0);
7803 // The vector width should be 128 bits by the time we get here, even
7804 // if it started as 64 bits (the extract_vector handling will have
7806 assert(Vec.getValueType().getSizeInBits() == 128 &&
7807 "unexpected vector size on extract_vector_elt!");
7808 if (Vec.getValueType() == MVT::v4i32)
7809 VecResTy = MVT::v4f32;
7810 else if (Vec.getValueType() == MVT::v2i64)
7811 VecResTy = MVT::v2f64;
7813 llvm_unreachable("unexpected vector type!");
7816 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7817 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7822 // AArch64 high-vector "long" operations are formed by performing the non-high
7823 // version on an extract_subvector of each operand which gets the high half:
7825 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7827 // However, there are cases which don't have an extract_high explicitly, but
7828 // have another operation that can be made compatible with one for free. For
7831 // (dupv64 scalar) --> (extract_high (dup128 scalar))
7833 // This routine does the actual conversion of such DUPs, once outer routines
7834 // have determined that everything else is in order.
7835 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7837 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7838 switch (N.getOpcode()) {
7839 case AArch64ISD::DUP:
7840 case AArch64ISD::DUPLANE8:
7841 case AArch64ISD::DUPLANE16:
7842 case AArch64ISD::DUPLANE32:
7843 case AArch64ISD::DUPLANE64:
7844 case AArch64ISD::MOVI:
7845 case AArch64ISD::MOVIshift:
7846 case AArch64ISD::MOVIedit:
7847 case AArch64ISD::MOVImsl:
7848 case AArch64ISD::MVNIshift:
7849 case AArch64ISD::MVNImsl:
7852 // FMOV could be supported, but isn't very useful, as it would only occur
7853 // if you passed a bitcast' floating point immediate to an eligible long
7854 // integer op (addl, smull, ...).
7858 MVT NarrowTy = N.getSimpleValueType();
7859 if (!NarrowTy.is64BitVector())
7862 MVT ElementTy = NarrowTy.getVectorElementType();
7863 unsigned NumElems = NarrowTy.getVectorNumElements();
7864 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7867 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
7868 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
7869 DAG.getConstant(NumElems, dl, MVT::i64));
7872 static bool isEssentiallyExtractSubvector(SDValue N) {
7873 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7876 return N.getOpcode() == ISD::BITCAST &&
7877 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7880 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7881 struct GenericSetCCInfo {
7882 const SDValue *Opnd0;
7883 const SDValue *Opnd1;
7887 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7888 struct AArch64SetCCInfo {
7890 AArch64CC::CondCode CC;
7893 /// \brief Helper structure to keep track of SetCC information.
7895 GenericSetCCInfo Generic;
7896 AArch64SetCCInfo AArch64;
7899 /// \brief Helper structure to be able to read SetCC information. If set to
7900 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7901 /// GenericSetCCInfo.
7902 struct SetCCInfoAndKind {
7907 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7909 /// AArch64 lowered one.
7910 /// \p SetCCInfo is filled accordingly.
7911 /// \post SetCCInfo is meanginfull only when this function returns true.
7912 /// \return True when Op is a kind of SET_CC operation.
7913 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7914 // If this is a setcc, this is straight forward.
7915 if (Op.getOpcode() == ISD::SETCC) {
7916 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7917 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7918 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7919 SetCCInfo.IsAArch64 = false;
7922 // Otherwise, check if this is a matching csel instruction.
7926 if (Op.getOpcode() != AArch64ISD::CSEL)
7928 // Set the information about the operands.
7929 // TODO: we want the operands of the Cmp not the csel
7930 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7931 SetCCInfo.IsAArch64 = true;
7932 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7933 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7935 // Check that the operands matches the constraints:
7936 // (1) Both operands must be constants.
7937 // (2) One must be 1 and the other must be 0.
7938 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7939 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7942 if (!TValue || !FValue)
7946 if (!TValue->isOne()) {
7947 // Update the comparison when we are interested in !cc.
7948 std::swap(TValue, FValue);
7949 SetCCInfo.Info.AArch64.CC =
7950 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7952 return TValue->isOne() && FValue->isNullValue();
7955 // Returns true if Op is setcc or zext of setcc.
7956 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7957 if (isSetCC(Op, Info))
7959 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7960 isSetCC(Op->getOperand(0), Info));
7963 // The folding we want to perform is:
7964 // (add x, [zext] (setcc cc ...) )
7966 // (csel x, (add x, 1), !cc ...)
7968 // The latter will get matched to a CSINC instruction.
7969 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7970 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7971 SDValue LHS = Op->getOperand(0);
7972 SDValue RHS = Op->getOperand(1);
7973 SetCCInfoAndKind InfoAndKind;
7975 // If neither operand is a SET_CC, give up.
7976 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7977 std::swap(LHS, RHS);
7978 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7982 // FIXME: This could be generatized to work for FP comparisons.
7983 EVT CmpVT = InfoAndKind.IsAArch64
7984 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7985 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7986 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7992 if (InfoAndKind.IsAArch64) {
7993 CCVal = DAG.getConstant(
7994 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
7996 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7998 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7999 *InfoAndKind.Info.Generic.Opnd1,
8000 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8003 EVT VT = Op->getValueType(0);
8004 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8005 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8008 // The basic add/sub long vector instructions have variants with "2" on the end
8009 // which act on the high-half of their inputs. They are normally matched by
8012 // (add (zeroext (extract_high LHS)),
8013 // (zeroext (extract_high RHS)))
8014 // -> uaddl2 vD, vN, vM
8016 // However, if one of the extracts is something like a duplicate, this
8017 // instruction can still be used profitably. This function puts the DAG into a
8018 // more appropriate form for those patterns to trigger.
8019 static SDValue performAddSubLongCombine(SDNode *N,
8020 TargetLowering::DAGCombinerInfo &DCI,
8021 SelectionDAG &DAG) {
8022 if (DCI.isBeforeLegalizeOps())
8025 MVT VT = N->getSimpleValueType(0);
8026 if (!VT.is128BitVector()) {
8027 if (N->getOpcode() == ISD::ADD)
8028 return performSetccAddFolding(N, DAG);
8032 // Make sure both branches are extended in the same way.
8033 SDValue LHS = N->getOperand(0);
8034 SDValue RHS = N->getOperand(1);
8035 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8036 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8037 LHS.getOpcode() != RHS.getOpcode())
8040 unsigned ExtType = LHS.getOpcode();
8042 // It's not worth doing if at least one of the inputs isn't already an
8043 // extract, but we don't know which it'll be so we have to try both.
8044 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8045 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8049 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8050 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8051 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8055 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8058 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8061 // Massage DAGs which we can use the high-half "long" operations on into
8062 // something isel will recognize better. E.g.
8064 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8065 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8066 // (extract_high (v2i64 (dup128 scalar)))))
8068 static SDValue tryCombineLongOpWithDup(SDNode *N,
8069 TargetLowering::DAGCombinerInfo &DCI,
8070 SelectionDAG &DAG) {
8071 if (DCI.isBeforeLegalizeOps())
8074 bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8075 SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8076 SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8077 assert(LHS.getValueType().is64BitVector() &&
8078 RHS.getValueType().is64BitVector() &&
8079 "unexpected shape for long operation");
8081 // Either node could be a DUP, but it's not worth doing both of them (you'd
8082 // just as well use the non-high version) so look for a corresponding extract
8083 // operation on the other "wing".
8084 if (isEssentiallyExtractSubvector(LHS)) {
8085 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8088 } else if (isEssentiallyExtractSubvector(RHS)) {
8089 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8094 // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8096 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8097 N->getOperand(0), LHS, RHS);
8099 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8103 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8104 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8105 unsigned ElemBits = ElemTy.getSizeInBits();
8107 int64_t ShiftAmount;
8108 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8109 APInt SplatValue, SplatUndef;
8110 unsigned SplatBitSize;
8112 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8113 HasAnyUndefs, ElemBits) ||
8114 SplatBitSize != ElemBits)
8117 ShiftAmount = SplatValue.getSExtValue();
8118 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8119 ShiftAmount = CVN->getSExtValue();
8127 llvm_unreachable("Unknown shift intrinsic");
8128 case Intrinsic::aarch64_neon_sqshl:
8129 Opcode = AArch64ISD::SQSHL_I;
8130 IsRightShift = false;
8132 case Intrinsic::aarch64_neon_uqshl:
8133 Opcode = AArch64ISD::UQSHL_I;
8134 IsRightShift = false;
8136 case Intrinsic::aarch64_neon_srshl:
8137 Opcode = AArch64ISD::SRSHR_I;
8138 IsRightShift = true;
8140 case Intrinsic::aarch64_neon_urshl:
8141 Opcode = AArch64ISD::URSHR_I;
8142 IsRightShift = true;
8144 case Intrinsic::aarch64_neon_sqshlu:
8145 Opcode = AArch64ISD::SQSHLU_I;
8146 IsRightShift = false;
8150 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8152 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8153 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8154 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8156 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8157 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8163 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8164 // the intrinsics must be legal and take an i32, this means there's almost
8165 // certainly going to be a zext in the DAG which we can eliminate.
8166 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8167 SDValue AndN = N->getOperand(2);
8168 if (AndN.getOpcode() != ISD::AND)
8171 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8172 if (!CMask || CMask->getZExtValue() != Mask)
8175 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8176 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8179 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8180 SelectionDAG &DAG) {
8182 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8183 DAG.getNode(Opc, dl,
8184 N->getOperand(1).getSimpleValueType(),
8186 DAG.getConstant(0, dl, MVT::i64));
8189 static SDValue performIntrinsicCombine(SDNode *N,
8190 TargetLowering::DAGCombinerInfo &DCI,
8191 const AArch64Subtarget *Subtarget) {
8192 SelectionDAG &DAG = DCI.DAG;
8193 unsigned IID = getIntrinsicID(N);
8197 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8198 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8199 return tryCombineFixedPointConvert(N, DCI, DAG);
8200 case Intrinsic::aarch64_neon_saddv:
8201 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8202 case Intrinsic::aarch64_neon_uaddv:
8203 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8204 case Intrinsic::aarch64_neon_sminv:
8205 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8206 case Intrinsic::aarch64_neon_uminv:
8207 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8208 case Intrinsic::aarch64_neon_smaxv:
8209 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8210 case Intrinsic::aarch64_neon_umaxv:
8211 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8212 case Intrinsic::aarch64_neon_fmax:
8213 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8214 N->getOperand(1), N->getOperand(2));
8215 case Intrinsic::aarch64_neon_fmin:
8216 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8217 N->getOperand(1), N->getOperand(2));
8218 case Intrinsic::aarch64_neon_sabd:
8219 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8220 N->getOperand(1), N->getOperand(2));
8221 case Intrinsic::aarch64_neon_uabd:
8222 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8223 N->getOperand(1), N->getOperand(2));
8224 case Intrinsic::aarch64_neon_fmaxnm:
8225 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8226 N->getOperand(1), N->getOperand(2));
8227 case Intrinsic::aarch64_neon_fminnm:
8228 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8229 N->getOperand(1), N->getOperand(2));
8230 case Intrinsic::aarch64_neon_smull:
8231 case Intrinsic::aarch64_neon_umull:
8232 case Intrinsic::aarch64_neon_pmull:
8233 case Intrinsic::aarch64_neon_sqdmull:
8234 return tryCombineLongOpWithDup(N, DCI, DAG);
8235 case Intrinsic::aarch64_neon_sqshl:
8236 case Intrinsic::aarch64_neon_uqshl:
8237 case Intrinsic::aarch64_neon_sqshlu:
8238 case Intrinsic::aarch64_neon_srshl:
8239 case Intrinsic::aarch64_neon_urshl:
8240 return tryCombineShiftImm(IID, N, DAG);
8241 case Intrinsic::aarch64_crc32b:
8242 case Intrinsic::aarch64_crc32cb:
8243 return tryCombineCRC32(0xff, N, DAG);
8244 case Intrinsic::aarch64_crc32h:
8245 case Intrinsic::aarch64_crc32ch:
8246 return tryCombineCRC32(0xffff, N, DAG);
8251 static SDValue performExtendCombine(SDNode *N,
8252 TargetLowering::DAGCombinerInfo &DCI,
8253 SelectionDAG &DAG) {
8254 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8255 // we can convert that DUP into another extract_high (of a bigger DUP), which
8256 // helps the backend to decide that an sabdl2 would be useful, saving a real
8257 // extract_high operation.
8258 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8259 (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8260 N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8261 SDNode *ABDNode = N->getOperand(0).getNode();
8262 SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8263 if (!NewABD.getNode())
8266 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8270 // This is effectively a custom type legalization for AArch64.
8272 // Type legalization will split an extend of a small, legal, type to a larger
8273 // illegal type by first splitting the destination type, often creating
8274 // illegal source types, which then get legalized in isel-confusing ways,
8275 // leading to really terrible codegen. E.g.,
8276 // %result = v8i32 sext v8i8 %value
8278 // %losrc = extract_subreg %value, ...
8279 // %hisrc = extract_subreg %value, ...
8280 // %lo = v4i32 sext v4i8 %losrc
8281 // %hi = v4i32 sext v4i8 %hisrc
8282 // Things go rapidly downhill from there.
8284 // For AArch64, the [sz]ext vector instructions can only go up one element
8285 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8286 // take two instructions.
8288 // This implies that the most efficient way to do the extend from v8i8
8289 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8290 // the normal splitting to happen for the v8i16->v8i32.
8292 // This is pre-legalization to catch some cases where the default
8293 // type legalization will create ill-tempered code.
8294 if (!DCI.isBeforeLegalizeOps())
8297 // We're only interested in cleaning things up for non-legal vector types
8298 // here. If both the source and destination are legal, things will just
8299 // work naturally without any fiddling.
8300 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8301 EVT ResVT = N->getValueType(0);
8302 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8304 // If the vector type isn't a simple VT, it's beyond the scope of what
8305 // we're worried about here. Let legalization do its thing and hope for
8307 SDValue Src = N->getOperand(0);
8308 EVT SrcVT = Src->getValueType(0);
8309 if (!ResVT.isSimple() || !SrcVT.isSimple())
8312 // If the source VT is a 64-bit vector, we can play games and get the
8313 // better results we want.
8314 if (SrcVT.getSizeInBits() != 64)
8317 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8318 unsigned ElementCount = SrcVT.getVectorNumElements();
8319 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8321 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8323 // Now split the rest of the operation into two halves, each with a 64
8327 unsigned NumElements = ResVT.getVectorNumElements();
8328 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8329 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8330 ResVT.getVectorElementType(), NumElements / 2);
8332 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8333 LoVT.getVectorNumElements());
8334 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8335 DAG.getConstant(0, DL, MVT::i64));
8336 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8337 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8338 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8339 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8341 // Now combine the parts back together so we still have a single result
8342 // like the combiner expects.
8343 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8346 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8347 /// value. The load store optimizer pass will merge them to store pair stores.
8348 /// This has better performance than a splat of the scalar followed by a split
8349 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8350 /// followed by an ext.b and two stores.
8351 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8352 SDValue StVal = St->getValue();
8353 EVT VT = StVal.getValueType();
8355 // Don't replace floating point stores, they possibly won't be transformed to
8356 // stp because of the store pair suppress pass.
8357 if (VT.isFloatingPoint())
8360 // Check for insert vector elements.
8361 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8364 // We can express a splat as store pair(s) for 2 or 4 elements.
8365 unsigned NumVecElts = VT.getVectorNumElements();
8366 if (NumVecElts != 4 && NumVecElts != 2)
8368 SDValue SplatVal = StVal.getOperand(1);
8369 unsigned RemainInsertElts = NumVecElts - 1;
8371 // Check that this is a splat.
8372 while (--RemainInsertElts) {
8373 SDValue NextInsertElt = StVal.getOperand(0);
8374 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8376 if (NextInsertElt.getOperand(1) != SplatVal)
8378 StVal = NextInsertElt;
8380 unsigned OrigAlignment = St->getAlignment();
8381 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8382 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8384 // Create scalar stores. This is at least as good as the code sequence for a
8385 // split unaligned store which is a dup.s, ext.b, and two stores.
8386 // Most of the time the three stores should be replaced by store pair
8387 // instructions (stp).
8389 SDValue BasePtr = St->getBasePtr();
8391 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8392 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8394 unsigned Offset = EltOffset;
8395 while (--NumVecElts) {
8396 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8397 DAG.getConstant(Offset, DL, MVT::i64));
8398 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8399 St->getPointerInfo(), St->isVolatile(),
8400 St->isNonTemporal(), Alignment);
8401 Offset += EltOffset;
8406 static SDValue performSTORECombine(SDNode *N,
8407 TargetLowering::DAGCombinerInfo &DCI,
8409 const AArch64Subtarget *Subtarget) {
8410 if (!DCI.isBeforeLegalize())
8413 StoreSDNode *S = cast<StoreSDNode>(N);
8414 if (S->isVolatile())
8417 // Cyclone has bad performance on unaligned 16B stores when crossing line and
8418 // page boundaries. We want to split such stores.
8419 if (!Subtarget->isCyclone())
8422 // Don't split at -Oz.
8423 if (DAG.getMachineFunction().getFunction()->optForMinSize())
8426 SDValue StVal = S->getValue();
8427 EVT VT = StVal.getValueType();
8429 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8430 // those up regresses performance on micro-benchmarks and olden/bh.
8431 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8434 // Split unaligned 16B stores. They are terrible for performance.
8435 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8436 // extensions can use this to mark that it does not want splitting to happen
8437 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8438 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8439 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8440 S->getAlignment() <= 2)
8443 // If we get a splat of a scalar convert this vector store to a store of
8444 // scalars. They will be merged into store pairs thereby removing two
8446 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8447 return ReplacedSplat;
8450 unsigned NumElts = VT.getVectorNumElements() / 2;
8451 // Split VT into two.
8453 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8454 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8455 DAG.getConstant(0, DL, MVT::i64));
8456 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8457 DAG.getConstant(NumElts, DL, MVT::i64));
8458 SDValue BasePtr = S->getBasePtr();
8460 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8461 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8462 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8463 DAG.getConstant(8, DL, MVT::i64));
8464 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8465 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8469 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8470 /// post-increment LD1R.
8471 static SDValue performPostLD1Combine(SDNode *N,
8472 TargetLowering::DAGCombinerInfo &DCI,
8474 if (DCI.isBeforeLegalizeOps())
8477 SelectionDAG &DAG = DCI.DAG;
8478 EVT VT = N->getValueType(0);
8480 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8481 SDNode *LD = N->getOperand(LoadIdx).getNode();
8482 // If it is not LOAD, can not do such combine.
8483 if (LD->getOpcode() != ISD::LOAD)
8486 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8487 EVT MemVT = LoadSDN->getMemoryVT();
8488 // Check if memory operand is the same type as the vector element.
8489 if (MemVT != VT.getVectorElementType())
8492 // Check if there are other uses. If so, do not combine as it will introduce
8494 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8496 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8502 SDValue Addr = LD->getOperand(1);
8503 SDValue Vector = N->getOperand(0);
8504 // Search for a use of the address operand that is an increment.
8505 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8506 Addr.getNode()->use_end(); UI != UE; ++UI) {
8508 if (User->getOpcode() != ISD::ADD
8509 || UI.getUse().getResNo() != Addr.getResNo())
8512 // Check that the add is independent of the load. Otherwise, folding it
8513 // would create a cycle.
8514 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8516 // Also check that add is not used in the vector operand. This would also
8518 if (User->isPredecessorOf(Vector.getNode()))
8521 // If the increment is a constant, it must match the memory ref size.
8522 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8523 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8524 uint32_t IncVal = CInc->getZExtValue();
8525 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8526 if (IncVal != NumBytes)
8528 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8531 // Finally, check that the vector doesn't depend on the load.
8532 // Again, this would create a cycle.
8533 // The load depending on the vector is fine, as that's the case for the
8534 // LD1*post we'll eventually generate anyway.
8535 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8538 SmallVector<SDValue, 8> Ops;
8539 Ops.push_back(LD->getOperand(0)); // Chain
8541 Ops.push_back(Vector); // The vector to be inserted
8542 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8544 Ops.push_back(Addr);
8547 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8548 SDVTList SDTys = DAG.getVTList(Tys);
8549 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8550 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8552 LoadSDN->getMemOperand());
8555 SmallVector<SDValue, 2> NewResults;
8556 NewResults.push_back(SDValue(LD, 0)); // The result of load
8557 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8558 DCI.CombineTo(LD, NewResults);
8559 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8560 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8567 /// Target-specific DAG combine function for NEON load/store intrinsics
8568 /// to merge base address updates.
8569 static SDValue performNEONPostLDSTCombine(SDNode *N,
8570 TargetLowering::DAGCombinerInfo &DCI,
8571 SelectionDAG &DAG) {
8572 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8575 unsigned AddrOpIdx = N->getNumOperands() - 1;
8576 SDValue Addr = N->getOperand(AddrOpIdx);
8578 // Search for a use of the address operand that is an increment.
8579 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8580 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8582 if (User->getOpcode() != ISD::ADD ||
8583 UI.getUse().getResNo() != Addr.getResNo())
8586 // Check that the add is independent of the load/store. Otherwise, folding
8587 // it would create a cycle.
8588 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8591 // Find the new opcode for the updating load/store.
8592 bool IsStore = false;
8593 bool IsLaneOp = false;
8594 bool IsDupOp = false;
8595 unsigned NewOpc = 0;
8596 unsigned NumVecs = 0;
8597 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8599 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8600 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8602 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8604 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8606 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8607 NumVecs = 2; IsStore = true; break;
8608 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8609 NumVecs = 3; IsStore = true; break;
8610 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8611 NumVecs = 4; IsStore = true; break;
8612 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8614 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8616 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8618 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8619 NumVecs = 2; IsStore = true; break;
8620 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8621 NumVecs = 3; IsStore = true; break;
8622 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8623 NumVecs = 4; IsStore = true; break;
8624 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8625 NumVecs = 2; IsDupOp = true; break;
8626 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8627 NumVecs = 3; IsDupOp = true; break;
8628 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8629 NumVecs = 4; IsDupOp = true; break;
8630 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8631 NumVecs = 2; IsLaneOp = true; break;
8632 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8633 NumVecs = 3; IsLaneOp = true; break;
8634 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8635 NumVecs = 4; IsLaneOp = true; break;
8636 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8637 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8638 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8639 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8640 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8641 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8646 VecTy = N->getOperand(2).getValueType();
8648 VecTy = N->getValueType(0);
8650 // If the increment is a constant, it must match the memory ref size.
8651 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8652 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8653 uint32_t IncVal = CInc->getZExtValue();
8654 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8655 if (IsLaneOp || IsDupOp)
8656 NumBytes /= VecTy.getVectorNumElements();
8657 if (IncVal != NumBytes)
8659 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8661 SmallVector<SDValue, 8> Ops;
8662 Ops.push_back(N->getOperand(0)); // Incoming chain
8663 // Load lane and store have vector list as input.
8664 if (IsLaneOp || IsStore)
8665 for (unsigned i = 2; i < AddrOpIdx; ++i)
8666 Ops.push_back(N->getOperand(i));
8667 Ops.push_back(Addr); // Base register
8672 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8674 for (n = 0; n < NumResultVecs; ++n)
8676 Tys[n++] = MVT::i64; // Type of write back register
8677 Tys[n] = MVT::Other; // Type of the chain
8678 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8680 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8681 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8682 MemInt->getMemoryVT(),
8683 MemInt->getMemOperand());
8686 std::vector<SDValue> NewResults;
8687 for (unsigned i = 0; i < NumResultVecs; ++i) {
8688 NewResults.push_back(SDValue(UpdN.getNode(), i));
8690 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8691 DCI.CombineTo(N, NewResults);
8692 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8699 // Checks to see if the value is the prescribed width and returns information
8700 // about its extension mode.
8702 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8703 ExtType = ISD::NON_EXTLOAD;
8704 switch(V.getNode()->getOpcode()) {
8708 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8709 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8710 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8711 ExtType = LoadNode->getExtensionType();
8716 case ISD::AssertSext: {
8717 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8718 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8719 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8720 ExtType = ISD::SEXTLOAD;
8725 case ISD::AssertZext: {
8726 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8727 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8728 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8729 ExtType = ISD::ZEXTLOAD;
8735 case ISD::TargetConstant: {
8736 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8746 // This function does a whole lot of voodoo to determine if the tests are
8747 // equivalent without and with a mask. Essentially what happens is that given a
8750 // +-------------+ +-------------+ +-------------+ +-------------+
8751 // | Input | | AddConstant | | CompConstant| | CC |
8752 // +-------------+ +-------------+ +-------------+ +-------------+
8754 // V V | +----------+
8755 // +-------------+ +----+ | |
8756 // | ADD | |0xff| | |
8757 // +-------------+ +----+ | |
8760 // +-------------+ | |
8762 // +-------------+ | |
8771 // The AND node may be safely removed for some combinations of inputs. In
8772 // particular we need to take into account the extension type of the Input,
8773 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8774 // width of the input (this can work for any width inputs, the above graph is
8775 // specific to 8 bits.
8777 // The specific equations were worked out by generating output tables for each
8778 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8779 // problem was simplified by working with 4 bit inputs, which means we only
8780 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8781 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8782 // patterns present in both extensions (0,7). For every distinct set of
8783 // AddConstant and CompConstants bit patterns we can consider the masked and
8784 // unmasked versions to be equivalent if the result of this function is true for
8785 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8788 // and w10, w8, #0x0f
8790 // cset w9, AArch64CC
8792 // cset w11, AArch64CC
8797 // Since the above function shows when the outputs are equivalent it defines
8798 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8799 // would be expensive to run during compiles. The equations below were written
8800 // in a test harness that confirmed they gave equivalent outputs to the above
8801 // for all inputs function, so they can be used determine if the removal is
8804 // isEquivalentMaskless() is the code for testing if the AND can be removed
8805 // factored out of the DAG recognition as the DAG can take several forms.
8808 bool isEquivalentMaskless(unsigned CC, unsigned width,
8809 ISD::LoadExtType ExtType, signed AddConstant,
8810 signed CompConstant) {
8811 // By being careful about our equations and only writing the in term
8812 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8813 // make them generally applicable to all bit widths.
8814 signed MaxUInt = (1 << width);
8816 // For the purposes of these comparisons sign extending the type is
8817 // equivalent to zero extending the add and displacing it by half the integer
8818 // width. Provided we are careful and make sure our equations are valid over
8819 // the whole range we can just adjust the input and avoid writing equations
8820 // for sign extended inputs.
8821 if (ExtType == ISD::SEXTLOAD)
8822 AddConstant -= (1 << (width-1));
8826 case AArch64CC::GT: {
8827 if ((AddConstant == 0) ||
8828 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8829 (AddConstant >= 0 && CompConstant < 0) ||
8830 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8834 case AArch64CC::GE: {
8835 if ((AddConstant == 0) ||
8836 (AddConstant >= 0 && CompConstant <= 0) ||
8837 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8841 case AArch64CC::LS: {
8842 if ((AddConstant >= 0 && CompConstant < 0) ||
8843 (AddConstant <= 0 && CompConstant >= -1 &&
8844 CompConstant < AddConstant + MaxUInt))
8848 case AArch64CC::MI: {
8849 if ((AddConstant == 0) ||
8850 (AddConstant > 0 && CompConstant <= 0) ||
8851 (AddConstant < 0 && CompConstant <= AddConstant))
8855 case AArch64CC::HS: {
8856 if ((AddConstant >= 0 && CompConstant <= 0) ||
8857 (AddConstant <= 0 && CompConstant >= 0 &&
8858 CompConstant <= AddConstant + MaxUInt))
8862 case AArch64CC::NE: {
8863 if ((AddConstant > 0 && CompConstant < 0) ||
8864 (AddConstant < 0 && CompConstant >= 0 &&
8865 CompConstant < AddConstant + MaxUInt) ||
8866 (AddConstant >= 0 && CompConstant >= 0 &&
8867 CompConstant >= AddConstant) ||
8868 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8877 case AArch64CC::Invalid:
8885 SDValue performCONDCombine(SDNode *N,
8886 TargetLowering::DAGCombinerInfo &DCI,
8887 SelectionDAG &DAG, unsigned CCIndex,
8888 unsigned CmpIndex) {
8889 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8890 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8891 unsigned CondOpcode = SubsNode->getOpcode();
8893 if (CondOpcode != AArch64ISD::SUBS)
8896 // There is a SUBS feeding this condition. Is it fed by a mask we can
8899 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8900 unsigned MaskBits = 0;
8902 if (AndNode->getOpcode() != ISD::AND)
8905 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8906 uint32_t CNV = CN->getZExtValue();
8909 else if (CNV == 65535)
8916 SDValue AddValue = AndNode->getOperand(0);
8918 if (AddValue.getOpcode() != ISD::ADD)
8921 // The basic dag structure is correct, grab the inputs and validate them.
8923 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8924 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8925 SDValue SubsInputValue = SubsNode->getOperand(1);
8927 // The mask is present and the provenance of all the values is a smaller type,
8928 // lets see if the mask is superfluous.
8930 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8931 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8934 ISD::LoadExtType ExtType;
8936 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8937 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8938 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8941 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8942 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8943 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8946 // The AND is not necessary, remove it.
8948 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8949 SubsNode->getValueType(1));
8950 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8952 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8953 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8955 return SDValue(N, 0);
8958 // Optimize compare with zero and branch.
8959 static SDValue performBRCONDCombine(SDNode *N,
8960 TargetLowering::DAGCombinerInfo &DCI,
8961 SelectionDAG &DAG) {
8962 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8965 SDValue Chain = N->getOperand(0);
8966 SDValue Dest = N->getOperand(1);
8967 SDValue CCVal = N->getOperand(2);
8968 SDValue Cmp = N->getOperand(3);
8970 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8971 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8972 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8975 unsigned CmpOpc = Cmp.getOpcode();
8976 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8979 // Only attempt folding if there is only one use of the flag and no use of the
8981 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8984 SDValue LHS = Cmp.getOperand(0);
8985 SDValue RHS = Cmp.getOperand(1);
8987 assert(LHS.getValueType() == RHS.getValueType() &&
8988 "Expected the value type to be the same for both operands!");
8989 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8992 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8993 std::swap(LHS, RHS);
8995 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8998 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8999 LHS.getOpcode() == ISD::SRL)
9002 // Fold the compare into the branch instruction.
9004 if (CC == AArch64CC::EQ)
9005 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9007 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9009 // Do not add new nodes to DAG combiner worklist.
9010 DCI.CombineTo(N, BR, false);
9015 // vselect (v1i1 setcc) ->
9016 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
9017 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9018 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9020 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9021 SDValue N0 = N->getOperand(0);
9022 EVT CCVT = N0.getValueType();
9024 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9025 CCVT.getVectorElementType() != MVT::i1)
9028 EVT ResVT = N->getValueType(0);
9029 EVT CmpVT = N0.getOperand(0).getValueType();
9030 // Only combine when the result type is of the same size as the compared
9032 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9035 SDValue IfTrue = N->getOperand(1);
9036 SDValue IfFalse = N->getOperand(2);
9038 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9039 N0.getOperand(0), N0.getOperand(1),
9040 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9041 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9045 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9046 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9047 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9048 /// with a vector one followed by a DUP shuffle on the result.
9049 static SDValue performSelectCombine(SDNode *N,
9050 TargetLowering::DAGCombinerInfo &DCI) {
9051 SelectionDAG &DAG = DCI.DAG;
9052 SDValue N0 = N->getOperand(0);
9053 EVT ResVT = N->getValueType(0);
9055 if (N0.getOpcode() != ISD::SETCC)
9058 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9059 // scalar SetCCResultType. We also don't expect vectors, because we assume
9060 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9061 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9062 "Scalar-SETCC feeding SELECT has unexpected result type!");
9064 // If NumMaskElts == 0, the comparison is larger than select result. The
9065 // largest real NEON comparison is 64-bits per lane, which means the result is
9066 // at most 32-bits and an illegal vector. Just bail out for now.
9067 EVT SrcVT = N0.getOperand(0).getValueType();
9069 // Don't try to do this optimization when the setcc itself has i1 operands.
9070 // There are no legal vectors of i1, so this would be pointless.
9071 if (SrcVT == MVT::i1)
9074 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9075 if (!ResVT.isVector() || NumMaskElts == 0)
9078 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9079 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9081 // Also bail out if the vector CCVT isn't the same size as ResVT.
9082 // This can happen if the SETCC operand size doesn't divide the ResVT size
9083 // (e.g., f64 vs v3f32).
9084 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9087 // Make sure we didn't create illegal types, if we're not supposed to.
9088 assert(DCI.isBeforeLegalize() ||
9089 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9091 // First perform a vector comparison, where lane 0 is the one we're interested
9095 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9097 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9098 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9100 // Now duplicate the comparison mask we want across all other lanes.
9101 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9102 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9103 Mask = DAG.getNode(ISD::BITCAST, DL,
9104 ResVT.changeVectorElementTypeToInteger(), Mask);
9106 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9109 /// Get rid of unnecessary NVCASTs (that don't change the type).
9110 static SDValue performNVCASTCombine(SDNode *N) {
9111 if (N->getValueType(0) == N->getOperand(0).getValueType())
9112 return N->getOperand(0);
9117 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9118 DAGCombinerInfo &DCI) const {
9119 SelectionDAG &DAG = DCI.DAG;
9120 switch (N->getOpcode()) {
9125 return performAddSubLongCombine(N, DCI, DAG);
9127 return performXorCombine(N, DAG, DCI, Subtarget);
9129 return performMulCombine(N, DAG, DCI, Subtarget);
9130 case ISD::SINT_TO_FP:
9131 case ISD::UINT_TO_FP:
9132 return performIntToFpCombine(N, DAG, Subtarget);
9134 return performORCombine(N, DCI, Subtarget);
9135 case ISD::INTRINSIC_WO_CHAIN:
9136 return performIntrinsicCombine(N, DCI, Subtarget);
9137 case ISD::ANY_EXTEND:
9138 case ISD::ZERO_EXTEND:
9139 case ISD::SIGN_EXTEND:
9140 return performExtendCombine(N, DCI, DAG);
9142 return performBitcastCombine(N, DCI, DAG);
9143 case ISD::CONCAT_VECTORS:
9144 return performConcatVectorsCombine(N, DCI, DAG);
9146 return performSelectCombine(N, DCI);
9148 return performVSelectCombine(N, DCI.DAG);
9150 return performSTORECombine(N, DCI, DAG, Subtarget);
9151 case AArch64ISD::BRCOND:
9152 return performBRCONDCombine(N, DCI, DAG);
9153 case AArch64ISD::CSEL:
9154 return performCONDCombine(N, DCI, DAG, 2, 3);
9155 case AArch64ISD::DUP:
9156 return performPostLD1Combine(N, DCI, false);
9157 case AArch64ISD::NVCAST:
9158 return performNVCASTCombine(N);
9159 case ISD::INSERT_VECTOR_ELT:
9160 return performPostLD1Combine(N, DCI, true);
9161 case ISD::INTRINSIC_VOID:
9162 case ISD::INTRINSIC_W_CHAIN:
9163 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9164 case Intrinsic::aarch64_neon_ld2:
9165 case Intrinsic::aarch64_neon_ld3:
9166 case Intrinsic::aarch64_neon_ld4:
9167 case Intrinsic::aarch64_neon_ld1x2:
9168 case Intrinsic::aarch64_neon_ld1x3:
9169 case Intrinsic::aarch64_neon_ld1x4:
9170 case Intrinsic::aarch64_neon_ld2lane:
9171 case Intrinsic::aarch64_neon_ld3lane:
9172 case Intrinsic::aarch64_neon_ld4lane:
9173 case Intrinsic::aarch64_neon_ld2r:
9174 case Intrinsic::aarch64_neon_ld3r:
9175 case Intrinsic::aarch64_neon_ld4r:
9176 case Intrinsic::aarch64_neon_st2:
9177 case Intrinsic::aarch64_neon_st3:
9178 case Intrinsic::aarch64_neon_st4:
9179 case Intrinsic::aarch64_neon_st1x2:
9180 case Intrinsic::aarch64_neon_st1x3:
9181 case Intrinsic::aarch64_neon_st1x4:
9182 case Intrinsic::aarch64_neon_st2lane:
9183 case Intrinsic::aarch64_neon_st3lane:
9184 case Intrinsic::aarch64_neon_st4lane:
9185 return performNEONPostLDSTCombine(N, DCI, DAG);
9193 // Check if the return value is used as only a return value, as otherwise
9194 // we can't perform a tail-call. In particular, we need to check for
9195 // target ISD nodes that are returns and any other "odd" constructs
9196 // that the generic analysis code won't necessarily catch.
9197 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9198 SDValue &Chain) const {
9199 if (N->getNumValues() != 1)
9201 if (!N->hasNUsesOfValue(1, 0))
9204 SDValue TCChain = Chain;
9205 SDNode *Copy = *N->use_begin();
9206 if (Copy->getOpcode() == ISD::CopyToReg) {
9207 // If the copy has a glue operand, we conservatively assume it isn't safe to
9208 // perform a tail call.
9209 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9212 TCChain = Copy->getOperand(0);
9213 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9216 bool HasRet = false;
9217 for (SDNode *Node : Copy->uses()) {
9218 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9230 // Return whether the an instruction can potentially be optimized to a tail
9231 // call. This will cause the optimizers to attempt to move, or duplicate,
9232 // return instructions to help enable tail call optimizations for this
9234 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9235 if (!CI->isTailCall())
9241 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9243 ISD::MemIndexedMode &AM,
9245 SelectionDAG &DAG) const {
9246 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9249 Base = Op->getOperand(0);
9250 // All of the indexed addressing mode instructions take a signed
9251 // 9 bit immediate offset.
9252 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9253 int64_t RHSC = (int64_t)RHS->getZExtValue();
9254 if (RHSC >= 256 || RHSC <= -256)
9256 IsInc = (Op->getOpcode() == ISD::ADD);
9257 Offset = Op->getOperand(1);
9263 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9265 ISD::MemIndexedMode &AM,
9266 SelectionDAG &DAG) const {
9269 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9270 VT = LD->getMemoryVT();
9271 Ptr = LD->getBasePtr();
9272 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9273 VT = ST->getMemoryVT();
9274 Ptr = ST->getBasePtr();
9279 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9281 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9285 bool AArch64TargetLowering::getPostIndexedAddressParts(
9286 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9287 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9290 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9291 VT = LD->getMemoryVT();
9292 Ptr = LD->getBasePtr();
9293 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9294 VT = ST->getMemoryVT();
9295 Ptr = ST->getBasePtr();
9300 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9302 // Post-indexing updates the base, so it's not a valid transform
9303 // if that's not the same as the load's pointer.
9306 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9310 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9311 SelectionDAG &DAG) {
9313 SDValue Op = N->getOperand(0);
9315 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9319 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9320 DAG.getUNDEF(MVT::i32), Op,
9321 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9323 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9324 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9327 void AArch64TargetLowering::ReplaceNodeResults(
9328 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9329 switch (N->getOpcode()) {
9331 llvm_unreachable("Don't know how to custom expand this");
9333 ReplaceBITCASTResults(N, Results, DAG);
9335 case ISD::FP_TO_UINT:
9336 case ISD::FP_TO_SINT:
9337 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9338 // Let normal code take care of it by not adding anything to Results.
9343 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9347 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9348 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9349 // reciprocal if there are three or more FDIVs.
9353 TargetLoweringBase::LegalizeTypeAction
9354 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9355 MVT SVT = VT.getSimpleVT();
9356 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9357 // v4i16, v2i32 instead of to promote.
9358 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9359 || SVT == MVT::v1f32)
9360 return TypeWidenVector;
9362 return TargetLoweringBase::getPreferredVectorAction(VT);
9365 // Loads and stores less than 128-bits are already atomic; ones above that
9366 // are doomed anyway, so defer to the default libcall and blame the OS when
9368 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9369 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9373 // Loads and stores less than 128-bits are already atomic; ones above that
9374 // are doomed anyway, so defer to the default libcall and blame the OS when
9376 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9377 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9381 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9382 TargetLoweringBase::AtomicRMWExpansionKind
9383 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9384 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9385 return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9386 : AtomicRMWExpansionKind::None;
9389 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9393 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9394 AtomicOrdering Ord) const {
9395 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9396 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9397 bool IsAcquire = isAtLeastAcquire(Ord);
9399 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9400 // intrinsic must return {i64, i64} and we have to recombine them into a
9401 // single i128 here.
9402 if (ValTy->getPrimitiveSizeInBits() == 128) {
9404 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9405 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9407 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9408 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9410 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9411 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9412 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9413 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9414 return Builder.CreateOr(
9415 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9418 Type *Tys[] = { Addr->getType() };
9420 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9421 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9423 return Builder.CreateTruncOrBitCast(
9424 Builder.CreateCall(Ldxr, Addr),
9425 cast<PointerType>(Addr->getType())->getElementType());
9428 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9429 Value *Val, Value *Addr,
9430 AtomicOrdering Ord) const {
9431 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9432 bool IsRelease = isAtLeastRelease(Ord);
9434 // Since the intrinsics must have legal type, the i128 intrinsics take two
9435 // parameters: "i64, i64". We must marshal Val into the appropriate form
9437 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9439 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9440 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9441 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9443 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9444 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9445 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9446 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9450 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9451 Type *Tys[] = { Addr->getType() };
9452 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9454 return Builder.CreateCall(Stxr,
9455 {Builder.CreateZExtOrBitCast(
9456 Val, Stxr->getFunctionType()->getParamType(0)),
9460 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9461 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9462 return Ty->isArrayTy();
9465 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,