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");
44 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
45 cl::desc("Allow AArch64 SLI/SRI formation"),
48 // FIXME: The necessary dtprel relocations don't seem to be supported
49 // well in the GNU bfd and gold linkers at the moment. Therefore, by
50 // default, for now, fall back to GeneralDynamic code generation.
51 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
52 "aarch64-elf-ldtls-generation", cl::Hidden,
53 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
56 /// Value type used for condition codes.
57 static const MVT MVT_CC = MVT::i32;
59 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
60 const AArch64Subtarget &STI)
61 : TargetLowering(TM), Subtarget(&STI) {
63 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
64 // we have to make something up. Arbitrarily, choose ZeroOrOne.
65 setBooleanContents(ZeroOrOneBooleanContent);
66 // When comparing vectors the result sets the different elements in the
67 // vector to all-one or all-zero.
68 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
70 // Set up the register classes.
71 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
72 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
74 if (Subtarget->hasFPARMv8()) {
75 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
76 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
77 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
78 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
81 if (Subtarget->hasNEON()) {
82 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
83 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
84 // Someone set us up the NEON.
85 addDRTypeForNEON(MVT::v2f32);
86 addDRTypeForNEON(MVT::v8i8);
87 addDRTypeForNEON(MVT::v4i16);
88 addDRTypeForNEON(MVT::v2i32);
89 addDRTypeForNEON(MVT::v1i64);
90 addDRTypeForNEON(MVT::v1f64);
91 addDRTypeForNEON(MVT::v4f16);
93 addQRTypeForNEON(MVT::v4f32);
94 addQRTypeForNEON(MVT::v2f64);
95 addQRTypeForNEON(MVT::v16i8);
96 addQRTypeForNEON(MVT::v8i16);
97 addQRTypeForNEON(MVT::v4i32);
98 addQRTypeForNEON(MVT::v2i64);
99 addQRTypeForNEON(MVT::v8f16);
102 // Compute derived properties from the register classes
103 computeRegisterProperties(Subtarget->getRegisterInfo());
105 // Provide all sorts of operation actions
106 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
107 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
108 setOperationAction(ISD::SETCC, MVT::i32, Custom);
109 setOperationAction(ISD::SETCC, MVT::i64, Custom);
110 setOperationAction(ISD::SETCC, MVT::f32, Custom);
111 setOperationAction(ISD::SETCC, MVT::f64, Custom);
112 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
113 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
114 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
115 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
116 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
117 setOperationAction(ISD::SELECT, MVT::i32, Custom);
118 setOperationAction(ISD::SELECT, MVT::i64, Custom);
119 setOperationAction(ISD::SELECT, MVT::f32, Custom);
120 setOperationAction(ISD::SELECT, MVT::f64, Custom);
121 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
122 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
123 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
124 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
125 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
126 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
128 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
129 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
130 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
132 setOperationAction(ISD::FREM, MVT::f32, Expand);
133 setOperationAction(ISD::FREM, MVT::f64, Expand);
134 setOperationAction(ISD::FREM, MVT::f80, Expand);
136 // Custom lowering hooks are needed for XOR
137 // to fold it into CSINC/CSINV.
138 setOperationAction(ISD::XOR, MVT::i32, Custom);
139 setOperationAction(ISD::XOR, MVT::i64, Custom);
141 // Virtually no operation on f128 is legal, but LLVM can't expand them when
142 // there's a valid register class, so we need custom operations in most cases.
143 setOperationAction(ISD::FABS, MVT::f128, Expand);
144 setOperationAction(ISD::FADD, MVT::f128, Custom);
145 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
146 setOperationAction(ISD::FCOS, MVT::f128, Expand);
147 setOperationAction(ISD::FDIV, MVT::f128, Custom);
148 setOperationAction(ISD::FMA, MVT::f128, Expand);
149 setOperationAction(ISD::FMUL, MVT::f128, Custom);
150 setOperationAction(ISD::FNEG, MVT::f128, Expand);
151 setOperationAction(ISD::FPOW, MVT::f128, Expand);
152 setOperationAction(ISD::FREM, MVT::f128, Expand);
153 setOperationAction(ISD::FRINT, MVT::f128, Expand);
154 setOperationAction(ISD::FSIN, MVT::f128, Expand);
155 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
156 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
157 setOperationAction(ISD::FSUB, MVT::f128, Custom);
158 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
159 setOperationAction(ISD::SETCC, MVT::f128, Custom);
160 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
161 setOperationAction(ISD::SELECT, MVT::f128, Custom);
162 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
163 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
165 // Lowering for many of the conversions is actually specified by the non-f128
166 // type. The LowerXXX function will be trivial when f128 isn't involved.
167 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
168 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
169 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
170 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
171 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
172 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
173 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
174 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
175 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
176 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
177 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
178 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
179 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
180 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
182 // Variable arguments.
183 setOperationAction(ISD::VASTART, MVT::Other, Custom);
184 setOperationAction(ISD::VAARG, MVT::Other, Custom);
185 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
186 setOperationAction(ISD::VAEND, MVT::Other, Expand);
188 // Variable-sized objects.
189 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
190 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
191 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
193 // Constant pool entries
194 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
197 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
199 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
200 setOperationAction(ISD::ADDC, MVT::i32, Custom);
201 setOperationAction(ISD::ADDE, MVT::i32, Custom);
202 setOperationAction(ISD::SUBC, MVT::i32, Custom);
203 setOperationAction(ISD::SUBE, MVT::i32, Custom);
204 setOperationAction(ISD::ADDC, MVT::i64, Custom);
205 setOperationAction(ISD::ADDE, MVT::i64, Custom);
206 setOperationAction(ISD::SUBC, MVT::i64, Custom);
207 setOperationAction(ISD::SUBE, MVT::i64, Custom);
209 // AArch64 lacks both left-rotate and popcount instructions.
210 setOperationAction(ISD::ROTL, MVT::i32, Expand);
211 setOperationAction(ISD::ROTL, MVT::i64, Expand);
212 for (MVT VT : MVT::vector_valuetypes()) {
213 setOperationAction(ISD::ROTL, VT, Expand);
214 setOperationAction(ISD::ROTR, VT, Expand);
217 // AArch64 doesn't have {U|S}MUL_LOHI.
218 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
219 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
222 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
223 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
225 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
226 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
227 for (MVT VT : MVT::vector_valuetypes()) {
228 setOperationAction(ISD::SDIVREM, VT, Expand);
229 setOperationAction(ISD::UDIVREM, VT, Expand);
231 setOperationAction(ISD::SREM, MVT::i32, Expand);
232 setOperationAction(ISD::SREM, MVT::i64, Expand);
233 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
234 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
235 setOperationAction(ISD::UREM, MVT::i32, Expand);
236 setOperationAction(ISD::UREM, MVT::i64, Expand);
238 // Custom lower Add/Sub/Mul with overflow.
239 setOperationAction(ISD::SADDO, MVT::i32, Custom);
240 setOperationAction(ISD::SADDO, MVT::i64, Custom);
241 setOperationAction(ISD::UADDO, MVT::i32, Custom);
242 setOperationAction(ISD::UADDO, MVT::i64, Custom);
243 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
244 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
245 setOperationAction(ISD::USUBO, MVT::i32, Custom);
246 setOperationAction(ISD::USUBO, MVT::i64, Custom);
247 setOperationAction(ISD::SMULO, MVT::i32, Custom);
248 setOperationAction(ISD::SMULO, MVT::i64, Custom);
249 setOperationAction(ISD::UMULO, MVT::i32, Custom);
250 setOperationAction(ISD::UMULO, MVT::i64, Custom);
252 setOperationAction(ISD::FSIN, MVT::f32, Expand);
253 setOperationAction(ISD::FSIN, MVT::f64, Expand);
254 setOperationAction(ISD::FCOS, MVT::f32, Expand);
255 setOperationAction(ISD::FCOS, MVT::f64, Expand);
256 setOperationAction(ISD::FPOW, MVT::f32, Expand);
257 setOperationAction(ISD::FPOW, MVT::f64, Expand);
258 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
259 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
261 // f16 is a storage-only type, always promote it to f32.
262 setOperationAction(ISD::SETCC, MVT::f16, Promote);
263 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
264 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
265 setOperationAction(ISD::SELECT, MVT::f16, Promote);
266 setOperationAction(ISD::FADD, MVT::f16, Promote);
267 setOperationAction(ISD::FSUB, MVT::f16, Promote);
268 setOperationAction(ISD::FMUL, MVT::f16, Promote);
269 setOperationAction(ISD::FDIV, MVT::f16, Promote);
270 setOperationAction(ISD::FREM, MVT::f16, Promote);
271 setOperationAction(ISD::FMA, MVT::f16, Promote);
272 setOperationAction(ISD::FNEG, MVT::f16, Promote);
273 setOperationAction(ISD::FABS, MVT::f16, Promote);
274 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
275 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
276 setOperationAction(ISD::FCOS, MVT::f16, Promote);
277 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
278 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
279 setOperationAction(ISD::FPOW, MVT::f16, Promote);
280 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
281 setOperationAction(ISD::FRINT, MVT::f16, Promote);
282 setOperationAction(ISD::FSIN, MVT::f16, Promote);
283 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
284 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
285 setOperationAction(ISD::FEXP, MVT::f16, Promote);
286 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
287 setOperationAction(ISD::FLOG, MVT::f16, Promote);
288 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
289 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
290 setOperationAction(ISD::FROUND, MVT::f16, Promote);
291 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
292 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
293 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
294 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
295 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
297 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
299 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
300 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
301 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
302 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
303 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
304 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
305 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
306 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
307 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
308 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
309 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
310 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
312 // Expand all other v4f16 operations.
313 // FIXME: We could generate better code by promoting some operations to
315 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
316 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
317 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
318 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
319 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
320 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
321 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
322 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
323 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
324 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
325 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
326 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
327 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
328 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
330 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
331 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
332 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
333 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
334 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
335 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
336 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
337 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
338 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
339 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
340 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
343 // v8f16 is also a storage-only type, so expand it.
344 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
345 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
346 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
347 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
348 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
349 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
350 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
351 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
352 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
353 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
354 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
355 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
356 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
357 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
358 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
359 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
360 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
363 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
364 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
365 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
366 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
367 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
368 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
369 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
370 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
371 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
372 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
373 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
374 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
376 // AArch64 has implementations of a lot of rounding-like FP operations.
377 for (MVT Ty : {MVT::f32, MVT::f64}) {
378 setOperationAction(ISD::FFLOOR, Ty, Legal);
379 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
380 setOperationAction(ISD::FCEIL, Ty, Legal);
381 setOperationAction(ISD::FRINT, Ty, Legal);
382 setOperationAction(ISD::FTRUNC, Ty, Legal);
383 setOperationAction(ISD::FROUND, Ty, Legal);
384 setOperationAction(ISD::FMINNUM, Ty, Legal);
385 setOperationAction(ISD::FMAXNUM, Ty, Legal);
386 setOperationAction(ISD::FMINNAN, Ty, Legal);
387 setOperationAction(ISD::FMAXNAN, Ty, Legal);
390 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
392 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
394 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
395 // This requires the Performance Monitors extension.
396 if (Subtarget->hasPerfMon())
397 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
399 if (Subtarget->isTargetMachO()) {
400 // For iOS, we don't want to the normal expansion of a libcall to
401 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
403 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
404 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
406 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
407 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
410 // Make floating-point constants legal for the large code model, so they don't
411 // become loads from the constant pool.
412 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
413 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
414 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
417 // AArch64 does not have floating-point extending loads, i1 sign-extending
418 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
419 for (MVT VT : MVT::fp_valuetypes()) {
420 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
421 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
422 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
425 for (MVT VT : MVT::integer_valuetypes())
426 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
428 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
429 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
430 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
431 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
432 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
433 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
434 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
436 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
437 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
439 // Indexed loads and stores are supported.
440 for (unsigned im = (unsigned)ISD::PRE_INC;
441 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
442 setIndexedLoadAction(im, MVT::i8, Legal);
443 setIndexedLoadAction(im, MVT::i16, Legal);
444 setIndexedLoadAction(im, MVT::i32, Legal);
445 setIndexedLoadAction(im, MVT::i64, Legal);
446 setIndexedLoadAction(im, MVT::f64, Legal);
447 setIndexedLoadAction(im, MVT::f32, Legal);
448 setIndexedLoadAction(im, MVT::f16, Legal);
449 setIndexedStoreAction(im, MVT::i8, Legal);
450 setIndexedStoreAction(im, MVT::i16, Legal);
451 setIndexedStoreAction(im, MVT::i32, Legal);
452 setIndexedStoreAction(im, MVT::i64, Legal);
453 setIndexedStoreAction(im, MVT::f64, Legal);
454 setIndexedStoreAction(im, MVT::f32, Legal);
455 setIndexedStoreAction(im, MVT::f16, Legal);
459 setOperationAction(ISD::TRAP, MVT::Other, Legal);
461 // We combine OR nodes for bitfield operations.
462 setTargetDAGCombine(ISD::OR);
464 // Vector add and sub nodes may conceal a high-half opportunity.
465 // Also, try to fold ADD into CSINC/CSINV..
466 setTargetDAGCombine(ISD::ADD);
467 setTargetDAGCombine(ISD::SUB);
468 setTargetDAGCombine(ISD::SRL);
469 setTargetDAGCombine(ISD::XOR);
470 setTargetDAGCombine(ISD::SINT_TO_FP);
471 setTargetDAGCombine(ISD::UINT_TO_FP);
473 setTargetDAGCombine(ISD::FP_TO_SINT);
474 setTargetDAGCombine(ISD::FP_TO_UINT);
475 setTargetDAGCombine(ISD::FDIV);
477 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
479 setTargetDAGCombine(ISD::ANY_EXTEND);
480 setTargetDAGCombine(ISD::ZERO_EXTEND);
481 setTargetDAGCombine(ISD::SIGN_EXTEND);
482 setTargetDAGCombine(ISD::BITCAST);
483 setTargetDAGCombine(ISD::CONCAT_VECTORS);
484 setTargetDAGCombine(ISD::STORE);
485 if (Subtarget->supportsAddressTopByteIgnored())
486 setTargetDAGCombine(ISD::LOAD);
488 setTargetDAGCombine(ISD::MUL);
490 setTargetDAGCombine(ISD::SELECT);
491 setTargetDAGCombine(ISD::VSELECT);
493 setTargetDAGCombine(ISD::INTRINSIC_VOID);
494 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
495 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
496 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
498 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
499 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
500 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
502 setStackPointerRegisterToSaveRestore(AArch64::SP);
504 setSchedulingPreference(Sched::Hybrid);
507 MaskAndBranchFoldingIsLegal = true;
508 EnableExtLdPromotion = true;
510 // Set required alignment.
511 setMinFunctionAlignment(2);
512 // Set preferred alignments.
513 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
514 setPrefLoopAlignment(STI.getPrefLoopAlignment());
516 // Only change the limit for entries in a jump table if specified by
517 // the subtarget, but not at the command line.
518 unsigned MaxJT = STI.getMaximumJumpTableSize();
519 if (MaxJT && getMaximumJumpTableSize() == 0)
520 setMaximumJumpTableSize(MaxJT);
522 setHasExtractBitsInsn(true);
524 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
526 if (Subtarget->hasNEON()) {
527 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
528 // silliness like this:
529 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
530 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
531 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
532 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
533 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
534 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
535 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
536 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
537 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
538 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
539 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
540 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
541 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
542 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
543 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
544 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
545 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
546 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
547 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
548 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
549 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
550 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
551 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
552 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
553 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
555 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
556 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
557 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
559 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
561 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
563 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
564 // elements smaller than i32, so promote the input to i32 first.
565 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
566 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
567 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
569 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
570 // -> v8f16 conversions.
571 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
572 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
573 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
574 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
575 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
576 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
577 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
578 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
579 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
580 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
581 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
582 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
585 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
586 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
588 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
589 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
590 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
591 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
592 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
593 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
594 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
595 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
597 // AArch64 doesn't have MUL.2d:
598 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
599 // Custom handling for some quad-vector types to detect MULL.
600 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
601 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
602 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
604 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
605 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
606 // Likewise, narrowing and extending vector loads/stores aren't handled
608 for (MVT VT : MVT::vector_valuetypes()) {
609 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
611 setOperationAction(ISD::MULHS, VT, Expand);
612 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
613 setOperationAction(ISD::MULHU, VT, Expand);
614 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
616 setOperationAction(ISD::BSWAP, VT, Expand);
618 for (MVT InnerVT : MVT::vector_valuetypes()) {
619 setTruncStoreAction(VT, InnerVT, Expand);
620 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
621 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
622 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
626 // AArch64 has implementations of a lot of rounding-like FP operations.
627 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
628 setOperationAction(ISD::FFLOOR, Ty, Legal);
629 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
630 setOperationAction(ISD::FCEIL, Ty, Legal);
631 setOperationAction(ISD::FRINT, Ty, Legal);
632 setOperationAction(ISD::FTRUNC, Ty, Legal);
633 setOperationAction(ISD::FROUND, Ty, Legal);
637 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
640 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
641 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
642 setOperationAction(ISD::LOAD, VT, Promote);
643 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
645 setOperationAction(ISD::STORE, VT, Promote);
646 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
647 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
648 setOperationAction(ISD::LOAD, VT, Promote);
649 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
651 setOperationAction(ISD::STORE, VT, Promote);
652 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
655 // Mark vector float intrinsics as expand.
656 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
657 setOperationAction(ISD::FSIN, VT, Expand);
658 setOperationAction(ISD::FCOS, VT, Expand);
659 setOperationAction(ISD::FPOWI, VT, Expand);
660 setOperationAction(ISD::FPOW, VT, Expand);
661 setOperationAction(ISD::FLOG, VT, Expand);
662 setOperationAction(ISD::FLOG2, VT, Expand);
663 setOperationAction(ISD::FLOG10, VT, Expand);
664 setOperationAction(ISD::FEXP, VT, Expand);
665 setOperationAction(ISD::FEXP2, VT, Expand);
667 // But we do support custom-lowering for FCOPYSIGN.
668 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
672 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
673 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
675 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
676 setOperationAction(ISD::SRA, VT, Custom);
677 setOperationAction(ISD::SRL, VT, Custom);
678 setOperationAction(ISD::SHL, VT, Custom);
679 setOperationAction(ISD::AND, VT, Custom);
680 setOperationAction(ISD::OR, VT, Custom);
681 setOperationAction(ISD::SETCC, VT, Custom);
682 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
684 setOperationAction(ISD::SELECT, VT, Expand);
685 setOperationAction(ISD::SELECT_CC, VT, Expand);
686 setOperationAction(ISD::VSELECT, VT, Expand);
687 for (MVT InnerVT : MVT::all_valuetypes())
688 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
690 // CNT supports only B element sizes.
691 if (VT != MVT::v8i8 && VT != MVT::v16i8)
692 setOperationAction(ISD::CTPOP, VT, Expand);
694 setOperationAction(ISD::UDIV, VT, Expand);
695 setOperationAction(ISD::SDIV, VT, Expand);
696 setOperationAction(ISD::UREM, VT, Expand);
697 setOperationAction(ISD::SREM, VT, Expand);
698 setOperationAction(ISD::FREM, VT, Expand);
700 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
701 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
703 // [SU][MIN|MAX] are available for all NEON types apart from i64.
704 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
705 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
706 setOperationAction(Opcode, VT, Legal);
708 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
709 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
710 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
711 ISD::FMINNUM, ISD::FMAXNUM})
712 setOperationAction(Opcode, VT, Legal);
714 if (Subtarget->isLittleEndian()) {
715 for (unsigned im = (unsigned)ISD::PRE_INC;
716 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
717 setIndexedLoadAction(im, VT, Legal);
718 setIndexedStoreAction(im, VT, Legal);
723 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
724 addRegisterClass(VT, &AArch64::FPR64RegClass);
725 addTypeForNEON(VT, MVT::v2i32);
728 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
729 addRegisterClass(VT, &AArch64::FPR128RegClass);
730 addTypeForNEON(VT, MVT::v4i32);
733 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
737 return VT.changeVectorElementTypeToInteger();
740 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
741 /// Mask are known to be either zero or one and return them in the
742 /// KnownZero/KnownOne bitsets.
743 void AArch64TargetLowering::computeKnownBitsForTargetNode(
744 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
745 const SelectionDAG &DAG, unsigned Depth) const {
746 switch (Op.getOpcode()) {
749 case AArch64ISD::CSEL: {
750 APInt KnownZero2, KnownOne2;
751 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
752 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
753 KnownZero &= KnownZero2;
754 KnownOne &= KnownOne2;
757 case ISD::INTRINSIC_W_CHAIN: {
758 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
759 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
762 case Intrinsic::aarch64_ldaxr:
763 case Intrinsic::aarch64_ldxr: {
764 unsigned BitWidth = KnownOne.getBitWidth();
765 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
766 unsigned MemBits = VT.getScalarSizeInBits();
767 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
773 case ISD::INTRINSIC_WO_CHAIN:
774 case ISD::INTRINSIC_VOID: {
775 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
779 case Intrinsic::aarch64_neon_umaxv:
780 case Intrinsic::aarch64_neon_uminv: {
781 // Figure out the datatype of the vector operand. The UMINV instruction
782 // will zero extend the result, so we can mark as known zero all the
783 // bits larger than the element datatype. 32-bit or larget doesn't need
784 // this as those are legal types and will be handled by isel directly.
785 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
786 unsigned BitWidth = KnownZero.getBitWidth();
787 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
788 assert(BitWidth >= 8 && "Unexpected width!");
789 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
791 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
792 assert(BitWidth >= 16 && "Unexpected width!");
793 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
803 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
808 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
812 if (Subtarget->requiresStrictAlign())
816 // Some CPUs are fine with unaligned stores except for 128-bit ones.
817 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
818 // See comments in performSTORECombine() for more details about
821 // Code that uses clang vector extensions can mark that it
822 // wants unaligned accesses to be treated as fast by
823 // underspecifying alignment to be 1 or 2.
826 // Disregard v2i64. Memcpy lowering produces those and splitting
827 // them regresses performance on micro-benchmarks and olden/bh.
834 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
835 const TargetLibraryInfo *libInfo) const {
836 return AArch64::createFastISel(funcInfo, libInfo);
839 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
840 switch ((AArch64ISD::NodeType)Opcode) {
841 case AArch64ISD::FIRST_NUMBER: break;
842 case AArch64ISD::CALL: return "AArch64ISD::CALL";
843 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
844 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
845 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
846 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
847 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
848 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
849 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
850 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
851 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
852 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
853 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
854 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
855 case AArch64ISD::ADC: return "AArch64ISD::ADC";
856 case AArch64ISD::SBC: return "AArch64ISD::SBC";
857 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
858 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
859 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
860 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
861 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
862 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
863 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
864 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
865 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
866 case AArch64ISD::DUP: return "AArch64ISD::DUP";
867 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
868 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
869 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
870 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
871 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
872 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
873 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
874 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
875 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
876 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
877 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
878 case AArch64ISD::BICi: return "AArch64ISD::BICi";
879 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
880 case AArch64ISD::BSL: return "AArch64ISD::BSL";
881 case AArch64ISD::NEG: return "AArch64ISD::NEG";
882 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
883 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
884 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
885 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
886 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
887 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
888 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
889 case AArch64ISD::REV16: return "AArch64ISD::REV16";
890 case AArch64ISD::REV32: return "AArch64ISD::REV32";
891 case AArch64ISD::REV64: return "AArch64ISD::REV64";
892 case AArch64ISD::EXT: return "AArch64ISD::EXT";
893 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
894 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
895 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
896 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
897 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
898 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
899 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
900 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
901 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
902 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
903 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
904 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
905 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
906 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
907 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
908 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
909 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
910 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
911 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
912 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
913 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
914 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
915 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
916 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
917 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
918 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
919 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
920 case AArch64ISD::NOT: return "AArch64ISD::NOT";
921 case AArch64ISD::BIT: return "AArch64ISD::BIT";
922 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
923 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
924 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
925 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
926 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
927 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
928 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
929 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
930 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
931 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
932 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
933 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
934 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
935 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
936 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
937 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
938 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
939 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
940 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
941 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
942 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
943 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
944 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
945 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
946 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
947 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
948 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
949 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
950 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
951 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
952 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
953 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
954 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
955 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
956 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
957 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
958 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
959 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
960 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
961 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
962 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
963 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
964 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
965 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
971 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
972 MachineBasicBlock *MBB) const {
973 // We materialise the F128CSEL pseudo-instruction as some control flow and a
977 // [... previous instrs leading to comparison ...]
983 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
985 MachineFunction *MF = MBB->getParent();
986 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
987 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
988 DebugLoc DL = MI.getDebugLoc();
989 MachineFunction::iterator It = ++MBB->getIterator();
991 unsigned DestReg = MI.getOperand(0).getReg();
992 unsigned IfTrueReg = MI.getOperand(1).getReg();
993 unsigned IfFalseReg = MI.getOperand(2).getReg();
994 unsigned CondCode = MI.getOperand(3).getImm();
995 bool NZCVKilled = MI.getOperand(4).isKill();
997 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
998 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
999 MF->insert(It, TrueBB);
1000 MF->insert(It, EndBB);
1002 // Transfer rest of current basic-block to EndBB
1003 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1005 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1007 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1008 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1009 MBB->addSuccessor(TrueBB);
1010 MBB->addSuccessor(EndBB);
1012 // TrueBB falls through to the end.
1013 TrueBB->addSuccessor(EndBB);
1016 TrueBB->addLiveIn(AArch64::NZCV);
1017 EndBB->addLiveIn(AArch64::NZCV);
1020 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1026 MI.eraseFromParent();
1030 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1031 MachineInstr &MI, MachineBasicBlock *BB) const {
1032 switch (MI.getOpcode()) {
1037 llvm_unreachable("Unexpected instruction for custom inserter!");
1039 case AArch64::F128CSEL:
1040 return EmitF128CSEL(MI, BB);
1042 case TargetOpcode::STACKMAP:
1043 case TargetOpcode::PATCHPOINT:
1044 return emitPatchPoint(MI, BB);
1048 //===----------------------------------------------------------------------===//
1049 // AArch64 Lowering private implementation.
1050 //===----------------------------------------------------------------------===//
1052 //===----------------------------------------------------------------------===//
1054 //===----------------------------------------------------------------------===//
1056 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1058 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1061 llvm_unreachable("Unknown condition code!");
1063 return AArch64CC::NE;
1065 return AArch64CC::EQ;
1067 return AArch64CC::GT;
1069 return AArch64CC::GE;
1071 return AArch64CC::LT;
1073 return AArch64CC::LE;
1075 return AArch64CC::HI;
1077 return AArch64CC::HS;
1079 return AArch64CC::LO;
1081 return AArch64CC::LS;
1085 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1086 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1087 AArch64CC::CondCode &CondCode,
1088 AArch64CC::CondCode &CondCode2) {
1089 CondCode2 = AArch64CC::AL;
1092 llvm_unreachable("Unknown FP condition!");
1095 CondCode = AArch64CC::EQ;
1099 CondCode = AArch64CC::GT;
1103 CondCode = AArch64CC::GE;
1106 CondCode = AArch64CC::MI;
1109 CondCode = AArch64CC::LS;
1112 CondCode = AArch64CC::MI;
1113 CondCode2 = AArch64CC::GT;
1116 CondCode = AArch64CC::VC;
1119 CondCode = AArch64CC::VS;
1122 CondCode = AArch64CC::EQ;
1123 CondCode2 = AArch64CC::VS;
1126 CondCode = AArch64CC::HI;
1129 CondCode = AArch64CC::PL;
1133 CondCode = AArch64CC::LT;
1137 CondCode = AArch64CC::LE;
1141 CondCode = AArch64CC::NE;
1146 /// Convert a DAG fp condition code to an AArch64 CC.
1147 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1148 /// should be AND'ed instead of OR'ed.
1149 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1150 AArch64CC::CondCode &CondCode,
1151 AArch64CC::CondCode &CondCode2) {
1152 CondCode2 = AArch64CC::AL;
1155 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1156 assert(CondCode2 == AArch64CC::AL);
1160 // == ((a olt b) || (a ogt b))
1161 // == ((a ord b) && (a une b))
1162 CondCode = AArch64CC::VC;
1163 CondCode2 = AArch64CC::NE;
1167 // == ((a uno b) || (a oeq b))
1168 // == ((a ule b) && (a uge b))
1169 CondCode = AArch64CC::PL;
1170 CondCode2 = AArch64CC::LE;
1175 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1176 /// CC usable with the vector instructions. Fewer operations are available
1177 /// without a real NZCV register, so we have to use less efficient combinations
1178 /// to get the same effect.
1179 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1180 AArch64CC::CondCode &CondCode,
1181 AArch64CC::CondCode &CondCode2,
1186 // Mostly the scalar mappings work fine.
1187 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1193 CondCode = AArch64CC::MI;
1194 CondCode2 = AArch64CC::GE;
1201 // All of the compare-mask comparisons are ordered, but we can switch
1202 // between the two by a double inversion. E.g. ULE == !OGT.
1204 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1209 static bool isLegalArithImmed(uint64_t C) {
1210 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1211 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1214 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1215 const SDLoc &dl, SelectionDAG &DAG) {
1216 EVT VT = LHS.getValueType();
1218 if (VT.isFloatingPoint()) {
1219 assert(VT != MVT::f128);
1220 if (VT == MVT::f16) {
1221 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1222 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1225 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1228 // The CMP instruction is just an alias for SUBS, and representing it as
1229 // SUBS means that it's possible to get CSE with subtract operations.
1230 // A later phase can perform the optimization of setting the destination
1231 // register to WZR/XZR if it ends up being unused.
1232 unsigned Opcode = AArch64ISD::SUBS;
1234 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1235 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1236 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1237 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1238 // can be set differently by this operation. It comes down to whether
1239 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1240 // everything is fine. If not then the optimization is wrong. Thus general
1241 // comparisons are only valid if op2 != 0.
1243 // So, finally, the only LLVM-native comparisons that don't mention C and V
1244 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1245 // the absence of information about op2.
1246 Opcode = AArch64ISD::ADDS;
1247 RHS = RHS.getOperand(1);
1248 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1249 !isUnsignedIntSetCC(CC)) {
1250 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1251 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1252 // of the signed comparisons.
1253 Opcode = AArch64ISD::ANDS;
1254 RHS = LHS.getOperand(1);
1255 LHS = LHS.getOperand(0);
1258 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1262 /// \defgroup AArch64CCMP CMP;CCMP matching
1264 /// These functions deal with the formation of CMP;CCMP;... sequences.
1265 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1266 /// a comparison. They set the NZCV flags to a predefined value if their
1267 /// predicate is false. This allows to express arbitrary conjunctions, for
1268 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1271 /// ccmp B, inv(CB), CA
1272 /// check for CB flags
1274 /// In general we can create code for arbitrary "... (and (and A B) C)"
1275 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1276 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1277 /// negation operations:
1278 /// We can negate the results of a single comparison by inverting the flags
1279 /// used when the predicate fails and inverting the flags tested in the next
1280 /// instruction; We can also negate the results of the whole previous
1281 /// conditional compare sequence by inverting the flags tested in the next
1282 /// instruction. However there is no way to negate the result of a partial
1285 /// Therefore on encountering an "or" expression we can negate the subtree on
1286 /// one side and have to be able to push the negate to the leafs of the subtree
1287 /// on the other side (see also the comments in code). As complete example:
1288 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1289 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1290 /// is transformed to
1291 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1292 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1293 /// and implemented as:
1295 /// ccmp D, inv(CD), CC
1296 /// ccmp A, CA, inv(CD)
1297 /// ccmp B, CB, inv(CA)
1298 /// check for CB flags
1299 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1300 /// by conditional compare sequences.
1303 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1304 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1305 ISD::CondCode CC, SDValue CCOp,
1306 AArch64CC::CondCode Predicate,
1307 AArch64CC::CondCode OutCC,
1308 const SDLoc &DL, SelectionDAG &DAG) {
1309 unsigned Opcode = 0;
1310 if (LHS.getValueType().isFloatingPoint()) {
1311 assert(LHS.getValueType() != MVT::f128);
1312 if (LHS.getValueType() == MVT::f16) {
1313 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1314 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1316 Opcode = AArch64ISD::FCCMP;
1317 } else if (RHS.getOpcode() == ISD::SUB) {
1318 SDValue SubOp0 = RHS.getOperand(0);
1319 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1320 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1321 Opcode = AArch64ISD::CCMN;
1322 RHS = RHS.getOperand(1);
1326 Opcode = AArch64ISD::CCMP;
1328 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1329 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1330 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1331 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1332 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1335 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1336 /// CanPushNegate is set to true if we can push a negate operation through
1337 /// the tree in a was that we are left with AND operations and negate operations
1338 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1339 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1340 /// brought into such a form.
1341 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1342 unsigned Depth = 0) {
1343 if (!Val.hasOneUse())
1345 unsigned Opcode = Val->getOpcode();
1346 if (Opcode == ISD::SETCC) {
1347 if (Val->getOperand(0).getValueType() == MVT::f128)
1352 // Protect against exponential runtime and stack overflow.
1355 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1356 SDValue O0 = Val->getOperand(0);
1357 SDValue O1 = Val->getOperand(1);
1359 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1362 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1365 if (Opcode == ISD::OR) {
1366 // For an OR expression we need to be able to negate at least one side or
1367 // we cannot do the transformation at all.
1368 if (!CanNegateL && !CanNegateR)
1370 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1371 // can negate the x and y subtrees.
1372 CanNegate = CanNegateL && CanNegateR;
1374 // If the operands are OR expressions then we finally need to negate their
1375 // outputs, we can only do that for the operand with emitted last by
1376 // negating OutCC, not for both operands.
1377 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1378 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1379 if (NeedsNegOutL && NeedsNegOutR)
1381 // We cannot negate an AND operation (it would become an OR),
1389 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1390 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1391 /// Tries to transform the given i1 producing node @p Val to a series compare
1392 /// and conditional compare operations. @returns an NZCV flags producing node
1393 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1394 /// transformation was not possible.
1395 /// On recursive invocations @p PushNegate may be set to true to have negation
1396 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1397 /// for the comparisons in the current subtree; @p Depth limits the search
1398 /// depth to avoid stack overflow.
1399 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1400 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1401 AArch64CC::CondCode Predicate) {
1402 // We're at a tree leaf, produce a conditional comparison operation.
1403 unsigned Opcode = Val->getOpcode();
1404 if (Opcode == ISD::SETCC) {
1405 SDValue LHS = Val->getOperand(0);
1406 SDValue RHS = Val->getOperand(1);
1407 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1408 bool isInteger = LHS.getValueType().isInteger();
1410 CC = getSetCCInverse(CC, isInteger);
1412 // Determine OutCC and handle FP special case.
1414 OutCC = changeIntCCToAArch64CC(CC);
1416 assert(LHS.getValueType().isFloatingPoint());
1417 AArch64CC::CondCode ExtraCC;
1418 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1419 // Some floating point conditions can't be tested with a single condition
1420 // code. Construct an additional comparison in this case.
1421 if (ExtraCC != AArch64CC::AL) {
1423 if (!CCOp.getNode())
1424 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1426 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1429 Predicate = ExtraCC;
1433 // Produce a normal comparison if we are first in the chain
1435 return emitComparison(LHS, RHS, CC, DL, DAG);
1436 // Otherwise produce a ccmp.
1437 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1440 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1441 "Valid conjunction/disjunction tree");
1443 // Check if both sides can be transformed.
1444 SDValue LHS = Val->getOperand(0);
1445 SDValue RHS = Val->getOperand(1);
1447 // In case of an OR we need to negate our operands and the result.
1448 // (A v B) <=> not(not(A) ^ not(B))
1449 bool NegateOpsAndResult = Opcode == ISD::OR;
1450 // We can negate the results of all previous operations by inverting the
1451 // predicate flags giving us a free negation for one side. The other side
1452 // must be negatable by itself.
1453 if (NegateOpsAndResult) {
1454 // See which side we can negate.
1456 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1457 assert(isValidL && "Valid conjunction/disjunction tree");
1462 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1463 assert(isValidR && "Valid conjunction/disjunction tree");
1464 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1467 // Order the side which we cannot negate to RHS so we can emit it first.
1469 std::swap(LHS, RHS);
1471 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1472 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1473 "Valid conjunction/disjunction tree");
1474 // Order the side where we need to negate the output flags to RHS so it
1475 // gets emitted first.
1477 std::swap(LHS, RHS);
1480 // Emit RHS. If we want to negate the tree we only need to push a negate
1481 // through if we are already in a PushNegate case, otherwise we can negate
1482 // the "flags to test" afterwards.
1483 AArch64CC::CondCode RHSCC;
1484 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1486 if (NegateOpsAndResult && !Negate)
1487 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1488 // Emit LHS. We may need to negate it.
1489 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1490 NegateOpsAndResult, CmpR,
1492 // If we transformed an OR to and AND then we have to negate the result
1493 // (or absorb the Negate parameter).
1494 if (NegateOpsAndResult && !Negate)
1495 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1499 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1500 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1501 /// \see emitConjunctionDisjunctionTreeRec().
1502 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1503 AArch64CC::CondCode &OutCC) {
1505 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1508 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1514 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1515 SDValue &AArch64cc, SelectionDAG &DAG,
1517 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1518 EVT VT = RHS.getValueType();
1519 uint64_t C = RHSC->getZExtValue();
1520 if (!isLegalArithImmed(C)) {
1521 // Constant does not fit, try adjusting it by one?
1527 if ((VT == MVT::i32 && C != 0x80000000 &&
1528 isLegalArithImmed((uint32_t)(C - 1))) ||
1529 (VT == MVT::i64 && C != 0x80000000ULL &&
1530 isLegalArithImmed(C - 1ULL))) {
1531 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1532 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1533 RHS = DAG.getConstant(C, dl, VT);
1538 if ((VT == MVT::i32 && C != 0 &&
1539 isLegalArithImmed((uint32_t)(C - 1))) ||
1540 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1541 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1542 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1543 RHS = DAG.getConstant(C, dl, VT);
1548 if ((VT == MVT::i32 && C != INT32_MAX &&
1549 isLegalArithImmed((uint32_t)(C + 1))) ||
1550 (VT == MVT::i64 && C != INT64_MAX &&
1551 isLegalArithImmed(C + 1ULL))) {
1552 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1553 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1554 RHS = DAG.getConstant(C, dl, VT);
1559 if ((VT == MVT::i32 && C != UINT32_MAX &&
1560 isLegalArithImmed((uint32_t)(C + 1))) ||
1561 (VT == MVT::i64 && C != UINT64_MAX &&
1562 isLegalArithImmed(C + 1ULL))) {
1563 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1564 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1565 RHS = DAG.getConstant(C, dl, VT);
1572 AArch64CC::CondCode AArch64CC;
1573 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1574 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1576 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1577 // For the i8 operand, the largest immediate is 255, so this can be easily
1578 // encoded in the compare instruction. For the i16 operand, however, the
1579 // largest immediate cannot be encoded in the compare.
1580 // Therefore, use a sign extending load and cmn to avoid materializing the
1581 // -1 constant. For example,
1583 // ldrh w0, [x0, #0]
1586 // ldrsh w0, [x0, #0]
1588 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1589 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1590 // ensure both the LHS and RHS are truly zero extended and to make sure the
1591 // transformation is profitable.
1592 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1593 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1594 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1595 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1596 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1597 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1599 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1600 DAG.getValueType(MVT::i16));
1601 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1602 RHS.getValueType()),
1604 AArch64CC = changeIntCCToAArch64CC(CC);
1608 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1609 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1610 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1611 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1617 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1618 AArch64CC = changeIntCCToAArch64CC(CC);
1620 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1624 static std::pair<SDValue, SDValue>
1625 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1626 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1627 "Unsupported value type");
1628 SDValue Value, Overflow;
1630 SDValue LHS = Op.getOperand(0);
1631 SDValue RHS = Op.getOperand(1);
1633 switch (Op.getOpcode()) {
1635 llvm_unreachable("Unknown overflow instruction!");
1637 Opc = AArch64ISD::ADDS;
1641 Opc = AArch64ISD::ADDS;
1645 Opc = AArch64ISD::SUBS;
1649 Opc = AArch64ISD::SUBS;
1652 // Multiply needs a little bit extra work.
1656 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1657 if (Op.getValueType() == MVT::i32) {
1658 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1659 // For a 32 bit multiply with overflow check we want the instruction
1660 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1661 // need to generate the following pattern:
1662 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1663 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1664 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1665 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1666 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1667 DAG.getConstant(0, DL, MVT::i64));
1668 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1669 // operation. We need to clear out the upper 32 bits, because we used a
1670 // widening multiply that wrote all 64 bits. In the end this should be a
1672 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1674 // The signed overflow check requires more than just a simple check for
1675 // any bit set in the upper 32 bits of the result. These bits could be
1676 // just the sign bits of a negative number. To perform the overflow
1677 // check we have to arithmetic shift right the 32nd bit of the result by
1678 // 31 bits. Then we compare the result to the upper 32 bits.
1679 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1680 DAG.getConstant(32, DL, MVT::i64));
1681 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1682 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1683 DAG.getConstant(31, DL, MVT::i64));
1684 // It is important that LowerBits is last, otherwise the arithmetic
1685 // shift will not be folded into the compare (SUBS).
1686 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1687 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1690 // The overflow check for unsigned multiply is easy. We only need to
1691 // check if any of the upper 32 bits are set. This can be done with a
1692 // CMP (shifted register). For that we need to generate the following
1694 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1695 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1696 DAG.getConstant(32, DL, MVT::i64));
1697 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1699 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1700 DAG.getConstant(0, DL, MVT::i64),
1701 UpperBits).getValue(1);
1705 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1706 // For the 64 bit multiply
1707 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1709 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1710 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1711 DAG.getConstant(63, DL, MVT::i64));
1712 // It is important that LowerBits is last, otherwise the arithmetic
1713 // shift will not be folded into the compare (SUBS).
1714 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1715 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1718 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1719 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1721 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1722 DAG.getConstant(0, DL, MVT::i64),
1723 UpperBits).getValue(1);
1730 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1732 // Emit the AArch64 operation with overflow check.
1733 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1734 Overflow = Value.getValue(1);
1736 return std::make_pair(Value, Overflow);
1739 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1740 RTLIB::Libcall Call) const {
1741 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1742 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1745 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1746 SDValue Sel = Op.getOperand(0);
1747 SDValue Other = Op.getOperand(1);
1749 // If neither operand is a SELECT_CC, give up.
1750 if (Sel.getOpcode() != ISD::SELECT_CC)
1751 std::swap(Sel, Other);
1752 if (Sel.getOpcode() != ISD::SELECT_CC)
1755 // The folding we want to perform is:
1756 // (xor x, (select_cc a, b, cc, 0, -1) )
1758 // (csel x, (xor x, -1), cc ...)
1760 // The latter will get matched to a CSINV instruction.
1762 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1763 SDValue LHS = Sel.getOperand(0);
1764 SDValue RHS = Sel.getOperand(1);
1765 SDValue TVal = Sel.getOperand(2);
1766 SDValue FVal = Sel.getOperand(3);
1769 // FIXME: This could be generalized to non-integer comparisons.
1770 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1773 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1774 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1776 // The values aren't constants, this isn't the pattern we're looking for.
1777 if (!CFVal || !CTVal)
1780 // We can commute the SELECT_CC by inverting the condition. This
1781 // might be needed to make this fit into a CSINV pattern.
1782 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1783 std::swap(TVal, FVal);
1784 std::swap(CTVal, CFVal);
1785 CC = ISD::getSetCCInverse(CC, true);
1788 // If the constants line up, perform the transform!
1789 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1791 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1794 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1795 DAG.getConstant(-1ULL, dl, Other.getValueType()));
1797 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1804 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1805 EVT VT = Op.getValueType();
1807 // Let legalize expand this if it isn't a legal type yet.
1808 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1811 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1814 bool ExtraOp = false;
1815 switch (Op.getOpcode()) {
1817 llvm_unreachable("Invalid code");
1819 Opc = AArch64ISD::ADDS;
1822 Opc = AArch64ISD::SUBS;
1825 Opc = AArch64ISD::ADCS;
1829 Opc = AArch64ISD::SBCS;
1835 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1836 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1840 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1841 // Let legalize expand this if it isn't a legal type yet.
1842 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1846 AArch64CC::CondCode CC;
1847 // The actual operation that sets the overflow or carry flag.
1848 SDValue Value, Overflow;
1849 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1851 // We use 0 and 1 as false and true values.
1852 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1853 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1855 // We use an inverted condition, because the conditional select is inverted
1856 // too. This will allow it to be selected to a single instruction:
1857 // CSINC Wd, WZR, WZR, invert(cond).
1858 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1859 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1862 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1863 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1866 // Prefetch operands are:
1867 // 1: Address to prefetch
1869 // 3: int locality (0 = no locality ... 3 = extreme locality)
1870 // 4: bool isDataCache
1871 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1873 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1874 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1875 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1877 bool IsStream = !Locality;
1878 // When the locality number is set
1880 // The front-end should have filtered out the out-of-range values
1881 assert(Locality <= 3 && "Prefetch locality out-of-range");
1882 // The locality degree is the opposite of the cache speed.
1883 // Put the number the other way around.
1884 // The encoding starts at 0 for level 1
1885 Locality = 3 - Locality;
1888 // built the mask value encoding the expected behavior.
1889 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1890 (!IsData << 3) | // IsDataCache bit
1891 (Locality << 1) | // Cache level bits
1892 (unsigned)IsStream; // Stream bit
1893 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1894 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1897 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1898 SelectionDAG &DAG) const {
1899 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1902 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1904 return LowerF128Call(Op, DAG, LC);
1907 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1908 SelectionDAG &DAG) const {
1909 if (Op.getOperand(0).getValueType() != MVT::f128) {
1910 // It's legal except when f128 is involved
1915 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1917 // FP_ROUND node has a second operand indicating whether it is known to be
1918 // precise. That doesn't take part in the LibCall so we can't directly use
1920 SDValue SrcVal = Op.getOperand(0);
1921 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1925 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1926 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1927 // Any additional optimization in this function should be recorded
1928 // in the cost tables.
1929 EVT InVT = Op.getOperand(0).getValueType();
1930 EVT VT = Op.getValueType();
1931 unsigned NumElts = InVT.getVectorNumElements();
1933 // f16 vectors are promoted to f32 before a conversion.
1934 if (InVT.getVectorElementType() == MVT::f16) {
1935 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1938 Op.getOpcode(), dl, Op.getValueType(),
1939 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1942 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1945 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1947 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1950 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1953 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1954 VT.getVectorNumElements());
1955 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1956 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1959 // Type changing conversions are illegal.
1963 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1964 SelectionDAG &DAG) const {
1965 if (Op.getOperand(0).getValueType().isVector())
1966 return LowerVectorFP_TO_INT(Op, DAG);
1968 // f16 conversions are promoted to f32.
1969 if (Op.getOperand(0).getValueType() == MVT::f16) {
1972 Op.getOpcode(), dl, Op.getValueType(),
1973 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1976 if (Op.getOperand(0).getValueType() != MVT::f128) {
1977 // It's legal except when f128 is involved
1982 if (Op.getOpcode() == ISD::FP_TO_SINT)
1983 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1985 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1987 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1988 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1991 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1992 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1993 // Any additional optimization in this function should be recorded
1994 // in the cost tables.
1995 EVT VT = Op.getValueType();
1997 SDValue In = Op.getOperand(0);
1998 EVT InVT = In.getValueType();
2000 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2002 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2003 InVT.getVectorNumElements());
2004 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2005 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2008 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2010 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2011 EVT CastVT = VT.changeVectorElementTypeToInteger();
2012 In = DAG.getNode(CastOpc, dl, CastVT, In);
2013 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2019 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2020 SelectionDAG &DAG) const {
2021 if (Op.getValueType().isVector())
2022 return LowerVectorINT_TO_FP(Op, DAG);
2024 // f16 conversions are promoted to f32.
2025 if (Op.getValueType() == MVT::f16) {
2028 ISD::FP_ROUND, dl, MVT::f16,
2029 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2030 DAG.getIntPtrConstant(0, dl));
2033 // i128 conversions are libcalls.
2034 if (Op.getOperand(0).getValueType() == MVT::i128)
2037 // Other conversions are legal, unless it's to the completely software-based
2039 if (Op.getValueType() != MVT::f128)
2043 if (Op.getOpcode() == ISD::SINT_TO_FP)
2044 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2046 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2048 return LowerF128Call(Op, DAG, LC);
2051 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2052 SelectionDAG &DAG) const {
2053 // For iOS, we want to call an alternative entry point: __sincos_stret,
2054 // which returns the values in two S / D registers.
2056 SDValue Arg = Op.getOperand(0);
2057 EVT ArgVT = Arg.getValueType();
2058 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2065 Entry.isSExt = false;
2066 Entry.isZExt = false;
2067 Args.push_back(Entry);
2069 const char *LibcallName =
2070 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2072 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2074 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2075 TargetLowering::CallLoweringInfo CLI(DAG);
2076 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2077 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2079 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2080 return CallResult.first;
2083 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2084 if (Op.getValueType() != MVT::f16)
2087 assert(Op.getOperand(0).getValueType() == MVT::i16);
2090 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2091 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2093 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2094 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2098 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2099 if (OrigVT.getSizeInBits() >= 64)
2102 assert(OrigVT.isSimple() && "Expecting a simple value type");
2104 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2105 switch (OrigSimpleTy) {
2106 default: llvm_unreachable("Unexpected Vector Type");
2115 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2118 unsigned ExtOpcode) {
2119 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2120 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2121 // 64-bits we need to insert a new extension so that it will be 64-bits.
2122 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2123 if (OrigTy.getSizeInBits() >= 64)
2126 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2127 EVT NewVT = getExtensionTo64Bits(OrigTy);
2129 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2132 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2134 EVT VT = N->getValueType(0);
2136 if (N->getOpcode() != ISD::BUILD_VECTOR)
2139 for (const SDValue &Elt : N->op_values()) {
2140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2141 unsigned EltSize = VT.getScalarSizeInBits();
2142 unsigned HalfSize = EltSize / 2;
2144 if (!isIntN(HalfSize, C->getSExtValue()))
2147 if (!isUIntN(HalfSize, C->getZExtValue()))
2158 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2159 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2160 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2161 N->getOperand(0)->getValueType(0),
2165 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2166 EVT VT = N->getValueType(0);
2168 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2169 unsigned NumElts = VT.getVectorNumElements();
2170 MVT TruncVT = MVT::getIntegerVT(EltSize);
2171 SmallVector<SDValue, 8> Ops;
2172 for (unsigned i = 0; i != NumElts; ++i) {
2173 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2174 const APInt &CInt = C->getAPIntValue();
2175 // Element types smaller than 32 bits are not legal, so use i32 elements.
2176 // The values are implicitly truncated so sext vs. zext doesn't matter.
2177 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2179 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2182 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2183 if (N->getOpcode() == ISD::SIGN_EXTEND)
2185 if (isExtendedBUILD_VECTOR(N, DAG, true))
2190 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2191 if (N->getOpcode() == ISD::ZERO_EXTEND)
2193 if (isExtendedBUILD_VECTOR(N, DAG, false))
2198 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2199 unsigned Opcode = N->getOpcode();
2200 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2201 SDNode *N0 = N->getOperand(0).getNode();
2202 SDNode *N1 = N->getOperand(1).getNode();
2203 return N0->hasOneUse() && N1->hasOneUse() &&
2204 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2209 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2210 unsigned Opcode = N->getOpcode();
2211 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2212 SDNode *N0 = N->getOperand(0).getNode();
2213 SDNode *N1 = N->getOperand(1).getNode();
2214 return N0->hasOneUse() && N1->hasOneUse() &&
2215 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2220 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2221 // Multiplications are only custom-lowered for 128-bit vectors so that
2222 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2223 EVT VT = Op.getValueType();
2224 assert(VT.is128BitVector() && VT.isInteger() &&
2225 "unexpected type for custom-lowering ISD::MUL");
2226 SDNode *N0 = Op.getOperand(0).getNode();
2227 SDNode *N1 = Op.getOperand(1).getNode();
2228 unsigned NewOpc = 0;
2230 bool isN0SExt = isSignExtended(N0, DAG);
2231 bool isN1SExt = isSignExtended(N1, DAG);
2232 if (isN0SExt && isN1SExt)
2233 NewOpc = AArch64ISD::SMULL;
2235 bool isN0ZExt = isZeroExtended(N0, DAG);
2236 bool isN1ZExt = isZeroExtended(N1, DAG);
2237 if (isN0ZExt && isN1ZExt)
2238 NewOpc = AArch64ISD::UMULL;
2239 else if (isN1SExt || isN1ZExt) {
2240 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2241 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2242 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2243 NewOpc = AArch64ISD::SMULL;
2245 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2246 NewOpc = AArch64ISD::UMULL;
2248 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2250 NewOpc = AArch64ISD::UMULL;
2256 if (VT == MVT::v2i64)
2257 // Fall through to expand this. It is not legal.
2260 // Other vector multiplications are legal.
2265 // Legalize to a S/UMULL instruction
2268 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2270 Op0 = skipExtensionForVectorMULL(N0, DAG);
2271 assert(Op0.getValueType().is64BitVector() &&
2272 Op1.getValueType().is64BitVector() &&
2273 "unexpected types for extended operands to VMULL");
2274 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2276 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2277 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2278 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2279 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2280 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2281 EVT Op1VT = Op1.getValueType();
2282 return DAG.getNode(N0->getOpcode(), DL, VT,
2283 DAG.getNode(NewOpc, DL, VT,
2284 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2285 DAG.getNode(NewOpc, DL, VT,
2286 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2289 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2290 SelectionDAG &DAG) const {
2291 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2294 default: return SDValue(); // Don't custom lower most intrinsics.
2295 case Intrinsic::thread_pointer: {
2296 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2297 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2299 case Intrinsic::aarch64_neon_smax:
2300 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2301 Op.getOperand(1), Op.getOperand(2));
2302 case Intrinsic::aarch64_neon_umax:
2303 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2304 Op.getOperand(1), Op.getOperand(2));
2305 case Intrinsic::aarch64_neon_smin:
2306 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2307 Op.getOperand(1), Op.getOperand(2));
2308 case Intrinsic::aarch64_neon_umin:
2309 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2310 Op.getOperand(1), Op.getOperand(2));
2314 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2315 SelectionDAG &DAG) const {
2316 switch (Op.getOpcode()) {
2318 llvm_unreachable("unimplemented operand");
2321 return LowerBITCAST(Op, DAG);
2322 case ISD::GlobalAddress:
2323 return LowerGlobalAddress(Op, DAG);
2324 case ISD::GlobalTLSAddress:
2325 return LowerGlobalTLSAddress(Op, DAG);
2327 return LowerSETCC(Op, DAG);
2329 return LowerBR_CC(Op, DAG);
2331 return LowerSELECT(Op, DAG);
2332 case ISD::SELECT_CC:
2333 return LowerSELECT_CC(Op, DAG);
2334 case ISD::JumpTable:
2335 return LowerJumpTable(Op, DAG);
2336 case ISD::ConstantPool:
2337 return LowerConstantPool(Op, DAG);
2338 case ISD::BlockAddress:
2339 return LowerBlockAddress(Op, DAG);
2341 return LowerVASTART(Op, DAG);
2343 return LowerVACOPY(Op, DAG);
2345 return LowerVAARG(Op, DAG);
2350 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2357 return LowerXALUO(Op, DAG);
2359 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2361 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2363 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2365 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2367 return LowerFP_ROUND(Op, DAG);
2368 case ISD::FP_EXTEND:
2369 return LowerFP_EXTEND(Op, DAG);
2370 case ISD::FRAMEADDR:
2371 return LowerFRAMEADDR(Op, DAG);
2372 case ISD::RETURNADDR:
2373 return LowerRETURNADDR(Op, DAG);
2374 case ISD::INSERT_VECTOR_ELT:
2375 return LowerINSERT_VECTOR_ELT(Op, DAG);
2376 case ISD::EXTRACT_VECTOR_ELT:
2377 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2378 case ISD::BUILD_VECTOR:
2379 return LowerBUILD_VECTOR(Op, DAG);
2380 case ISD::VECTOR_SHUFFLE:
2381 return LowerVECTOR_SHUFFLE(Op, DAG);
2382 case ISD::EXTRACT_SUBVECTOR:
2383 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2387 return LowerVectorSRA_SRL_SHL(Op, DAG);
2388 case ISD::SHL_PARTS:
2389 return LowerShiftLeftParts(Op, DAG);
2390 case ISD::SRL_PARTS:
2391 case ISD::SRA_PARTS:
2392 return LowerShiftRightParts(Op, DAG);
2394 return LowerCTPOP(Op, DAG);
2395 case ISD::FCOPYSIGN:
2396 return LowerFCOPYSIGN(Op, DAG);
2398 return LowerVectorAND(Op, DAG);
2400 return LowerVectorOR(Op, DAG);
2402 return LowerXOR(Op, DAG);
2404 return LowerPREFETCH(Op, DAG);
2405 case ISD::SINT_TO_FP:
2406 case ISD::UINT_TO_FP:
2407 return LowerINT_TO_FP(Op, DAG);
2408 case ISD::FP_TO_SINT:
2409 case ISD::FP_TO_UINT:
2410 return LowerFP_TO_INT(Op, DAG);
2412 return LowerFSINCOS(Op, DAG);
2414 return LowerMUL(Op, DAG);
2415 case ISD::INTRINSIC_WO_CHAIN:
2416 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2420 //===----------------------------------------------------------------------===//
2421 // Calling Convention Implementation
2422 //===----------------------------------------------------------------------===//
2424 #include "AArch64GenCallingConv.inc"
2426 /// Selects the correct CCAssignFn for a given CallingConvention value.
2427 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2428 bool IsVarArg) const {
2431 llvm_unreachable("Unsupported calling convention.");
2432 case CallingConv::WebKit_JS:
2433 return CC_AArch64_WebKit_JS;
2434 case CallingConv::GHC:
2435 return CC_AArch64_GHC;
2436 case CallingConv::C:
2437 case CallingConv::Fast:
2438 case CallingConv::PreserveMost:
2439 case CallingConv::CXX_FAST_TLS:
2440 case CallingConv::Swift:
2441 if (!Subtarget->isTargetDarwin())
2442 return CC_AArch64_AAPCS;
2443 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2448 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2449 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2450 : RetCC_AArch64_AAPCS;
2453 SDValue AArch64TargetLowering::LowerFormalArguments(
2454 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2455 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2456 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2457 MachineFunction &MF = DAG.getMachineFunction();
2458 MachineFrameInfo &MFI = MF.getFrameInfo();
2460 // Assign locations to all of the incoming arguments.
2461 SmallVector<CCValAssign, 16> ArgLocs;
2462 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2465 // At this point, Ins[].VT may already be promoted to i32. To correctly
2466 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2467 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2468 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2469 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2471 unsigned NumArgs = Ins.size();
2472 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2473 unsigned CurArgIdx = 0;
2474 for (unsigned i = 0; i != NumArgs; ++i) {
2475 MVT ValVT = Ins[i].VT;
2476 if (Ins[i].isOrigArg()) {
2477 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2478 CurArgIdx = Ins[i].getOrigArgIndex();
2480 // Get type of the original argument.
2481 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2482 /*AllowUnknown*/ true);
2483 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2484 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2485 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2487 else if (ActualMVT == MVT::i16)
2490 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2492 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2493 assert(!Res && "Call operand has unhandled type");
2496 assert(ArgLocs.size() == Ins.size());
2497 SmallVector<SDValue, 16> ArgValues;
2498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2499 CCValAssign &VA = ArgLocs[i];
2501 if (Ins[i].Flags.isByVal()) {
2502 // Byval is used for HFAs in the PCS, but the system should work in a
2503 // non-compliant manner for larger structs.
2504 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2505 int Size = Ins[i].Flags.getByValSize();
2506 unsigned NumRegs = (Size + 7) / 8;
2508 // FIXME: This works on big-endian for composite byvals, which are the common
2509 // case. It should also work for fundamental types too.
2511 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2512 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2513 InVals.push_back(FrameIdxN);
2518 if (VA.isRegLoc()) {
2519 // Arguments stored in registers.
2520 EVT RegVT = VA.getLocVT();
2523 const TargetRegisterClass *RC;
2525 if (RegVT == MVT::i32)
2526 RC = &AArch64::GPR32RegClass;
2527 else if (RegVT == MVT::i64)
2528 RC = &AArch64::GPR64RegClass;
2529 else if (RegVT == MVT::f16)
2530 RC = &AArch64::FPR16RegClass;
2531 else if (RegVT == MVT::f32)
2532 RC = &AArch64::FPR32RegClass;
2533 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2534 RC = &AArch64::FPR64RegClass;
2535 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2536 RC = &AArch64::FPR128RegClass;
2538 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2540 // Transform the arguments in physical registers into virtual ones.
2541 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2542 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2544 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2545 // to 64 bits. Insert an assert[sz]ext to capture this, then
2546 // truncate to the right size.
2547 switch (VA.getLocInfo()) {
2549 llvm_unreachable("Unknown loc info!");
2550 case CCValAssign::Full:
2552 case CCValAssign::BCvt:
2553 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2555 case CCValAssign::AExt:
2556 case CCValAssign::SExt:
2557 case CCValAssign::ZExt:
2558 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2559 // nodes after our lowering.
2560 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2564 InVals.push_back(ArgValue);
2566 } else { // VA.isRegLoc()
2567 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2568 unsigned ArgOffset = VA.getLocMemOffset();
2569 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2571 uint32_t BEAlign = 0;
2572 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2573 !Ins[i].Flags.isInConsecutiveRegs())
2574 BEAlign = 8 - ArgSize;
2576 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2578 // Create load nodes to retrieve arguments from the stack.
2579 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2582 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2583 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2584 MVT MemVT = VA.getValVT();
2586 switch (VA.getLocInfo()) {
2589 case CCValAssign::BCvt:
2590 MemVT = VA.getLocVT();
2592 case CCValAssign::SExt:
2593 ExtType = ISD::SEXTLOAD;
2595 case CCValAssign::ZExt:
2596 ExtType = ISD::ZEXTLOAD;
2598 case CCValAssign::AExt:
2599 ExtType = ISD::EXTLOAD;
2603 ArgValue = DAG.getExtLoad(
2604 ExtType, DL, VA.getLocVT(), Chain, FIN,
2605 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2608 InVals.push_back(ArgValue);
2613 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2615 if (!Subtarget->isTargetDarwin()) {
2616 // The AAPCS variadic function ABI is identical to the non-variadic
2617 // one. As a result there may be more arguments in registers and we should
2618 // save them for future reference.
2619 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2622 // This will point to the next argument passed via stack.
2623 unsigned StackOffset = CCInfo.getNextStackOffset();
2624 // We currently pass all varargs at 8-byte alignment.
2625 StackOffset = ((StackOffset + 7) & ~7);
2626 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2629 unsigned StackArgSize = CCInfo.getNextStackOffset();
2630 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2631 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2632 // This is a non-standard ABI so by fiat I say we're allowed to make full
2633 // use of the stack area to be popped, which must be aligned to 16 bytes in
2635 StackArgSize = alignTo(StackArgSize, 16);
2637 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2638 // a multiple of 16.
2639 FuncInfo->setArgumentStackToRestore(StackArgSize);
2641 // This realignment carries over to the available bytes below. Our own
2642 // callers will guarantee the space is free by giving an aligned value to
2645 // Even if we're not expected to free up the space, it's useful to know how
2646 // much is there while considering tail calls (because we can reuse it).
2647 FuncInfo->setBytesInStackArgArea(StackArgSize);
2652 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2655 SDValue &Chain) const {
2656 MachineFunction &MF = DAG.getMachineFunction();
2657 MachineFrameInfo &MFI = MF.getFrameInfo();
2658 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2659 auto PtrVT = getPointerTy(DAG.getDataLayout());
2661 SmallVector<SDValue, 8> MemOps;
2663 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2664 AArch64::X3, AArch64::X4, AArch64::X5,
2665 AArch64::X6, AArch64::X7 };
2666 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2667 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2669 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2671 if (GPRSaveSize != 0) {
2672 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2674 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2676 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2677 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2678 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2679 SDValue Store = DAG.getStore(
2680 Val.getValue(1), DL, Val, FIN,
2681 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2682 MemOps.push_back(Store);
2684 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2687 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2688 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2690 if (Subtarget->hasFPARMv8()) {
2691 static const MCPhysReg FPRArgRegs[] = {
2692 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2693 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2694 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2695 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2697 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2699 if (FPRSaveSize != 0) {
2700 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2702 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2704 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2705 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2706 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2708 SDValue Store = DAG.getStore(
2709 Val.getValue(1), DL, Val, FIN,
2710 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2711 MemOps.push_back(Store);
2712 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2713 DAG.getConstant(16, DL, PtrVT));
2716 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2717 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2720 if (!MemOps.empty()) {
2721 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2725 /// LowerCallResult - Lower the result values of a call into the
2726 /// appropriate copies out of appropriate physical registers.
2727 SDValue AArch64TargetLowering::LowerCallResult(
2728 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2729 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2730 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2731 SDValue ThisVal) const {
2732 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2733 ? RetCC_AArch64_WebKit_JS
2734 : RetCC_AArch64_AAPCS;
2735 // Assign locations to each value returned by this call.
2736 SmallVector<CCValAssign, 16> RVLocs;
2737 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2739 CCInfo.AnalyzeCallResult(Ins, RetCC);
2741 // Copy all of the result registers out of their specified physreg.
2742 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2743 CCValAssign VA = RVLocs[i];
2745 // Pass 'this' value directly from the argument to return value, to avoid
2746 // reg unit interference
2747 if (i == 0 && isThisReturn) {
2748 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2749 "unexpected return calling convention register assignment");
2750 InVals.push_back(ThisVal);
2755 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2756 Chain = Val.getValue(1);
2757 InFlag = Val.getValue(2);
2759 switch (VA.getLocInfo()) {
2761 llvm_unreachable("Unknown loc info!");
2762 case CCValAssign::Full:
2764 case CCValAssign::BCvt:
2765 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2769 InVals.push_back(Val);
2775 /// Return true if the calling convention is one that we can guarantee TCO for.
2776 static bool canGuaranteeTCO(CallingConv::ID CC) {
2777 return CC == CallingConv::Fast;
2780 /// Return true if we might ever do TCO for calls with this calling convention.
2781 static bool mayTailCallThisCC(CallingConv::ID CC) {
2783 case CallingConv::C:
2784 case CallingConv::PreserveMost:
2785 case CallingConv::Swift:
2788 return canGuaranteeTCO(CC);
2792 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2793 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2794 const SmallVectorImpl<ISD::OutputArg> &Outs,
2795 const SmallVectorImpl<SDValue> &OutVals,
2796 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2797 if (!mayTailCallThisCC(CalleeCC))
2800 MachineFunction &MF = DAG.getMachineFunction();
2801 const Function *CallerF = MF.getFunction();
2802 CallingConv::ID CallerCC = CallerF->getCallingConv();
2803 bool CCMatch = CallerCC == CalleeCC;
2805 // Byval parameters hand the function a pointer directly into the stack area
2806 // we want to reuse during a tail call. Working around this *is* possible (see
2807 // X86) but less efficient and uglier in LowerCall.
2808 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2809 e = CallerF->arg_end();
2811 if (i->hasByValAttr())
2814 if (getTargetMachine().Options.GuaranteedTailCallOpt)
2815 return canGuaranteeTCO(CalleeCC) && CCMatch;
2817 // Externally-defined functions with weak linkage should not be
2818 // tail-called on AArch64 when the OS does not support dynamic
2819 // pre-emption of symbols, as the AAELF spec requires normal calls
2820 // to undefined weak functions to be replaced with a NOP or jump to the
2821 // next instruction. The behaviour of branch instructions in this
2822 // situation (as used for tail calls) is implementation-defined, so we
2823 // cannot rely on the linker replacing the tail call with a return.
2824 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2825 const GlobalValue *GV = G->getGlobal();
2826 const Triple &TT = getTargetMachine().getTargetTriple();
2827 if (GV->hasExternalWeakLinkage() &&
2828 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2832 // Now we search for cases where we can use a tail call without changing the
2833 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2836 // I want anyone implementing a new calling convention to think long and hard
2837 // about this assert.
2838 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2839 "Unexpected variadic calling convention");
2841 LLVMContext &C = *DAG.getContext();
2842 if (isVarArg && !Outs.empty()) {
2843 // At least two cases here: if caller is fastcc then we can't have any
2844 // memory arguments (we'd be expected to clean up the stack afterwards). If
2845 // caller is C then we could potentially use its argument area.
2847 // FIXME: for now we take the most conservative of these in both cases:
2848 // disallow all variadic memory operands.
2849 SmallVector<CCValAssign, 16> ArgLocs;
2850 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2852 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2853 for (const CCValAssign &ArgLoc : ArgLocs)
2854 if (!ArgLoc.isRegLoc())
2858 // Check that the call results are passed in the same way.
2859 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2860 CCAssignFnForCall(CalleeCC, isVarArg),
2861 CCAssignFnForCall(CallerCC, isVarArg)))
2863 // The callee has to preserve all registers the caller needs to preserve.
2864 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2865 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2867 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2868 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2872 // Nothing more to check if the callee is taking no arguments
2876 SmallVector<CCValAssign, 16> ArgLocs;
2877 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2879 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2881 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2883 // If the stack arguments for this call do not fit into our own save area then
2884 // the call cannot be made tail.
2885 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2888 const MachineRegisterInfo &MRI = MF.getRegInfo();
2889 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2895 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2897 MachineFrameInfo &MFI,
2898 int ClobberedFI) const {
2899 SmallVector<SDValue, 8> ArgChains;
2900 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2901 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
2903 // Include the original chain at the beginning of the list. When this is
2904 // used by target LowerCall hooks, this helps legalize find the
2905 // CALLSEQ_BEGIN node.
2906 ArgChains.push_back(Chain);
2908 // Add a chain value for each stack argument corresponding
2909 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2910 UE = DAG.getEntryNode().getNode()->use_end();
2912 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2913 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2914 if (FI->getIndex() < 0) {
2915 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
2916 int64_t InLastByte = InFirstByte;
2917 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
2919 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2920 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2921 ArgChains.push_back(SDValue(L, 1));
2924 // Build a tokenfactor for all the chains.
2925 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2928 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2929 bool TailCallOpt) const {
2930 return CallCC == CallingConv::Fast && TailCallOpt;
2933 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2934 /// and add input and output parameter nodes.
2936 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2937 SmallVectorImpl<SDValue> &InVals) const {
2938 SelectionDAG &DAG = CLI.DAG;
2940 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2941 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2942 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2943 SDValue Chain = CLI.Chain;
2944 SDValue Callee = CLI.Callee;
2945 bool &IsTailCall = CLI.IsTailCall;
2946 CallingConv::ID CallConv = CLI.CallConv;
2947 bool IsVarArg = CLI.IsVarArg;
2949 MachineFunction &MF = DAG.getMachineFunction();
2950 bool IsThisReturn = false;
2952 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2953 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2954 bool IsSibCall = false;
2957 // Check if it's really possible to do a tail call.
2958 IsTailCall = isEligibleForTailCallOptimization(
2959 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2960 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2961 report_fatal_error("failed to perform tail call elimination on a call "
2962 "site marked musttail");
2964 // A sibling call is one where we're under the usual C ABI and not planning
2965 // to change that but can still do a tail call:
2966 if (!TailCallOpt && IsTailCall)
2973 // Analyze operands of the call, assigning locations to each operand.
2974 SmallVector<CCValAssign, 16> ArgLocs;
2975 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2979 // Handle fixed and variable vector arguments differently.
2980 // Variable vector arguments always go into memory.
2981 unsigned NumArgs = Outs.size();
2983 for (unsigned i = 0; i != NumArgs; ++i) {
2984 MVT ArgVT = Outs[i].VT;
2985 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2986 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2987 /*IsVarArg=*/ !Outs[i].IsFixed);
2988 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2989 assert(!Res && "Call operand has unhandled type");
2993 // At this point, Outs[].VT may already be promoted to i32. To correctly
2994 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2995 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2996 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2997 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2999 unsigned NumArgs = Outs.size();
3000 for (unsigned i = 0; i != NumArgs; ++i) {
3001 MVT ValVT = Outs[i].VT;
3002 // Get type of the original argument.
3003 EVT ActualVT = getValueType(DAG.getDataLayout(),
3004 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3005 /*AllowUnknown*/ true);
3006 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3007 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3008 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3009 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3011 else if (ActualMVT == MVT::i16)
3014 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3015 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3016 assert(!Res && "Call operand has unhandled type");
3021 // Get a count of how many bytes are to be pushed on the stack.
3022 unsigned NumBytes = CCInfo.getNextStackOffset();
3025 // Since we're not changing the ABI to make this a tail call, the memory
3026 // operands are already available in the caller's incoming argument space.
3030 // FPDiff is the byte offset of the call's argument area from the callee's.
3031 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3032 // by this amount for a tail call. In a sibling call it must be 0 because the
3033 // caller will deallocate the entire stack and the callee still expects its
3034 // arguments to begin at SP+0. Completely unused for non-tail calls.
3037 if (IsTailCall && !IsSibCall) {
3038 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3040 // Since callee will pop argument stack as a tail call, we must keep the
3041 // popped size 16-byte aligned.
3042 NumBytes = alignTo(NumBytes, 16);
3044 // FPDiff will be negative if this tail call requires more space than we
3045 // would automatically have in our incoming argument space. Positive if we
3046 // can actually shrink the stack.
3047 FPDiff = NumReusableBytes - NumBytes;
3049 // The stack pointer must be 16-byte aligned at all times it's used for a
3050 // memory operation, which in practice means at *all* times and in
3051 // particular across call boundaries. Therefore our own arguments started at
3052 // a 16-byte aligned SP and the delta applied for the tail call should
3053 // satisfy the same constraint.
3054 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3057 // Adjust the stack pointer for the new arguments...
3058 // These operations are automatically eliminated by the prolog/epilog pass
3060 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3064 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3065 getPointerTy(DAG.getDataLayout()));
3067 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3068 SmallVector<SDValue, 8> MemOpChains;
3069 auto PtrVT = getPointerTy(DAG.getDataLayout());
3071 // Walk the register/memloc assignments, inserting copies/loads.
3072 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3073 ++i, ++realArgIdx) {
3074 CCValAssign &VA = ArgLocs[i];
3075 SDValue Arg = OutVals[realArgIdx];
3076 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3078 // Promote the value if needed.
3079 switch (VA.getLocInfo()) {
3081 llvm_unreachable("Unknown loc info!");
3082 case CCValAssign::Full:
3084 case CCValAssign::SExt:
3085 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3087 case CCValAssign::ZExt:
3088 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3090 case CCValAssign::AExt:
3091 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3092 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3093 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3094 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3096 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3098 case CCValAssign::BCvt:
3099 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3101 case CCValAssign::FPExt:
3102 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3106 if (VA.isRegLoc()) {
3107 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3108 assert(VA.getLocVT() == MVT::i64 &&
3109 "unexpected calling convention register assignment");
3110 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3111 "unexpected use of 'returned'");
3112 IsThisReturn = true;
3114 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3116 assert(VA.isMemLoc());
3119 MachinePointerInfo DstInfo;
3121 // FIXME: This works on big-endian for composite byvals, which are the
3122 // common case. It should also work for fundamental types too.
3123 uint32_t BEAlign = 0;
3124 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3125 : VA.getValVT().getSizeInBits();
3126 OpSize = (OpSize + 7) / 8;
3127 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3128 !Flags.isInConsecutiveRegs()) {
3130 BEAlign = 8 - OpSize;
3132 unsigned LocMemOffset = VA.getLocMemOffset();
3133 int32_t Offset = LocMemOffset + BEAlign;
3134 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3135 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3138 Offset = Offset + FPDiff;
3139 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3141 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3143 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3145 // Make sure any stack arguments overlapping with where we're storing
3146 // are loaded before this eventual operation. Otherwise they'll be
3148 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3150 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3152 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3153 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3157 if (Outs[i].Flags.isByVal()) {
3159 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3160 SDValue Cpy = DAG.getMemcpy(
3161 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3162 /*isVol = */ false, /*AlwaysInline = */ false,
3163 /*isTailCall = */ false,
3164 DstInfo, MachinePointerInfo());
3166 MemOpChains.push_back(Cpy);
3168 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3169 // promoted to a legal register type i32, we should truncate Arg back to
3171 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3172 VA.getValVT() == MVT::i16)
3173 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3175 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3176 MemOpChains.push_back(Store);
3181 if (!MemOpChains.empty())
3182 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3184 // Build a sequence of copy-to-reg nodes chained together with token chain
3185 // and flag operands which copy the outgoing args into the appropriate regs.
3187 for (auto &RegToPass : RegsToPass) {
3188 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3189 RegToPass.second, InFlag);
3190 InFlag = Chain.getValue(1);
3193 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3194 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3195 // node so that legalize doesn't hack it.
3196 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3197 Subtarget->isTargetMachO()) {
3198 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3199 const GlobalValue *GV = G->getGlobal();
3200 bool InternalLinkage = GV->hasInternalLinkage();
3201 if (InternalLinkage)
3202 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3205 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3206 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3208 } else if (ExternalSymbolSDNode *S =
3209 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3210 const char *Sym = S->getSymbol();
3211 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3212 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3214 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3215 const GlobalValue *GV = G->getGlobal();
3216 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3217 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3218 const char *Sym = S->getSymbol();
3219 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3222 // We don't usually want to end the call-sequence here because we would tidy
3223 // the frame up *after* the call, however in the ABI-changing tail-call case
3224 // we've carefully laid out the parameters so that when sp is reset they'll be
3225 // in the correct location.
3226 if (IsTailCall && !IsSibCall) {
3227 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3228 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3229 InFlag = Chain.getValue(1);
3232 std::vector<SDValue> Ops;
3233 Ops.push_back(Chain);
3234 Ops.push_back(Callee);
3237 // Each tail call may have to adjust the stack by a different amount, so
3238 // this information must travel along with the operation for eventual
3239 // consumption by emitEpilogue.
3240 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3243 // Add argument registers to the end of the list so that they are known live
3245 for (auto &RegToPass : RegsToPass)
3246 Ops.push_back(DAG.getRegister(RegToPass.first,
3247 RegToPass.second.getValueType()));
3249 // Add a register mask operand representing the call-preserved registers.
3250 const uint32_t *Mask;
3251 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3253 // For 'this' returns, use the X0-preserving mask if applicable
3254 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3256 IsThisReturn = false;
3257 Mask = TRI->getCallPreservedMask(MF, CallConv);
3260 Mask = TRI->getCallPreservedMask(MF, CallConv);
3262 assert(Mask && "Missing call preserved mask for calling convention");
3263 Ops.push_back(DAG.getRegisterMask(Mask));
3265 if (InFlag.getNode())
3266 Ops.push_back(InFlag);
3268 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3270 // If we're doing a tall call, use a TC_RETURN here rather than an
3271 // actual call instruction.
3273 MF.getFrameInfo().setHasTailCall();
3274 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3277 // Returns a chain and a flag for retval copy to use.
3278 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3279 InFlag = Chain.getValue(1);
3281 uint64_t CalleePopBytes =
3282 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3284 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3285 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3288 InFlag = Chain.getValue(1);
3290 // Handle result values, copying them out of physregs into vregs that we
3292 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3293 InVals, IsThisReturn,
3294 IsThisReturn ? OutVals[0] : SDValue());
3297 bool AArch64TargetLowering::CanLowerReturn(
3298 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3299 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3300 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3301 ? RetCC_AArch64_WebKit_JS
3302 : RetCC_AArch64_AAPCS;
3303 SmallVector<CCValAssign, 16> RVLocs;
3304 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3305 return CCInfo.CheckReturn(Outs, RetCC);
3309 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3311 const SmallVectorImpl<ISD::OutputArg> &Outs,
3312 const SmallVectorImpl<SDValue> &OutVals,
3313 const SDLoc &DL, SelectionDAG &DAG) const {
3314 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3315 ? RetCC_AArch64_WebKit_JS
3316 : RetCC_AArch64_AAPCS;
3317 SmallVector<CCValAssign, 16> RVLocs;
3318 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3320 CCInfo.AnalyzeReturn(Outs, RetCC);
3322 // Copy the result values into the output registers.
3324 SmallVector<SDValue, 4> RetOps(1, Chain);
3325 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3326 ++i, ++realRVLocIdx) {
3327 CCValAssign &VA = RVLocs[i];
3328 assert(VA.isRegLoc() && "Can only return in registers!");
3329 SDValue Arg = OutVals[realRVLocIdx];
3331 switch (VA.getLocInfo()) {
3333 llvm_unreachable("Unknown loc info!");
3334 case CCValAssign::Full:
3335 if (Outs[i].ArgVT == MVT::i1) {
3336 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3337 // value. This is strictly redundant on Darwin (which uses "zeroext
3338 // i1"), but will be optimised out before ISel.
3339 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3340 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3343 case CCValAssign::BCvt:
3344 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3348 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3349 Flag = Chain.getValue(1);
3350 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3352 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3353 const MCPhysReg *I =
3354 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3357 if (AArch64::GPR64RegClass.contains(*I))
3358 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3359 else if (AArch64::FPR64RegClass.contains(*I))
3360 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3362 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3366 RetOps[0] = Chain; // Update chain.
3368 // Add the flag if we have it.
3370 RetOps.push_back(Flag);
3372 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3375 //===----------------------------------------------------------------------===//
3376 // Other Lowering Code
3377 //===----------------------------------------------------------------------===//
3379 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3380 SelectionDAG &DAG) const {
3381 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3383 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3384 const GlobalValue *GV = GN->getGlobal();
3385 unsigned char OpFlags =
3386 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3388 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3389 "unexpected offset in global node");
3391 // This also catched the large code model case for Darwin.
3392 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3393 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3394 // FIXME: Once remat is capable of dealing with instructions with register
3395 // operands, expand this into two nodes instead of using a wrapper node.
3396 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3399 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3400 const unsigned char MO_NC = AArch64II::MO_NC;
3402 AArch64ISD::WrapperLarge, DL, PtrVT,
3403 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3404 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3405 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3406 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3408 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3409 // the only correct model on Darwin.
3410 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3411 OpFlags | AArch64II::MO_PAGE);
3412 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3413 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3415 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3416 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3420 /// \brief Convert a TLS address reference into the correct sequence of loads
3421 /// and calls to compute the variable's address (for Darwin, currently) and
3422 /// return an SDValue containing the final node.
3424 /// Darwin only has one TLS scheme which must be capable of dealing with the
3425 /// fully general situation, in the worst case. This means:
3426 /// + "extern __thread" declaration.
3427 /// + Defined in a possibly unknown dynamic library.
3429 /// The general system is that each __thread variable has a [3 x i64] descriptor
3430 /// which contains information used by the runtime to calculate the address. The
3431 /// only part of this the compiler needs to know about is the first xword, which
3432 /// contains a function pointer that must be called with the address of the
3433 /// entire descriptor in "x0".
3435 /// Since this descriptor may be in a different unit, in general even the
3436 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3438 /// adrp x0, _var@TLVPPAGE
3439 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3440 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3441 /// ; the function pointer
3442 /// blr x1 ; Uses descriptor address in x0
3443 /// ; Address of _var is now in x0.
3445 /// If the address of _var's descriptor *is* known to the linker, then it can
3446 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3447 /// a slight efficiency gain.
3449 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3450 SelectionDAG &DAG) const {
3451 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3454 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3455 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3458 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3459 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3461 // The first entry in the descriptor is a function pointer that we must call
3462 // to obtain the address of the variable.
3463 SDValue Chain = DAG.getEntryNode();
3464 SDValue FuncTLVGet = DAG.getLoad(
3465 MVT::i64, DL, Chain, DescAddr,
3466 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3467 /* Alignment = */ 8,
3468 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3469 MachineMemOperand::MODereferenceable);
3470 Chain = FuncTLVGet.getValue(1);
3472 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3473 MFI.setAdjustsStack(true);
3475 // TLS calls preserve all registers except those that absolutely must be
3476 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3478 const uint32_t *Mask =
3479 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3481 // Finally, we can make the call. This is just a degenerate version of a
3482 // normal AArch64 call node: x0 takes the address of the descriptor, and
3483 // returns the address of the variable in this thread.
3484 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3486 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3487 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3488 DAG.getRegisterMask(Mask), Chain.getValue(1));
3489 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3492 /// When accessing thread-local variables under either the general-dynamic or
3493 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3494 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3495 /// is a function pointer to carry out the resolution.
3497 /// The sequence is:
3498 /// adrp x0, :tlsdesc:var
3499 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3500 /// add x0, x0, #:tlsdesc_lo12:var
3501 /// .tlsdesccall var
3503 /// (TPIDR_EL0 offset now in x0)
3505 /// The above sequence must be produced unscheduled, to enable the linker to
3506 /// optimize/relax this sequence.
3507 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3508 /// above sequence, and expanded really late in the compilation flow, to ensure
3509 /// the sequence is produced as per above.
3510 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3512 SelectionDAG &DAG) const {
3513 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3515 SDValue Chain = DAG.getEntryNode();
3516 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3519 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3520 SDValue Glue = Chain.getValue(1);
3522 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3526 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3527 SelectionDAG &DAG) const {
3528 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3529 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3530 "ELF TLS only supported in small memory model");
3531 // Different choices can be made for the maximum size of the TLS area for a
3532 // module. For the small address model, the default TLS size is 16MiB and the
3533 // maximum TLS size is 4GiB.
3534 // FIXME: add -mtls-size command line option and make it control the 16MiB
3535 // vs. 4GiB code sequence generation.
3536 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3538 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3540 if (DAG.getTarget().Options.EmulatedTLS)
3541 return LowerToTLSEmulatedModel(GA, DAG);
3543 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3544 if (Model == TLSModel::LocalDynamic)
3545 Model = TLSModel::GeneralDynamic;
3549 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3551 const GlobalValue *GV = GA->getGlobal();
3553 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3555 if (Model == TLSModel::LocalExec) {
3556 SDValue HiVar = DAG.getTargetGlobalAddress(
3557 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3558 SDValue LoVar = DAG.getTargetGlobalAddress(
3560 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3562 SDValue TPWithOff_lo =
3563 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3565 DAG.getTargetConstant(0, DL, MVT::i32)),
3568 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3570 DAG.getTargetConstant(0, DL, MVT::i32)),
3573 } else if (Model == TLSModel::InitialExec) {
3574 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3575 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3576 } else if (Model == TLSModel::LocalDynamic) {
3577 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3578 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3579 // the beginning of the module's TLS region, followed by a DTPREL offset
3582 // These accesses will need deduplicating if there's more than one.
3583 AArch64FunctionInfo *MFI =
3584 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3585 MFI->incNumLocalDynamicTLSAccesses();
3587 // The call needs a relocation too for linker relaxation. It doesn't make
3588 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3590 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3593 // Now we can calculate the offset from TPIDR_EL0 to this module's
3594 // thread-local area.
3595 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3597 // Now use :dtprel_whatever: operations to calculate this variable's offset
3598 // in its thread-storage area.
3599 SDValue HiVar = DAG.getTargetGlobalAddress(
3600 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3601 SDValue LoVar = DAG.getTargetGlobalAddress(
3602 GV, DL, MVT::i64, 0,
3603 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3605 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3606 DAG.getTargetConstant(0, DL, MVT::i32)),
3608 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3609 DAG.getTargetConstant(0, DL, MVT::i32)),
3611 } else if (Model == TLSModel::GeneralDynamic) {
3612 // The call needs a relocation too for linker relaxation. It doesn't make
3613 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3616 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3618 // Finally we can make a call to calculate the offset from tpidr_el0.
3619 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3621 llvm_unreachable("Unsupported ELF TLS access model");
3623 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3626 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3627 SelectionDAG &DAG) const {
3628 if (Subtarget->isTargetDarwin())
3629 return LowerDarwinGlobalTLSAddress(Op, DAG);
3630 else if (Subtarget->isTargetELF())
3631 return LowerELFGlobalTLSAddress(Op, DAG);
3633 llvm_unreachable("Unexpected platform trying to use TLS");
3635 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3636 SDValue Chain = Op.getOperand(0);
3637 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3638 SDValue LHS = Op.getOperand(2);
3639 SDValue RHS = Op.getOperand(3);
3640 SDValue Dest = Op.getOperand(4);
3643 // Handle f128 first, since lowering it will result in comparing the return
3644 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3645 // is expecting to deal with.
3646 if (LHS.getValueType() == MVT::f128) {
3647 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3649 // If softenSetCCOperands returned a scalar, we need to compare the result
3650 // against zero to select between true and false values.
3651 if (!RHS.getNode()) {
3652 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3657 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3659 unsigned Opc = LHS.getOpcode();
3660 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3661 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3662 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3663 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3664 "Unexpected condition code.");
3665 // Only lower legal XALUO ops.
3666 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3669 // The actual operation with overflow check.
3670 AArch64CC::CondCode OFCC;
3671 SDValue Value, Overflow;
3672 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3674 if (CC == ISD::SETNE)
3675 OFCC = getInvertedCondCode(OFCC);
3676 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3678 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3682 if (LHS.getValueType().isInteger()) {
3683 assert((LHS.getValueType() == RHS.getValueType()) &&
3684 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3686 // If the RHS of the comparison is zero, we can potentially fold this
3687 // to a specialized branch.
3688 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3689 if (RHSC && RHSC->getZExtValue() == 0) {
3690 if (CC == ISD::SETEQ) {
3691 // See if we can use a TBZ to fold in an AND as well.
3692 // TBZ has a smaller branch displacement than CBZ. If the offset is
3693 // out of bounds, a late MI-layer pass rewrites branches.
3694 // 403.gcc is an example that hits this case.
3695 if (LHS.getOpcode() == ISD::AND &&
3696 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3697 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3698 SDValue Test = LHS.getOperand(0);
3699 uint64_t Mask = LHS.getConstantOperandVal(1);
3700 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3701 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3705 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3706 } else if (CC == ISD::SETNE) {
3707 // See if we can use a TBZ to fold in an AND as well.
3708 // TBZ has a smaller branch displacement than CBZ. If the offset is
3709 // out of bounds, a late MI-layer pass rewrites branches.
3710 // 403.gcc is an example that hits this case.
3711 if (LHS.getOpcode() == ISD::AND &&
3712 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3713 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3714 SDValue Test = LHS.getOperand(0);
3715 uint64_t Mask = LHS.getConstantOperandVal(1);
3716 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3717 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3721 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3722 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3723 // Don't combine AND since emitComparison converts the AND to an ANDS
3724 // (a.k.a. TST) and the test in the test bit and branch instruction
3725 // becomes redundant. This would also increase register pressure.
3726 uint64_t Mask = LHS.getValueSizeInBits() - 1;
3727 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3728 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3731 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3732 LHS.getOpcode() != ISD::AND) {
3733 // Don't combine AND since emitComparison converts the AND to an ANDS
3734 // (a.k.a. TST) and the test in the test bit and branch instruction
3735 // becomes redundant. This would also increase register pressure.
3736 uint64_t Mask = LHS.getValueSizeInBits() - 1;
3737 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3738 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3742 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3743 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3747 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3749 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3750 // clean. Some of them require two branches to implement.
3751 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3752 AArch64CC::CondCode CC1, CC2;
3753 changeFPCCToAArch64CC(CC, CC1, CC2);
3754 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3756 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3757 if (CC2 != AArch64CC::AL) {
3758 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3759 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3766 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3767 SelectionDAG &DAG) const {
3768 EVT VT = Op.getValueType();
3771 SDValue In1 = Op.getOperand(0);
3772 SDValue In2 = Op.getOperand(1);
3773 EVT SrcVT = In2.getValueType();
3775 if (SrcVT.bitsLT(VT))
3776 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3777 else if (SrcVT.bitsGT(VT))
3778 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3783 SDValue VecVal1, VecVal2;
3784 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3786 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3787 EltMask = 0x80000000ULL;
3789 if (!VT.isVector()) {
3790 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3791 DAG.getUNDEF(VecVT), In1);
3792 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3793 DAG.getUNDEF(VecVT), In2);
3795 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3796 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3798 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3802 // We want to materialize a mask with the high bit set, but the AdvSIMD
3803 // immediate moves cannot materialize that in a single instruction for
3804 // 64-bit elements. Instead, materialize zero and then negate it.
3807 if (!VT.isVector()) {
3808 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3809 DAG.getUNDEF(VecVT), In1);
3810 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3811 DAG.getUNDEF(VecVT), In2);
3813 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3814 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3817 llvm_unreachable("Invalid type for copysign!");
3820 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3822 // If we couldn't materialize the mask above, then the mask vector will be
3823 // the zero vector, and we need to negate it here.
3824 if (VT == MVT::f64 || VT == MVT::v2f64) {
3825 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3826 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3827 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3831 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3834 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3835 else if (VT == MVT::f64)
3836 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3838 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3841 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3842 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3843 Attribute::NoImplicitFloat))
3846 if (!Subtarget->hasNEON())
3849 // While there is no integer popcount instruction, it can
3850 // be more efficiently lowered to the following sequence that uses
3851 // AdvSIMD registers/instructions as long as the copies to/from
3852 // the AdvSIMD registers are cheap.
3853 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3854 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3855 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3856 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3857 SDValue Val = Op.getOperand(0);
3859 EVT VT = Op.getValueType();
3862 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3863 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3865 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3866 SDValue UaddLV = DAG.getNode(
3867 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3868 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3871 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3875 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3877 if (Op.getValueType().isVector())
3878 return LowerVSETCC(Op, DAG);
3880 SDValue LHS = Op.getOperand(0);
3881 SDValue RHS = Op.getOperand(1);
3882 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3885 // We chose ZeroOrOneBooleanContents, so use zero and one.
3886 EVT VT = Op.getValueType();
3887 SDValue TVal = DAG.getConstant(1, dl, VT);
3888 SDValue FVal = DAG.getConstant(0, dl, VT);
3890 // Handle f128 first, since one possible outcome is a normal integer
3891 // comparison which gets picked up by the next if statement.
3892 if (LHS.getValueType() == MVT::f128) {
3893 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3895 // If softenSetCCOperands returned a scalar, use it.
3896 if (!RHS.getNode()) {
3897 assert(LHS.getValueType() == Op.getValueType() &&
3898 "Unexpected setcc expansion!");
3903 if (LHS.getValueType().isInteger()) {
3906 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3908 // Note that we inverted the condition above, so we reverse the order of
3909 // the true and false operands here. This will allow the setcc to be
3910 // matched to a single CSINC instruction.
3911 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3914 // Now we know we're dealing with FP values.
3915 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3917 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3918 // and do the comparison.
3919 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3921 AArch64CC::CondCode CC1, CC2;
3922 changeFPCCToAArch64CC(CC, CC1, CC2);
3923 if (CC2 == AArch64CC::AL) {
3924 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3925 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3927 // Note that we inverted the condition above, so we reverse the order of
3928 // the true and false operands here. This will allow the setcc to be
3929 // matched to a single CSINC instruction.
3930 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3932 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3933 // totally clean. Some of them require two CSELs to implement. As is in
3934 // this case, we emit the first CSEL and then emit a second using the output
3935 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3937 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3938 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3940 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3942 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3943 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3947 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3948 SDValue RHS, SDValue TVal,
3949 SDValue FVal, const SDLoc &dl,
3950 SelectionDAG &DAG) const {
3951 // Handle f128 first, because it will result in a comparison of some RTLIB
3952 // call result against zero.
3953 if (LHS.getValueType() == MVT::f128) {
3954 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3956 // If softenSetCCOperands returned a scalar, we need to compare the result
3957 // against zero to select between true and false values.
3958 if (!RHS.getNode()) {
3959 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3964 // Also handle f16, for which we need to do a f32 comparison.
3965 if (LHS.getValueType() == MVT::f16) {
3966 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3967 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3970 // Next, handle integers.
3971 if (LHS.getValueType().isInteger()) {
3972 assert((LHS.getValueType() == RHS.getValueType()) &&
3973 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3975 unsigned Opcode = AArch64ISD::CSEL;
3977 // If both the TVal and the FVal are constants, see if we can swap them in
3978 // order to for a CSINV or CSINC out of them.
3979 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3980 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3982 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3983 std::swap(TVal, FVal);
3984 std::swap(CTVal, CFVal);
3985 CC = ISD::getSetCCInverse(CC, true);
3986 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3987 std::swap(TVal, FVal);
3988 std::swap(CTVal, CFVal);
3989 CC = ISD::getSetCCInverse(CC, true);
3990 } else if (TVal.getOpcode() == ISD::XOR) {
3991 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3992 // with a CSINV rather than a CSEL.
3993 if (isAllOnesConstant(TVal.getOperand(1))) {
3994 std::swap(TVal, FVal);
3995 std::swap(CTVal, CFVal);
3996 CC = ISD::getSetCCInverse(CC, true);
3998 } else if (TVal.getOpcode() == ISD::SUB) {
3999 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4000 // that we can match with a CSNEG rather than a CSEL.
4001 if (isNullConstant(TVal.getOperand(0))) {
4002 std::swap(TVal, FVal);
4003 std::swap(CTVal, CFVal);
4004 CC = ISD::getSetCCInverse(CC, true);
4006 } else if (CTVal && CFVal) {
4007 const int64_t TrueVal = CTVal->getSExtValue();
4008 const int64_t FalseVal = CFVal->getSExtValue();
4011 // If both TVal and FVal are constants, see if FVal is the
4012 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4013 // instead of a CSEL in that case.
4014 if (TrueVal == ~FalseVal) {
4015 Opcode = AArch64ISD::CSINV;
4016 } else if (TrueVal == -FalseVal) {
4017 Opcode = AArch64ISD::CSNEG;
4018 } else if (TVal.getValueType() == MVT::i32) {
4019 // If our operands are only 32-bit wide, make sure we use 32-bit
4020 // arithmetic for the check whether we can use CSINC. This ensures that
4021 // the addition in the check will wrap around properly in case there is
4022 // an overflow (which would not be the case if we do the check with
4023 // 64-bit arithmetic).
4024 const uint32_t TrueVal32 = CTVal->getZExtValue();
4025 const uint32_t FalseVal32 = CFVal->getZExtValue();
4027 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4028 Opcode = AArch64ISD::CSINC;
4030 if (TrueVal32 > FalseVal32) {
4034 // 64-bit check whether we can use CSINC.
4035 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4036 Opcode = AArch64ISD::CSINC;
4038 if (TrueVal > FalseVal) {
4043 // Swap TVal and FVal if necessary.
4045 std::swap(TVal, FVal);
4046 std::swap(CTVal, CFVal);
4047 CC = ISD::getSetCCInverse(CC, true);
4050 if (Opcode != AArch64ISD::CSEL) {
4051 // Drop FVal since we can get its value by simply inverting/negating
4057 // Avoid materializing a constant when possible by reusing a known value in
4058 // a register. However, don't perform this optimization if the known value
4059 // is one, zero or negative one in the case of a CSEL. We can always
4060 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4061 // FVal, respectively.
4062 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4063 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4064 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4065 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4066 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4067 // "a != C ? x : a" to avoid materializing C.
4068 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4070 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4072 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4073 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4074 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4075 // avoid materializing C.
4076 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4077 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4078 Opcode = AArch64ISD::CSINV;
4080 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4085 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4087 EVT VT = TVal.getValueType();
4088 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4091 // Now we know we're dealing with FP values.
4092 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4093 assert(LHS.getValueType() == RHS.getValueType());
4094 EVT VT = TVal.getValueType();
4095 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4097 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4098 // clean. Some of them require two CSELs to implement.
4099 AArch64CC::CondCode CC1, CC2;
4100 changeFPCCToAArch64CC(CC, CC1, CC2);
4102 if (DAG.getTarget().Options.UnsafeFPMath) {
4103 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4104 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4105 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4106 if (RHSVal && RHSVal->isZero()) {
4107 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4108 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4110 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4111 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4113 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4114 CFVal && CFVal->isZero() &&
4115 FVal.getValueType() == LHS.getValueType())
4120 // Emit first, and possibly only, CSEL.
4121 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4122 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4124 // If we need a second CSEL, emit it, using the output of the first as the
4125 // RHS. We're effectively OR'ing the two CC's together.
4126 if (CC2 != AArch64CC::AL) {
4127 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4128 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4131 // Otherwise, return the output of the first CSEL.
4135 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4136 SelectionDAG &DAG) const {
4137 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4138 SDValue LHS = Op.getOperand(0);
4139 SDValue RHS = Op.getOperand(1);
4140 SDValue TVal = Op.getOperand(2);
4141 SDValue FVal = Op.getOperand(3);
4143 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4146 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4147 SelectionDAG &DAG) const {
4148 SDValue CCVal = Op->getOperand(0);
4149 SDValue TVal = Op->getOperand(1);
4150 SDValue FVal = Op->getOperand(2);
4153 unsigned Opc = CCVal.getOpcode();
4154 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4156 if (CCVal.getResNo() == 1 &&
4157 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4158 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4159 // Only lower legal XALUO ops.
4160 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4163 AArch64CC::CondCode OFCC;
4164 SDValue Value, Overflow;
4165 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4166 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4168 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4172 // Lower it the same way as we would lower a SELECT_CC node.
4175 if (CCVal.getOpcode() == ISD::SETCC) {
4176 LHS = CCVal.getOperand(0);
4177 RHS = CCVal.getOperand(1);
4178 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4181 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4184 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4187 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4188 SelectionDAG &DAG) const {
4189 // Jump table entries as PC relative offsets. No additional tweaking
4190 // is necessary here. Just get the address of the jump table.
4191 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4192 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4195 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4196 !Subtarget->isTargetMachO()) {
4197 const unsigned char MO_NC = AArch64II::MO_NC;
4199 AArch64ISD::WrapperLarge, DL, PtrVT,
4200 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4201 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4202 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4203 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4204 AArch64II::MO_G0 | MO_NC));
4208 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4209 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4210 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4211 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4212 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4215 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4216 SelectionDAG &DAG) const {
4217 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4218 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4221 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4222 // Use the GOT for the large code model on iOS.
4223 if (Subtarget->isTargetMachO()) {
4224 SDValue GotAddr = DAG.getTargetConstantPool(
4225 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4227 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4230 const unsigned char MO_NC = AArch64II::MO_NC;
4232 AArch64ISD::WrapperLarge, DL, PtrVT,
4233 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4234 CP->getOffset(), AArch64II::MO_G3),
4235 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4236 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4237 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4238 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4239 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4240 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4242 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4243 // ELF, the only valid one on Darwin.
4245 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4246 CP->getOffset(), AArch64II::MO_PAGE);
4247 SDValue Lo = DAG.getTargetConstantPool(
4248 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4249 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4251 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4252 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4256 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4257 SelectionDAG &DAG) const {
4258 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4259 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4261 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4262 !Subtarget->isTargetMachO()) {
4263 const unsigned char MO_NC = AArch64II::MO_NC;
4265 AArch64ISD::WrapperLarge, DL, PtrVT,
4266 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4267 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4268 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4269 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4271 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4272 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4274 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4275 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4279 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4280 SelectionDAG &DAG) const {
4281 AArch64FunctionInfo *FuncInfo =
4282 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4285 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4286 getPointerTy(DAG.getDataLayout()));
4287 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4288 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4289 MachinePointerInfo(SV));
4292 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4293 SelectionDAG &DAG) const {
4294 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4295 // Standard, section B.3.
4296 MachineFunction &MF = DAG.getMachineFunction();
4297 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4298 auto PtrVT = getPointerTy(DAG.getDataLayout());
4301 SDValue Chain = Op.getOperand(0);
4302 SDValue VAList = Op.getOperand(1);
4303 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4304 SmallVector<SDValue, 4> MemOps;
4306 // void *__stack at offset 0
4307 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4308 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4309 MachinePointerInfo(SV), /* Alignment = */ 8));
4311 // void *__gr_top at offset 8
4312 int GPRSize = FuncInfo->getVarArgsGPRSize();
4314 SDValue GRTop, GRTopAddr;
4317 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4319 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4320 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4321 DAG.getConstant(GPRSize, DL, PtrVT));
4323 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4324 MachinePointerInfo(SV, 8),
4325 /* Alignment = */ 8));
4328 // void *__vr_top at offset 16
4329 int FPRSize = FuncInfo->getVarArgsFPRSize();
4331 SDValue VRTop, VRTopAddr;
4332 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4333 DAG.getConstant(16, DL, PtrVT));
4335 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4336 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4337 DAG.getConstant(FPRSize, DL, PtrVT));
4339 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4340 MachinePointerInfo(SV, 16),
4341 /* Alignment = */ 8));
4344 // int __gr_offs at offset 24
4345 SDValue GROffsAddr =
4346 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4347 MemOps.push_back(DAG.getStore(
4348 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4349 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4351 // int __vr_offs at offset 28
4352 SDValue VROffsAddr =
4353 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4354 MemOps.push_back(DAG.getStore(
4355 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4356 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4358 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4361 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4362 SelectionDAG &DAG) const {
4363 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4364 : LowerAAPCS_VASTART(Op, DAG);
4367 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4368 SelectionDAG &DAG) const {
4369 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4372 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4373 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4374 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4376 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4378 DAG.getConstant(VaListSize, DL, MVT::i32),
4379 8, false, false, false, MachinePointerInfo(DestSV),
4380 MachinePointerInfo(SrcSV));
4383 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4384 assert(Subtarget->isTargetDarwin() &&
4385 "automatic va_arg instruction only works on Darwin");
4387 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4388 EVT VT = Op.getValueType();
4390 SDValue Chain = Op.getOperand(0);
4391 SDValue Addr = Op.getOperand(1);
4392 unsigned Align = Op.getConstantOperandVal(3);
4393 auto PtrVT = getPointerTy(DAG.getDataLayout());
4395 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4396 Chain = VAList.getValue(1);
4399 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4400 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4401 DAG.getConstant(Align - 1, DL, PtrVT));
4402 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4403 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4406 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4407 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4409 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4410 // up to 64 bits. At the very least, we have to increase the striding of the
4411 // vaargs list to match this, and for FP values we need to introduce
4412 // FP_ROUND nodes as well.
4413 if (VT.isInteger() && !VT.isVector())
4415 bool NeedFPTrunc = false;
4416 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4421 // Increment the pointer, VAList, to the next vaarg
4422 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4423 DAG.getConstant(ArgSize, DL, PtrVT));
4424 // Store the incremented VAList to the legalized pointer
4426 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4428 // Load the actual argument out of the pointer VAList
4430 // Load the value as an f64.
4432 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4433 // Round the value down to an f32.
4434 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4435 DAG.getIntPtrConstant(1, DL));
4436 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4437 // Merge the rounded value with the chain output of the load.
4438 return DAG.getMergeValues(Ops, DL);
4441 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4444 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4445 SelectionDAG &DAG) const {
4446 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4447 MFI.setFrameAddressIsTaken(true);
4449 EVT VT = Op.getValueType();
4451 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4453 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4455 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4456 MachinePointerInfo());
4460 // FIXME? Maybe this could be a TableGen attribute on some registers and
4461 // this table could be generated automatically from RegInfo.
4462 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4463 SelectionDAG &DAG) const {
4464 unsigned Reg = StringSwitch<unsigned>(RegName)
4465 .Case("sp", AArch64::SP)
4469 report_fatal_error(Twine("Invalid register name \""
4470 + StringRef(RegName) + "\"."));
4473 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4474 SelectionDAG &DAG) const {
4475 MachineFunction &MF = DAG.getMachineFunction();
4476 MachineFrameInfo &MFI = MF.getFrameInfo();
4477 MFI.setReturnAddressIsTaken(true);
4479 EVT VT = Op.getValueType();
4481 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4483 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4484 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4485 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4486 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4487 MachinePointerInfo());
4490 // Return LR, which contains the return address. Mark it an implicit live-in.
4491 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4492 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4495 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4496 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4497 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4498 SelectionDAG &DAG) const {
4499 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4500 EVT VT = Op.getValueType();
4501 unsigned VTBits = VT.getSizeInBits();
4503 SDValue ShOpLo = Op.getOperand(0);
4504 SDValue ShOpHi = Op.getOperand(1);
4505 SDValue ShAmt = Op.getOperand(2);
4506 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4508 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4510 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4511 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4512 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4514 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4515 // is "undef". We wanted 0, so CSEL it directly.
4516 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4517 ISD::SETEQ, dl, DAG);
4518 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4520 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4521 HiBitsForLo, CCVal, Cmp);
4523 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4524 DAG.getConstant(VTBits, dl, MVT::i64));
4526 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4527 SDValue LoForNormalShift =
4528 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4530 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4532 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4533 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4534 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4535 LoForNormalShift, CCVal, Cmp);
4537 // AArch64 shifts larger than the register width are wrapped rather than
4538 // clamped, so we can't just emit "hi >> x".
4539 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4540 SDValue HiForBigShift =
4542 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4543 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4544 : DAG.getConstant(0, dl, VT);
4545 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4546 HiForNormalShift, CCVal, Cmp);
4548 SDValue Ops[2] = { Lo, Hi };
4549 return DAG.getMergeValues(Ops, dl);
4553 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4554 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4555 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4556 SelectionDAG &DAG) const {
4557 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4558 EVT VT = Op.getValueType();
4559 unsigned VTBits = VT.getSizeInBits();
4561 SDValue ShOpLo = Op.getOperand(0);
4562 SDValue ShOpHi = Op.getOperand(1);
4563 SDValue ShAmt = Op.getOperand(2);
4565 assert(Op.getOpcode() == ISD::SHL_PARTS);
4566 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4567 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4568 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4570 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4571 // is "undef". We wanted 0, so CSEL it directly.
4572 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4573 ISD::SETEQ, dl, DAG);
4574 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4576 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4577 LoBitsForHi, CCVal, Cmp);
4579 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4580 DAG.getConstant(VTBits, dl, MVT::i64));
4581 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4582 SDValue HiForNormalShift =
4583 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4585 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4587 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4589 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4590 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4591 HiForNormalShift, CCVal, Cmp);
4593 // AArch64 shifts of larger than register sizes are wrapped rather than
4594 // clamped, so we can't just emit "lo << a" if a is too big.
4595 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4596 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4597 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4598 LoForNormalShift, CCVal, Cmp);
4600 SDValue Ops[2] = { Lo, Hi };
4601 return DAG.getMergeValues(Ops, dl);
4604 bool AArch64TargetLowering::isOffsetFoldingLegal(
4605 const GlobalAddressSDNode *GA) const {
4606 // The AArch64 target doesn't support folding offsets into global addresses.
4610 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4611 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4612 // FIXME: We should be able to handle f128 as well with a clever lowering.
4613 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4617 return AArch64_AM::getFP64Imm(Imm) != -1;
4618 else if (VT == MVT::f32)
4619 return AArch64_AM::getFP32Imm(Imm) != -1;
4623 //===----------------------------------------------------------------------===//
4624 // AArch64 Optimization Hooks
4625 //===----------------------------------------------------------------------===//
4627 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4628 SDValue Operand, SelectionDAG &DAG,
4630 EVT VT = Operand.getValueType();
4631 if (ST->hasNEON() &&
4632 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4633 VT == MVT::f32 || VT == MVT::v1f32 ||
4634 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4635 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4636 // For the reciprocal estimates, convergence is quadratic, so the number
4637 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4638 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4639 // the result for float (23 mantissa bits) is 2 and for double (52
4640 // mantissa bits) is 3.
4641 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4643 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4649 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4650 SelectionDAG &DAG, int Enabled,
4653 bool Reciprocal) const {
4654 if (Enabled == ReciprocalEstimate::Enabled ||
4655 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4656 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4659 EVT VT = Operand.getValueType();
4662 Flags.setUnsafeAlgebra(true);
4664 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4665 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4666 for (int i = ExtraSteps; i > 0; --i) {
4667 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4669 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4670 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4674 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4676 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4677 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4679 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4680 // Correct the result if the operand is 0.0.
4681 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4682 VT, Eq, Operand, Estimate);
4692 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4693 SelectionDAG &DAG, int Enabled,
4694 int &ExtraSteps) const {
4695 if (Enabled == ReciprocalEstimate::Enabled)
4696 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4699 EVT VT = Operand.getValueType();
4702 Flags.setUnsafeAlgebra(true);
4704 // Newton reciprocal iteration: E * (2 - X * E)
4705 // AArch64 reciprocal iteration instruction: (2 - M * N)
4706 for (int i = ExtraSteps; i > 0; --i) {
4707 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4709 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4719 //===----------------------------------------------------------------------===//
4720 // AArch64 Inline Assembly Support
4721 //===----------------------------------------------------------------------===//
4723 // Table of Constraints
4724 // TODO: This is the current set of constraints supported by ARM for the
4725 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4727 // r - A general register
4728 // w - An FP/SIMD register of some size in the range v0-v31
4729 // x - An FP/SIMD register of some size in the range v0-v15
4730 // I - Constant that can be used with an ADD instruction
4731 // J - Constant that can be used with a SUB instruction
4732 // K - Constant that can be used with a 32-bit logical instruction
4733 // L - Constant that can be used with a 64-bit logical instruction
4734 // M - Constant that can be used as a 32-bit MOV immediate
4735 // N - Constant that can be used as a 64-bit MOV immediate
4736 // Q - A memory reference with base register and no offset
4737 // S - A symbolic address
4738 // Y - Floating point constant zero
4739 // Z - Integer constant zero
4741 // Note that general register operands will be output using their 64-bit x
4742 // register name, whatever the size of the variable, unless the asm operand
4743 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4744 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4746 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4747 // At this point, we have to lower this constraint to something else, so we
4748 // lower it to an "r" or "w". However, by doing this we will force the result
4749 // to be in register, while the X constraint is much more permissive.
4751 // Although we are correct (we are free to emit anything, without
4752 // constraints), we might break use cases that would expect us to be more
4753 // efficient and emit something else.
4754 if (!Subtarget->hasFPARMv8())
4757 if (ConstraintVT.isFloatingPoint())
4760 if (ConstraintVT.isVector() &&
4761 (ConstraintVT.getSizeInBits() == 64 ||
4762 ConstraintVT.getSizeInBits() == 128))
4768 /// getConstraintType - Given a constraint letter, return the type of
4769 /// constraint it is for this target.
4770 AArch64TargetLowering::ConstraintType
4771 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4772 if (Constraint.size() == 1) {
4773 switch (Constraint[0]) {
4780 return C_RegisterClass;
4781 // An address with a single base register. Due to the way we
4782 // currently handle addresses it is the same as 'r'.
4787 return TargetLowering::getConstraintType(Constraint);
4790 /// Examine constraint type and operand type and determine a weight value.
4791 /// This object must already have been set up with the operand type
4792 /// and the current alternative constraint selected.
4793 TargetLowering::ConstraintWeight
4794 AArch64TargetLowering::getSingleConstraintMatchWeight(
4795 AsmOperandInfo &info, const char *constraint) const {
4796 ConstraintWeight weight = CW_Invalid;
4797 Value *CallOperandVal = info.CallOperandVal;
4798 // If we don't have a value, we can't do a match,
4799 // but allow it at the lowest weight.
4800 if (!CallOperandVal)
4802 Type *type = CallOperandVal->getType();
4803 // Look at the constraint type.
4804 switch (*constraint) {
4806 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4810 if (type->isFloatingPointTy() || type->isVectorTy())
4811 weight = CW_Register;
4814 weight = CW_Constant;
4820 std::pair<unsigned, const TargetRegisterClass *>
4821 AArch64TargetLowering::getRegForInlineAsmConstraint(
4822 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4823 if (Constraint.size() == 1) {
4824 switch (Constraint[0]) {
4826 if (VT.getSizeInBits() == 64)
4827 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4828 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4830 if (VT.getSizeInBits() == 16)
4831 return std::make_pair(0U, &AArch64::FPR16RegClass);
4832 if (VT.getSizeInBits() == 32)
4833 return std::make_pair(0U, &AArch64::FPR32RegClass);
4834 if (VT.getSizeInBits() == 64)
4835 return std::make_pair(0U, &AArch64::FPR64RegClass);
4836 if (VT.getSizeInBits() == 128)
4837 return std::make_pair(0U, &AArch64::FPR128RegClass);
4839 // The instructions that this constraint is designed for can
4840 // only take 128-bit registers so just use that regclass.
4842 if (VT.getSizeInBits() == 128)
4843 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4847 if (StringRef("{cc}").equals_lower(Constraint))
4848 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4850 // Use the default implementation in TargetLowering to convert the register
4851 // constraint into a member of a register class.
4852 std::pair<unsigned, const TargetRegisterClass *> Res;
4853 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4855 // Not found as a standard register?
4857 unsigned Size = Constraint.size();
4858 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4859 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4861 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4862 if (!Failed && RegNo >= 0 && RegNo <= 31) {
4863 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4864 // By default we'll emit v0-v31 for this unless there's a modifier where
4865 // we'll emit the correct register as well.
4866 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4867 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4868 Res.second = &AArch64::FPR64RegClass;
4870 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4871 Res.second = &AArch64::FPR128RegClass;
4880 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4881 /// vector. If it is invalid, don't add anything to Ops.
4882 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4883 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4884 SelectionDAG &DAG) const {
4887 // Currently only support length 1 constraints.
4888 if (Constraint.length() != 1)
4891 char ConstraintLetter = Constraint[0];
4892 switch (ConstraintLetter) {
4896 // This set of constraints deal with valid constants for various instructions.
4897 // Validate and return a target constant for them if we can.
4899 // 'z' maps to xzr or wzr so it needs an input of 0.
4900 if (!isNullConstant(Op))
4903 if (Op.getValueType() == MVT::i64)
4904 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4906 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4916 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4920 // Grab the value and do some validation.
4921 uint64_t CVal = C->getZExtValue();
4922 switch (ConstraintLetter) {
4923 // The I constraint applies only to simple ADD or SUB immediate operands:
4924 // i.e. 0 to 4095 with optional shift by 12
4925 // The J constraint applies only to ADD or SUB immediates that would be
4926 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4927 // instruction [or vice versa], in other words -1 to -4095 with optional
4928 // left shift by 12.
4930 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4934 uint64_t NVal = -C->getSExtValue();
4935 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4936 CVal = C->getSExtValue();
4941 // The K and L constraints apply *only* to logical immediates, including
4942 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4943 // been removed and MOV should be used). So these constraints have to
4944 // distinguish between bit patterns that are valid 32-bit or 64-bit
4945 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4946 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4949 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4953 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4956 // The M and N constraints are a superset of K and L respectively, for use
4957 // with the MOV (immediate) alias. As well as the logical immediates they
4958 // also match 32 or 64-bit immediates that can be loaded either using a
4959 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4960 // (M) or 64-bit 0x1234000000000000 (N) etc.
4961 // As a note some of this code is liberally stolen from the asm parser.
4963 if (!isUInt<32>(CVal))
4965 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4967 if ((CVal & 0xFFFF) == CVal)
4969 if ((CVal & 0xFFFF0000ULL) == CVal)
4971 uint64_t NCVal = ~(uint32_t)CVal;
4972 if ((NCVal & 0xFFFFULL) == NCVal)
4974 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4979 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4981 if ((CVal & 0xFFFFULL) == CVal)
4983 if ((CVal & 0xFFFF0000ULL) == CVal)
4985 if ((CVal & 0xFFFF00000000ULL) == CVal)
4987 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4989 uint64_t NCVal = ~CVal;
4990 if ((NCVal & 0xFFFFULL) == NCVal)
4992 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4994 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4996 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5004 // All assembler immediates are 64-bit integers.
5005 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5009 if (Result.getNode()) {
5010 Ops.push_back(Result);
5014 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5017 //===----------------------------------------------------------------------===//
5018 // AArch64 Advanced SIMD Support
5019 //===----------------------------------------------------------------------===//
5021 /// WidenVector - Given a value in the V64 register class, produce the
5022 /// equivalent value in the V128 register class.
5023 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5024 EVT VT = V64Reg.getValueType();
5025 unsigned NarrowSize = VT.getVectorNumElements();
5026 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5027 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5030 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5031 V64Reg, DAG.getConstant(0, DL, MVT::i32));
5034 /// getExtFactor - Determine the adjustment factor for the position when
5035 /// generating an "extract from vector registers" instruction.
5036 static unsigned getExtFactor(SDValue &V) {
5037 EVT EltType = V.getValueType().getVectorElementType();
5038 return EltType.getSizeInBits() / 8;
5041 /// NarrowVector - Given a value in the V128 register class, produce the
5042 /// equivalent value in the V64 register class.
5043 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5044 EVT VT = V128Reg.getValueType();
5045 unsigned WideSize = VT.getVectorNumElements();
5046 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5047 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5050 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5053 // Gather data to see if the operation can be modelled as a
5054 // shuffle in combination with VEXTs.
5055 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5056 SelectionDAG &DAG) const {
5057 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5059 EVT VT = Op.getValueType();
5060 unsigned NumElts = VT.getVectorNumElements();
5062 struct ShuffleSourceInfo {
5067 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5068 // be compatible with the shuffle we intend to construct. As a result
5069 // ShuffleVec will be some sliding window into the original Vec.
5072 // Code should guarantee that element i in Vec starts at element "WindowBase
5073 // + i * WindowScale in ShuffleVec".
5077 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5078 ShuffleSourceInfo(SDValue Vec)
5079 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5083 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5085 SmallVector<ShuffleSourceInfo, 2> Sources;
5086 for (unsigned i = 0; i < NumElts; ++i) {
5087 SDValue V = Op.getOperand(i);
5090 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5091 !isa<ConstantSDNode>(V.getOperand(1))) {
5092 // A shuffle can only come from building a vector from various
5093 // elements of other vectors, provided their indices are constant.
5097 // Add this element source to the list if it's not already there.
5098 SDValue SourceVec = V.getOperand(0);
5099 auto Source = find(Sources, SourceVec);
5100 if (Source == Sources.end())
5101 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5103 // Update the minimum and maximum lane number seen.
5104 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5105 Source->MinElt = std::min(Source->MinElt, EltNo);
5106 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5109 // Currently only do something sane when at most two source vectors
5111 if (Sources.size() > 2)
5114 // Find out the smallest element size among result and two sources, and use
5115 // it as element size to build the shuffle_vector.
5116 EVT SmallestEltTy = VT.getVectorElementType();
5117 for (auto &Source : Sources) {
5118 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5119 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5120 SmallestEltTy = SrcEltTy;
5123 unsigned ResMultiplier =
5124 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5125 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5126 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5128 // If the source vector is too wide or too narrow, we may nevertheless be able
5129 // to construct a compatible shuffle either by concatenating it with UNDEF or
5130 // extracting a suitable range of elements.
5131 for (auto &Src : Sources) {
5132 EVT SrcVT = Src.ShuffleVec.getValueType();
5134 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5137 // This stage of the search produces a source with the same element type as
5138 // the original, but with a total width matching the BUILD_VECTOR output.
5139 EVT EltVT = SrcVT.getVectorElementType();
5140 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5141 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5143 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5144 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5145 // We can pad out the smaller vector for free, so if it's part of a
5148 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5149 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5153 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5155 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5156 // Span too large for a VEXT to cope
5160 if (Src.MinElt >= NumSrcElts) {
5161 // The extraction can just take the second half
5163 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5164 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5165 Src.WindowBase = -NumSrcElts;
5166 } else if (Src.MaxElt < NumSrcElts) {
5167 // The extraction can just take the first half
5169 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5170 DAG.getConstant(0, dl, MVT::i64));
5172 // An actual VEXT is needed
5174 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5175 DAG.getConstant(0, dl, MVT::i64));
5177 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5178 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5179 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5181 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5183 DAG.getConstant(Imm, dl, MVT::i32));
5184 Src.WindowBase = -Src.MinElt;
5188 // Another possible incompatibility occurs from the vector element types. We
5189 // can fix this by bitcasting the source vectors to the same type we intend
5191 for (auto &Src : Sources) {
5192 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5193 if (SrcEltTy == SmallestEltTy)
5195 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5196 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5197 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5198 Src.WindowBase *= Src.WindowScale;
5201 // Final sanity check before we try to actually produce a shuffle.
5203 for (auto Src : Sources)
5204 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5207 // The stars all align, our next step is to produce the mask for the shuffle.
5208 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5209 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5210 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5211 SDValue Entry = Op.getOperand(i);
5212 if (Entry.isUndef())
5215 auto Src = find(Sources, Entry.getOperand(0));
5216 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5218 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5219 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5221 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5223 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5224 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5226 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5227 // starting at the appropriate offset.
5228 int *LaneMask = &Mask[i * ResMultiplier];
5230 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5231 ExtractBase += NumElts * (Src - Sources.begin());
5232 for (int j = 0; j < LanesDefined; ++j)
5233 LaneMask[j] = ExtractBase + j;
5236 // Final check before we try to produce nonsense...
5237 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5240 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5241 for (unsigned i = 0; i < Sources.size(); ++i)
5242 ShuffleOps[i] = Sources[i].ShuffleVec;
5244 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5245 ShuffleOps[1], Mask);
5246 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5249 // check if an EXT instruction can handle the shuffle mask when the
5250 // vector sources of the shuffle are the same.
5251 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5252 unsigned NumElts = VT.getVectorNumElements();
5254 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5260 // If this is a VEXT shuffle, the immediate value is the index of the first
5261 // element. The other shuffle indices must be the successive elements after
5263 unsigned ExpectedElt = Imm;
5264 for (unsigned i = 1; i < NumElts; ++i) {
5265 // Increment the expected index. If it wraps around, just follow it
5266 // back to index zero and keep going.
5268 if (ExpectedElt == NumElts)
5272 continue; // ignore UNDEF indices
5273 if (ExpectedElt != static_cast<unsigned>(M[i]))
5280 // check if an EXT instruction can handle the shuffle mask when the
5281 // vector sources of the shuffle are different.
5282 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5284 // Look for the first non-undef element.
5285 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5287 // Benefit form APInt to handle overflow when calculating expected element.
5288 unsigned NumElts = VT.getVectorNumElements();
5289 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5290 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5291 // The following shuffle indices must be the successive elements after the
5292 // first real element.
5293 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5294 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5295 if (FirstWrongElt != M.end())
5298 // The index of an EXT is the first element if it is not UNDEF.
5299 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5300 // value of the first element. E.g.
5301 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5302 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5303 // ExpectedElt is the last mask index plus 1.
5304 Imm = ExpectedElt.getZExtValue();
5306 // There are two difference cases requiring to reverse input vectors.
5307 // For example, for vector <4 x i32> we have the following cases,
5308 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5309 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5310 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5311 // to reverse two input vectors.
5320 /// isREVMask - Check if a vector shuffle corresponds to a REV
5321 /// instruction with the specified blocksize. (The order of the elements
5322 /// within each block of the vector is reversed.)
5323 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5324 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5325 "Only possible block sizes for REV are: 16, 32, 64");
5327 unsigned EltSz = VT.getScalarSizeInBits();
5331 unsigned NumElts = VT.getVectorNumElements();
5332 unsigned BlockElts = M[0] + 1;
5333 // If the first shuffle index is UNDEF, be optimistic.
5335 BlockElts = BlockSize / EltSz;
5337 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5340 for (unsigned i = 0; i < NumElts; ++i) {
5342 continue; // ignore UNDEF indices
5343 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5350 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5351 unsigned NumElts = VT.getVectorNumElements();
5352 WhichResult = (M[0] == 0 ? 0 : 1);
5353 unsigned Idx = WhichResult * NumElts / 2;
5354 for (unsigned i = 0; i != NumElts; i += 2) {
5355 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5356 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5364 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5365 unsigned NumElts = VT.getVectorNumElements();
5366 WhichResult = (M[0] == 0 ? 0 : 1);
5367 for (unsigned i = 0; i != NumElts; ++i) {
5369 continue; // ignore UNDEF indices
5370 if ((unsigned)M[i] != 2 * i + WhichResult)
5377 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5378 unsigned NumElts = VT.getVectorNumElements();
5379 WhichResult = (M[0] == 0 ? 0 : 1);
5380 for (unsigned i = 0; i < NumElts; i += 2) {
5381 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5382 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5388 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5389 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5390 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5391 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5392 unsigned NumElts = VT.getVectorNumElements();
5393 WhichResult = (M[0] == 0 ? 0 : 1);
5394 unsigned Idx = WhichResult * NumElts / 2;
5395 for (unsigned i = 0; i != NumElts; i += 2) {
5396 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5397 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5405 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5406 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5407 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5408 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5409 unsigned Half = VT.getVectorNumElements() / 2;
5410 WhichResult = (M[0] == 0 ? 0 : 1);
5411 for (unsigned j = 0; j != 2; ++j) {
5412 unsigned Idx = WhichResult;
5413 for (unsigned i = 0; i != Half; ++i) {
5414 int MIdx = M[i + j * Half];
5415 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5424 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5425 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5426 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5427 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5428 unsigned NumElts = VT.getVectorNumElements();
5429 WhichResult = (M[0] == 0 ? 0 : 1);
5430 for (unsigned i = 0; i < NumElts; i += 2) {
5431 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5432 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5438 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5439 bool &DstIsLeft, int &Anomaly) {
5440 if (M.size() != static_cast<size_t>(NumInputElements))
5443 int NumLHSMatch = 0, NumRHSMatch = 0;
5444 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5446 for (int i = 0; i < NumInputElements; ++i) {
5456 LastLHSMismatch = i;
5458 if (M[i] == i + NumInputElements)
5461 LastRHSMismatch = i;
5464 if (NumLHSMatch == NumInputElements - 1) {
5466 Anomaly = LastLHSMismatch;
5468 } else if (NumRHSMatch == NumInputElements - 1) {
5470 Anomaly = LastRHSMismatch;
5477 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5478 if (VT.getSizeInBits() != 128)
5481 unsigned NumElts = VT.getVectorNumElements();
5483 for (int I = 0, E = NumElts / 2; I != E; I++) {
5488 int Offset = NumElts / 2;
5489 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5490 if (Mask[I] != I + SplitLHS * Offset)
5497 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5499 EVT VT = Op.getValueType();
5500 SDValue V0 = Op.getOperand(0);
5501 SDValue V1 = Op.getOperand(1);
5502 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5504 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5505 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5508 bool SplitV0 = V0.getValueSizeInBits() == 128;
5510 if (!isConcatMask(Mask, VT, SplitV0))
5513 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5514 VT.getVectorNumElements() / 2);
5516 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5517 DAG.getConstant(0, DL, MVT::i64));
5519 if (V1.getValueSizeInBits() == 128) {
5520 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5521 DAG.getConstant(0, DL, MVT::i64));
5523 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5526 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5527 /// the specified operations to build the shuffle.
5528 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5529 SDValue RHS, SelectionDAG &DAG,
5531 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5532 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5533 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5536 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5545 OP_VUZPL, // VUZP, left result
5546 OP_VUZPR, // VUZP, right result
5547 OP_VZIPL, // VZIP, left result
5548 OP_VZIPR, // VZIP, right result
5549 OP_VTRNL, // VTRN, left result
5550 OP_VTRNR // VTRN, right result
5553 if (OpNum == OP_COPY) {
5554 if (LHSID == (1 * 9 + 2) * 9 + 3)
5556 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5560 SDValue OpLHS, OpRHS;
5561 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5562 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5563 EVT VT = OpLHS.getValueType();
5567 llvm_unreachable("Unknown shuffle opcode!");
5569 // VREV divides the vector in half and swaps within the half.
5570 if (VT.getVectorElementType() == MVT::i32 ||
5571 VT.getVectorElementType() == MVT::f32)
5572 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5573 // vrev <4 x i16> -> REV32
5574 if (VT.getVectorElementType() == MVT::i16 ||
5575 VT.getVectorElementType() == MVT::f16)
5576 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5577 // vrev <4 x i8> -> REV16
5578 assert(VT.getVectorElementType() == MVT::i8);
5579 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5584 EVT EltTy = VT.getVectorElementType();
5586 if (EltTy == MVT::i8)
5587 Opcode = AArch64ISD::DUPLANE8;
5588 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5589 Opcode = AArch64ISD::DUPLANE16;
5590 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5591 Opcode = AArch64ISD::DUPLANE32;
5592 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5593 Opcode = AArch64ISD::DUPLANE64;
5595 llvm_unreachable("Invalid vector element type?");
5597 if (VT.getSizeInBits() == 64)
5598 OpLHS = WidenVector(OpLHS, DAG);
5599 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5600 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5605 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5606 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5607 DAG.getConstant(Imm, dl, MVT::i32));
5610 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5613 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5616 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5619 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5622 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5625 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5630 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5631 SelectionDAG &DAG) {
5632 // Check to see if we can use the TBL instruction.
5633 SDValue V1 = Op.getOperand(0);
5634 SDValue V2 = Op.getOperand(1);
5637 EVT EltVT = Op.getValueType().getVectorElementType();
5638 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5640 SmallVector<SDValue, 8> TBLMask;
5641 for (int Val : ShuffleMask) {
5642 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5643 unsigned Offset = Byte + Val * BytesPerElt;
5644 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5648 MVT IndexVT = MVT::v8i8;
5649 unsigned IndexLen = 8;
5650 if (Op.getValueSizeInBits() == 128) {
5651 IndexVT = MVT::v16i8;
5655 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5656 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5659 if (V2.getNode()->isUndef()) {
5661 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5662 Shuffle = DAG.getNode(
5663 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5664 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5665 DAG.getBuildVector(IndexVT, DL,
5666 makeArrayRef(TBLMask.data(), IndexLen)));
5668 if (IndexLen == 8) {
5669 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5670 Shuffle = DAG.getNode(
5671 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5672 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5673 DAG.getBuildVector(IndexVT, DL,
5674 makeArrayRef(TBLMask.data(), IndexLen)));
5676 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5677 // cannot currently represent the register constraints on the input
5679 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5680 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5682 Shuffle = DAG.getNode(
5683 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5684 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5685 V2Cst, DAG.getBuildVector(IndexVT, DL,
5686 makeArrayRef(TBLMask.data(), IndexLen)));
5689 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5692 static unsigned getDUPLANEOp(EVT EltType) {
5693 if (EltType == MVT::i8)
5694 return AArch64ISD::DUPLANE8;
5695 if (EltType == MVT::i16 || EltType == MVT::f16)
5696 return AArch64ISD::DUPLANE16;
5697 if (EltType == MVT::i32 || EltType == MVT::f32)
5698 return AArch64ISD::DUPLANE32;
5699 if (EltType == MVT::i64 || EltType == MVT::f64)
5700 return AArch64ISD::DUPLANE64;
5702 llvm_unreachable("Invalid vector element type?");
5705 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5706 SelectionDAG &DAG) const {
5708 EVT VT = Op.getValueType();
5710 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5712 // Convert shuffles that are directly supported on NEON to target-specific
5713 // DAG nodes, instead of keeping them as shuffles and matching them again
5714 // during code selection. This is more efficient and avoids the possibility
5715 // of inconsistencies between legalization and selection.
5716 ArrayRef<int> ShuffleMask = SVN->getMask();
5718 SDValue V1 = Op.getOperand(0);
5719 SDValue V2 = Op.getOperand(1);
5721 if (SVN->isSplat()) {
5722 int Lane = SVN->getSplatIndex();
5723 // If this is undef splat, generate it via "just" vdup, if possible.
5727 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5728 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5730 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5731 // constant. If so, we can just reference the lane's definition directly.
5732 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5733 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5734 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5736 // Otherwise, duplicate from the lane of the input vector.
5737 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5739 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5740 // to make a vector of the same size as this SHUFFLE. We can ignore the
5741 // extract entirely, and canonicalise the concat using WidenVector.
5742 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5743 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5744 V1 = V1.getOperand(0);
5745 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5746 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5747 Lane -= Idx * VT.getVectorNumElements() / 2;
5748 V1 = WidenVector(V1.getOperand(Idx), DAG);
5749 } else if (VT.getSizeInBits() == 64)
5750 V1 = WidenVector(V1, DAG);
5752 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5755 if (isREVMask(ShuffleMask, VT, 64))
5756 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5757 if (isREVMask(ShuffleMask, VT, 32))
5758 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5759 if (isREVMask(ShuffleMask, VT, 16))
5760 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5762 bool ReverseEXT = false;
5764 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5767 Imm *= getExtFactor(V1);
5768 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5769 DAG.getConstant(Imm, dl, MVT::i32));
5770 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5771 Imm *= getExtFactor(V1);
5772 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5773 DAG.getConstant(Imm, dl, MVT::i32));
5776 unsigned WhichResult;
5777 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5778 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5779 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5781 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5782 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5783 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5785 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5786 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5787 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5790 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5791 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5792 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5794 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5795 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5796 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5798 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5799 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5800 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5803 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5808 int NumInputElements = V1.getValueType().getVectorNumElements();
5809 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5810 SDValue DstVec = DstIsLeft ? V1 : V2;
5811 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5813 SDValue SrcVec = V1;
5814 int SrcLane = ShuffleMask[Anomaly];
5815 if (SrcLane >= NumInputElements) {
5817 SrcLane -= VT.getVectorNumElements();
5819 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5821 EVT ScalarVT = VT.getVectorElementType();
5823 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5824 ScalarVT = MVT::i32;
5827 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5828 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5832 // If the shuffle is not directly supported and it has 4 elements, use
5833 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5834 unsigned NumElts = VT.getVectorNumElements();
5836 unsigned PFIndexes[4];
5837 for (unsigned i = 0; i != 4; ++i) {
5838 if (ShuffleMask[i] < 0)
5841 PFIndexes[i] = ShuffleMask[i];
5844 // Compute the index in the perfect shuffle table.
5845 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5846 PFIndexes[2] * 9 + PFIndexes[3];
5847 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5848 unsigned Cost = (PFEntry >> 30);
5851 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5854 return GenerateTBL(Op, ShuffleMask, DAG);
5857 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5859 EVT VT = BVN->getValueType(0);
5860 APInt SplatBits, SplatUndef;
5861 unsigned SplatBitSize;
5863 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5864 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5866 for (unsigned i = 0; i < NumSplats; ++i) {
5867 CnstBits <<= SplatBitSize;
5868 UndefBits <<= SplatBitSize;
5869 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5870 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5879 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5880 SelectionDAG &DAG) const {
5881 BuildVectorSDNode *BVN =
5882 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5883 SDValue LHS = Op.getOperand(0);
5885 EVT VT = Op.getValueType();
5890 APInt CnstBits(VT.getSizeInBits(), 0);
5891 APInt UndefBits(VT.getSizeInBits(), 0);
5892 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5893 // We only have BIC vector immediate instruction, which is and-not.
5894 CnstBits = ~CnstBits;
5896 // We make use of a little bit of goto ickiness in order to avoid having to
5897 // duplicate the immediate matching logic for the undef toggled case.
5898 bool SecondTry = false;
5901 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5902 CnstBits = CnstBits.zextOrTrunc(64);
5903 uint64_t CnstVal = CnstBits.getZExtValue();
5905 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5906 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5907 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5908 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5909 DAG.getConstant(CnstVal, dl, MVT::i32),
5910 DAG.getConstant(0, dl, MVT::i32));
5911 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5914 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5915 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5916 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5917 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5918 DAG.getConstant(CnstVal, dl, MVT::i32),
5919 DAG.getConstant(8, dl, MVT::i32));
5920 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5923 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5924 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5925 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5926 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5927 DAG.getConstant(CnstVal, dl, MVT::i32),
5928 DAG.getConstant(16, dl, MVT::i32));
5929 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5932 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5933 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5934 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5935 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5936 DAG.getConstant(CnstVal, dl, MVT::i32),
5937 DAG.getConstant(24, dl, MVT::i32));
5938 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5941 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5942 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5943 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5944 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5945 DAG.getConstant(CnstVal, dl, MVT::i32),
5946 DAG.getConstant(0, dl, MVT::i32));
5947 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5950 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5951 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5952 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5953 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5954 DAG.getConstant(CnstVal, dl, MVT::i32),
5955 DAG.getConstant(8, dl, MVT::i32));
5956 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5963 CnstBits = ~UndefBits;
5967 // We can always fall back to a non-immediate AND.
5972 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5973 // consists of only the same constant int value, returned in reference arg
5975 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5976 uint64_t &ConstVal) {
5977 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5980 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5983 EVT VT = Bvec->getValueType(0);
5984 unsigned NumElts = VT.getVectorNumElements();
5985 for (unsigned i = 1; i < NumElts; ++i)
5986 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5988 ConstVal = FirstElt->getZExtValue();
5992 static unsigned getIntrinsicID(const SDNode *N) {
5993 unsigned Opcode = N->getOpcode();
5996 return Intrinsic::not_intrinsic;
5997 case ISD::INTRINSIC_WO_CHAIN: {
5998 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5999 if (IID < Intrinsic::num_intrinsics)
6001 return Intrinsic::not_intrinsic;
6006 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6007 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6008 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6009 // Also, logical shift right -> sri, with the same structure.
6010 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6011 EVT VT = N->getValueType(0);
6018 // Is the first op an AND?
6019 const SDValue And = N->getOperand(0);
6020 if (And.getOpcode() != ISD::AND)
6023 // Is the second op an shl or lshr?
6024 SDValue Shift = N->getOperand(1);
6025 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6026 // or AArch64ISD::VLSHR vector, #shift
6027 unsigned ShiftOpc = Shift.getOpcode();
6028 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6030 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6032 // Is the shift amount constant?
6033 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6037 // Is the and mask vector all constant?
6039 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6042 // Is C1 == ~C2, taking into account how much one can shift elements of a
6044 uint64_t C2 = C2node->getZExtValue();
6045 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6046 if (C2 > ElemSizeInBits)
6048 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6049 if ((C1 & ElemMask) != (~C2 & ElemMask))
6052 SDValue X = And.getOperand(0);
6053 SDValue Y = Shift.getOperand(0);
6056 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6058 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6059 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6060 Shift.getOperand(1));
6062 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6063 DEBUG(N->dump(&DAG));
6064 DEBUG(dbgs() << "into: \n");
6065 DEBUG(ResultSLI->dump(&DAG));
6071 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6072 SelectionDAG &DAG) const {
6073 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6074 if (EnableAArch64SlrGeneration) {
6075 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6079 BuildVectorSDNode *BVN =
6080 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6081 SDValue LHS = Op.getOperand(1);
6083 EVT VT = Op.getValueType();
6085 // OR commutes, so try swapping the operands.
6087 LHS = Op.getOperand(0);
6088 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6093 APInt CnstBits(VT.getSizeInBits(), 0);
6094 APInt UndefBits(VT.getSizeInBits(), 0);
6095 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6096 // We make use of a little bit of goto ickiness in order to avoid having to
6097 // duplicate the immediate matching logic for the undef toggled case.
6098 bool SecondTry = false;
6101 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6102 CnstBits = CnstBits.zextOrTrunc(64);
6103 uint64_t CnstVal = CnstBits.getZExtValue();
6105 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6106 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6107 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6108 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6109 DAG.getConstant(CnstVal, dl, MVT::i32),
6110 DAG.getConstant(0, dl, MVT::i32));
6111 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6114 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6115 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6116 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6117 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6118 DAG.getConstant(CnstVal, dl, MVT::i32),
6119 DAG.getConstant(8, dl, MVT::i32));
6120 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6123 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6124 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6125 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6126 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6127 DAG.getConstant(CnstVal, dl, MVT::i32),
6128 DAG.getConstant(16, dl, MVT::i32));
6129 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6132 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6133 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6134 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6135 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6136 DAG.getConstant(CnstVal, dl, MVT::i32),
6137 DAG.getConstant(24, dl, MVT::i32));
6138 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6141 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6142 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6143 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6144 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6145 DAG.getConstant(CnstVal, dl, MVT::i32),
6146 DAG.getConstant(0, dl, MVT::i32));
6147 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6150 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6151 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6152 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6153 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6154 DAG.getConstant(CnstVal, dl, MVT::i32),
6155 DAG.getConstant(8, dl, MVT::i32));
6156 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6163 CnstBits = UndefBits;
6167 // We can always fall back to a non-immediate OR.
6172 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6173 // be truncated to fit element width.
6174 static SDValue NormalizeBuildVector(SDValue Op,
6175 SelectionDAG &DAG) {
6176 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6178 EVT VT = Op.getValueType();
6179 EVT EltTy= VT.getVectorElementType();
6181 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6184 SmallVector<SDValue, 16> Ops;
6185 for (SDValue Lane : Op->ops()) {
6186 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6187 APInt LowBits(EltTy.getSizeInBits(),
6188 CstLane->getZExtValue());
6189 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6191 Ops.push_back(Lane);
6193 return DAG.getBuildVector(VT, dl, Ops);
6196 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6197 SelectionDAG &DAG) const {
6199 EVT VT = Op.getValueType();
6200 Op = NormalizeBuildVector(Op, DAG);
6201 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6203 APInt CnstBits(VT.getSizeInBits(), 0);
6204 APInt UndefBits(VT.getSizeInBits(), 0);
6205 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6206 // We make use of a little bit of goto ickiness in order to avoid having to
6207 // duplicate the immediate matching logic for the undef toggled case.
6208 bool SecondTry = false;
6211 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6212 CnstBits = CnstBits.zextOrTrunc(64);
6213 uint64_t CnstVal = CnstBits.getZExtValue();
6215 // Certain magic vector constants (used to express things like NOT
6216 // and NEG) are passed through unmodified. This allows codegen patterns
6217 // for these operations to match. Special-purpose patterns will lower
6218 // these immediates to MOVIs if it proves necessary.
6219 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6222 // The many faces of MOVI...
6223 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6224 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6225 if (VT.getSizeInBits() == 128) {
6226 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6227 DAG.getConstant(CnstVal, dl, MVT::i32));
6228 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6231 // Support the V64 version via subregister insertion.
6232 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6233 DAG.getConstant(CnstVal, dl, MVT::i32));
6234 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6237 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6238 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6239 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6240 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6241 DAG.getConstant(CnstVal, dl, MVT::i32),
6242 DAG.getConstant(0, dl, MVT::i32));
6243 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6246 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6247 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6248 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6249 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6250 DAG.getConstant(CnstVal, dl, MVT::i32),
6251 DAG.getConstant(8, dl, MVT::i32));
6252 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6255 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6256 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6257 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6258 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6259 DAG.getConstant(CnstVal, dl, MVT::i32),
6260 DAG.getConstant(16, dl, MVT::i32));
6261 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6264 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6265 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6266 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6267 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6268 DAG.getConstant(CnstVal, dl, MVT::i32),
6269 DAG.getConstant(24, dl, MVT::i32));
6270 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6273 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6274 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6275 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6276 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6277 DAG.getConstant(CnstVal, dl, MVT::i32),
6278 DAG.getConstant(0, dl, MVT::i32));
6279 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6282 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6283 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6284 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6285 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6286 DAG.getConstant(CnstVal, dl, MVT::i32),
6287 DAG.getConstant(8, dl, MVT::i32));
6288 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6291 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6292 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6293 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6294 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6295 DAG.getConstant(CnstVal, dl, MVT::i32),
6296 DAG.getConstant(264, dl, MVT::i32));
6297 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6300 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6301 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6302 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6303 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6304 DAG.getConstant(CnstVal, dl, MVT::i32),
6305 DAG.getConstant(272, dl, MVT::i32));
6306 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6309 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6310 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6311 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6312 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6313 DAG.getConstant(CnstVal, dl, MVT::i32));
6314 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6317 // The few faces of FMOV...
6318 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6319 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6320 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6321 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6322 DAG.getConstant(CnstVal, dl, MVT::i32));
6323 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6326 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6327 VT.getSizeInBits() == 128) {
6328 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6329 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6330 DAG.getConstant(CnstVal, dl, MVT::i32));
6331 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6334 // The many faces of MVNI...
6336 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6337 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6338 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6339 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6340 DAG.getConstant(CnstVal, dl, MVT::i32),
6341 DAG.getConstant(0, dl, MVT::i32));
6342 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6345 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6346 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6347 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6348 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6349 DAG.getConstant(CnstVal, dl, MVT::i32),
6350 DAG.getConstant(8, dl, MVT::i32));
6351 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6354 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6355 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6356 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6357 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6358 DAG.getConstant(CnstVal, dl, MVT::i32),
6359 DAG.getConstant(16, dl, MVT::i32));
6360 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6363 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6364 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6365 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6366 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6367 DAG.getConstant(CnstVal, dl, MVT::i32),
6368 DAG.getConstant(24, dl, MVT::i32));
6369 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6372 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6373 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6374 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6375 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6376 DAG.getConstant(CnstVal, dl, MVT::i32),
6377 DAG.getConstant(0, dl, MVT::i32));
6378 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6381 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6382 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6383 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6384 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6385 DAG.getConstant(CnstVal, dl, MVT::i32),
6386 DAG.getConstant(8, dl, MVT::i32));
6387 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6390 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6391 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6392 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6393 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6394 DAG.getConstant(CnstVal, dl, MVT::i32),
6395 DAG.getConstant(264, dl, MVT::i32));
6396 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6399 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6400 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6401 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6402 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6403 DAG.getConstant(CnstVal, dl, MVT::i32),
6404 DAG.getConstant(272, dl, MVT::i32));
6405 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6412 CnstBits = UndefBits;
6417 // Scan through the operands to find some interesting properties we can
6419 // 1) If only one value is used, we can use a DUP, or
6420 // 2) if only the low element is not undef, we can just insert that, or
6421 // 3) if only one constant value is used (w/ some non-constant lanes),
6422 // we can splat the constant value into the whole vector then fill
6423 // in the non-constant lanes.
6424 // 4) FIXME: If different constant values are used, but we can intelligently
6425 // select the values we'll be overwriting for the non-constant
6426 // lanes such that we can directly materialize the vector
6427 // some other way (MOVI, e.g.), we can be sneaky.
6428 unsigned NumElts = VT.getVectorNumElements();
6429 bool isOnlyLowElement = true;
6430 bool usesOnlyOneValue = true;
6431 bool usesOnlyOneConstantValue = true;
6432 bool isConstant = true;
6433 unsigned NumConstantLanes = 0;
6435 SDValue ConstantValue;
6436 for (unsigned i = 0; i < NumElts; ++i) {
6437 SDValue V = Op.getOperand(i);
6441 isOnlyLowElement = false;
6442 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6445 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6447 if (!ConstantValue.getNode())
6449 else if (ConstantValue != V)
6450 usesOnlyOneConstantValue = false;
6453 if (!Value.getNode())
6455 else if (V != Value)
6456 usesOnlyOneValue = false;
6459 if (!Value.getNode())
6460 return DAG.getUNDEF(VT);
6462 if (isOnlyLowElement)
6463 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6465 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6466 // i32 and try again.
6467 if (usesOnlyOneValue) {
6469 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6470 Value.getValueType() != VT)
6471 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6473 // This is actually a DUPLANExx operation, which keeps everything vectory.
6475 // DUPLANE works on 128-bit vectors, widen it if necessary.
6476 SDValue Lane = Value.getOperand(1);
6477 Value = Value.getOperand(0);
6478 if (Value.getValueSizeInBits() == 64)
6479 Value = WidenVector(Value, DAG);
6481 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6482 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6485 if (VT.getVectorElementType().isFloatingPoint()) {
6486 SmallVector<SDValue, 8> Ops;
6487 EVT EltTy = VT.getVectorElementType();
6488 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6489 "Unsupported floating-point vector type");
6490 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6491 for (unsigned i = 0; i < NumElts; ++i)
6492 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6493 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6494 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6495 Val = LowerBUILD_VECTOR(Val, DAG);
6497 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6501 // If there was only one constant value used and for more than one lane,
6502 // start by splatting that value, then replace the non-constant lanes. This
6503 // is better than the default, which will perform a separate initialization
6505 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6506 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6507 // Now insert the non-constant lanes.
6508 for (unsigned i = 0; i < NumElts; ++i) {
6509 SDValue V = Op.getOperand(i);
6510 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6511 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6512 // Note that type legalization likely mucked about with the VT of the
6513 // source operand, so we may have to convert it here before inserting.
6514 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6520 // If all elements are constants and the case above didn't get hit, fall back
6521 // to the default expansion, which will generate a load from the constant
6526 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6528 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6532 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6533 // know the default expansion would otherwise fall back on something even
6534 // worse. For a vector with one or two non-undef values, that's
6535 // scalar_to_vector for the elements followed by a shuffle (provided the
6536 // shuffle is valid for the target) and materialization element by element
6537 // on the stack followed by a load for everything else.
6538 if (!isConstant && !usesOnlyOneValue) {
6539 SDValue Vec = DAG.getUNDEF(VT);
6540 SDValue Op0 = Op.getOperand(0);
6541 unsigned ElemSize = VT.getScalarSizeInBits();
6543 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6544 // a) Avoid a RMW dependency on the full vector register, and
6545 // b) Allow the register coalescer to fold away the copy if the
6546 // value is already in an S or D register.
6547 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6548 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6549 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
6550 (ElemSize == 32 || ElemSize == 64)) {
6551 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6553 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6554 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6555 Vec = SDValue(N, 0);
6558 for (; i < NumElts; ++i) {
6559 SDValue V = Op.getOperand(i);
6562 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6563 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6568 // Just use the default expansion. We failed to find a better alternative.
6572 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6573 SelectionDAG &DAG) const {
6574 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6576 // Check for non-constant or out of range lane.
6577 EVT VT = Op.getOperand(0).getValueType();
6578 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6579 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6583 // Insertion/extraction are legal for V128 types.
6584 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6585 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6589 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6590 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6593 // For V64 types, we perform insertion by expanding the value
6594 // to a V128 type and perform the insertion on that.
6596 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6597 EVT WideTy = WideVec.getValueType();
6599 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6600 Op.getOperand(1), Op.getOperand(2));
6601 // Re-narrow the resultant vector.
6602 return NarrowVector(Node, DAG);
6606 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6607 SelectionDAG &DAG) const {
6608 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6610 // Check for non-constant or out of range lane.
6611 EVT VT = Op.getOperand(0).getValueType();
6612 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6613 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6617 // Insertion/extraction are legal for V128 types.
6618 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6619 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6623 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6624 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6627 // For V64 types, we perform extraction by expanding the value
6628 // to a V128 type and perform the extraction on that.
6630 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6631 EVT WideTy = WideVec.getValueType();
6633 EVT ExtrTy = WideTy.getVectorElementType();
6634 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6637 // For extractions, we just return the result directly.
6638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6642 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6643 SelectionDAG &DAG) const {
6644 EVT VT = Op.getOperand(0).getValueType();
6650 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6653 unsigned Val = Cst->getZExtValue();
6655 unsigned Size = Op.getValueSizeInBits();
6657 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6661 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6663 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6669 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6671 if (VT.getVectorNumElements() == 4 &&
6672 (VT.is128BitVector() || VT.is64BitVector())) {
6673 unsigned PFIndexes[4];
6674 for (unsigned i = 0; i != 4; ++i) {
6678 PFIndexes[i] = M[i];
6681 // Compute the index in the perfect shuffle table.
6682 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6683 PFIndexes[2] * 9 + PFIndexes[3];
6684 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6685 unsigned Cost = (PFEntry >> 30);
6693 unsigned DummyUnsigned;
6695 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6696 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6697 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6698 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6699 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6700 isZIPMask(M, VT, DummyUnsigned) ||
6701 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6702 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6703 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6704 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6705 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6708 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6709 /// operand of a vector shift operation, where all the elements of the
6710 /// build_vector must have the same constant integer value.
6711 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6712 // Ignore bit_converts.
6713 while (Op.getOpcode() == ISD::BITCAST)
6714 Op = Op.getOperand(0);
6715 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6716 APInt SplatBits, SplatUndef;
6717 unsigned SplatBitSize;
6719 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6720 HasAnyUndefs, ElementBits) ||
6721 SplatBitSize > ElementBits)
6723 Cnt = SplatBits.getSExtValue();
6727 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6728 /// operand of a vector shift left operation. That value must be in the range:
6729 /// 0 <= Value < ElementBits for a left shift; or
6730 /// 0 <= Value <= ElementBits for a long left shift.
6731 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6732 assert(VT.isVector() && "vector shift count is not a vector type");
6733 int64_t ElementBits = VT.getScalarSizeInBits();
6734 if (!getVShiftImm(Op, ElementBits, Cnt))
6736 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6739 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6740 /// operand of a vector shift right operation. The value must be in the range:
6741 /// 1 <= Value <= ElementBits for a right shift; or
6742 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6743 assert(VT.isVector() && "vector shift count is not a vector type");
6744 int64_t ElementBits = VT.getScalarSizeInBits();
6745 if (!getVShiftImm(Op, ElementBits, Cnt))
6747 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6750 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6751 SelectionDAG &DAG) const {
6752 EVT VT = Op.getValueType();
6756 if (!Op.getOperand(1).getValueType().isVector())
6758 unsigned EltSize = VT.getScalarSizeInBits();
6760 switch (Op.getOpcode()) {
6762 llvm_unreachable("unexpected shift opcode");
6765 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6766 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6767 DAG.getConstant(Cnt, DL, MVT::i32));
6768 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6769 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6771 Op.getOperand(0), Op.getOperand(1));
6774 // Right shift immediate
6775 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6777 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6778 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6779 DAG.getConstant(Cnt, DL, MVT::i32));
6782 // Right shift register. Note, there is not a shift right register
6783 // instruction, but the shift left register instruction takes a signed
6784 // value, where negative numbers specify a right shift.
6785 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6786 : Intrinsic::aarch64_neon_ushl;
6787 // negate the shift amount
6788 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6789 SDValue NegShiftLeft =
6790 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6791 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6793 return NegShiftLeft;
6799 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6800 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6801 const SDLoc &dl, SelectionDAG &DAG) {
6802 EVT SrcVT = LHS.getValueType();
6803 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6804 "function only supposed to emit natural comparisons");
6806 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6807 APInt CnstBits(VT.getSizeInBits(), 0);
6808 APInt UndefBits(VT.getSizeInBits(), 0);
6809 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6810 bool IsZero = IsCnst && (CnstBits == 0);
6812 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6816 case AArch64CC::NE: {
6819 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6821 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6822 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6826 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6827 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6830 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6831 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6834 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6835 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6838 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6839 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6843 // If we ignore NaNs then we can use to the MI implementation.
6847 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6848 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6855 case AArch64CC::NE: {
6858 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6860 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6861 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6865 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6866 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6869 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6870 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6873 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6874 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6877 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6878 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6880 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6882 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6885 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6886 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6888 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6890 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6894 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6895 SelectionDAG &DAG) const {
6896 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6897 SDValue LHS = Op.getOperand(0);
6898 SDValue RHS = Op.getOperand(1);
6899 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6902 if (LHS.getValueType().getVectorElementType().isInteger()) {
6903 assert(LHS.getValueType() == RHS.getValueType());
6904 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6906 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6907 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6910 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6913 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6914 LHS.getValueType().getVectorElementType() == MVT::f64);
6916 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6917 // clean. Some of them require two branches to implement.
6918 AArch64CC::CondCode CC1, CC2;
6920 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6922 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6924 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6928 if (CC2 != AArch64CC::AL) {
6930 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6931 if (!Cmp2.getNode())
6934 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6937 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6940 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6945 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6946 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6947 /// specified in the intrinsic calls.
6948 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6950 unsigned Intrinsic) const {
6951 auto &DL = I.getModule()->getDataLayout();
6952 switch (Intrinsic) {
6953 case Intrinsic::aarch64_neon_ld2:
6954 case Intrinsic::aarch64_neon_ld3:
6955 case Intrinsic::aarch64_neon_ld4:
6956 case Intrinsic::aarch64_neon_ld1x2:
6957 case Intrinsic::aarch64_neon_ld1x3:
6958 case Intrinsic::aarch64_neon_ld1x4:
6959 case Intrinsic::aarch64_neon_ld2lane:
6960 case Intrinsic::aarch64_neon_ld3lane:
6961 case Intrinsic::aarch64_neon_ld4lane:
6962 case Intrinsic::aarch64_neon_ld2r:
6963 case Intrinsic::aarch64_neon_ld3r:
6964 case Intrinsic::aarch64_neon_ld4r: {
6965 Info.opc = ISD::INTRINSIC_W_CHAIN;
6966 // Conservatively set memVT to the entire set of vectors loaded.
6967 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6968 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6969 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6972 Info.vol = false; // volatile loads with NEON intrinsics not supported
6973 Info.readMem = true;
6974 Info.writeMem = false;
6977 case Intrinsic::aarch64_neon_st2:
6978 case Intrinsic::aarch64_neon_st3:
6979 case Intrinsic::aarch64_neon_st4:
6980 case Intrinsic::aarch64_neon_st1x2:
6981 case Intrinsic::aarch64_neon_st1x3:
6982 case Intrinsic::aarch64_neon_st1x4:
6983 case Intrinsic::aarch64_neon_st2lane:
6984 case Intrinsic::aarch64_neon_st3lane:
6985 case Intrinsic::aarch64_neon_st4lane: {
6986 Info.opc = ISD::INTRINSIC_VOID;
6987 // Conservatively set memVT to the entire set of vectors stored.
6988 unsigned NumElts = 0;
6989 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6990 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6991 if (!ArgTy->isVectorTy())
6993 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6995 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6996 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6999 Info.vol = false; // volatile stores with NEON intrinsics not supported
7000 Info.readMem = false;
7001 Info.writeMem = true;
7004 case Intrinsic::aarch64_ldaxr:
7005 case Intrinsic::aarch64_ldxr: {
7006 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7007 Info.opc = ISD::INTRINSIC_W_CHAIN;
7008 Info.memVT = MVT::getVT(PtrTy->getElementType());
7009 Info.ptrVal = I.getArgOperand(0);
7011 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7013 Info.readMem = true;
7014 Info.writeMem = false;
7017 case Intrinsic::aarch64_stlxr:
7018 case Intrinsic::aarch64_stxr: {
7019 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7020 Info.opc = ISD::INTRINSIC_W_CHAIN;
7021 Info.memVT = MVT::getVT(PtrTy->getElementType());
7022 Info.ptrVal = I.getArgOperand(1);
7024 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7026 Info.readMem = false;
7027 Info.writeMem = true;
7030 case Intrinsic::aarch64_ldaxp:
7031 case Intrinsic::aarch64_ldxp: {
7032 Info.opc = ISD::INTRINSIC_W_CHAIN;
7033 Info.memVT = MVT::i128;
7034 Info.ptrVal = I.getArgOperand(0);
7038 Info.readMem = true;
7039 Info.writeMem = false;
7042 case Intrinsic::aarch64_stlxp:
7043 case Intrinsic::aarch64_stxp: {
7044 Info.opc = ISD::INTRINSIC_W_CHAIN;
7045 Info.memVT = MVT::i128;
7046 Info.ptrVal = I.getArgOperand(2);
7050 Info.readMem = false;
7051 Info.writeMem = true;
7061 // Truncations from 64-bit GPR to 32-bit GPR is free.
7062 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7063 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7065 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7066 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7067 return NumBits1 > NumBits2;
7069 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7070 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7072 unsigned NumBits1 = VT1.getSizeInBits();
7073 unsigned NumBits2 = VT2.getSizeInBits();
7074 return NumBits1 > NumBits2;
7077 /// Check if it is profitable to hoist instruction in then/else to if.
7078 /// Not profitable if I and it's user can form a FMA instruction
7079 /// because we prefer FMSUB/FMADD.
7080 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7081 if (I->getOpcode() != Instruction::FMul)
7084 if (I->getNumUses() != 1)
7087 Instruction *User = I->user_back();
7090 !(User->getOpcode() == Instruction::FSub ||
7091 User->getOpcode() == Instruction::FAdd))
7094 const TargetOptions &Options = getTargetMachine().Options;
7095 const DataLayout &DL = I->getModule()->getDataLayout();
7096 EVT VT = getValueType(DL, User->getOperand(0)->getType());
7098 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7099 isOperationLegalOrCustom(ISD::FMA, VT) &&
7100 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7101 Options.UnsafeFPMath));
7104 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7106 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7107 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7109 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7110 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7111 return NumBits1 == 32 && NumBits2 == 64;
7113 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7114 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7116 unsigned NumBits1 = VT1.getSizeInBits();
7117 unsigned NumBits2 = VT2.getSizeInBits();
7118 return NumBits1 == 32 && NumBits2 == 64;
7121 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7122 EVT VT1 = Val.getValueType();
7123 if (isZExtFree(VT1, VT2)) {
7127 if (Val.getOpcode() != ISD::LOAD)
7130 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7131 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7132 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7133 VT1.getSizeInBits() <= 32);
7136 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7137 if (isa<FPExtInst>(Ext))
7140 // Vector types are next free.
7141 if (Ext->getType()->isVectorTy())
7144 for (const Use &U : Ext->uses()) {
7145 // The extension is free if we can fold it with a left shift in an
7146 // addressing mode or an arithmetic operation: add, sub, and cmp.
7148 // Is there a shift?
7149 const Instruction *Instr = cast<Instruction>(U.getUser());
7151 // Is this a constant shift?
7152 switch (Instr->getOpcode()) {
7153 case Instruction::Shl:
7154 if (!isa<ConstantInt>(Instr->getOperand(1)))
7157 case Instruction::GetElementPtr: {
7158 gep_type_iterator GTI = gep_type_begin(Instr);
7159 auto &DL = Ext->getModule()->getDataLayout();
7160 std::advance(GTI, U.getOperandNo()-1);
7161 Type *IdxTy = GTI.getIndexedType();
7162 // This extension will end up with a shift because of the scaling factor.
7163 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7164 // Get the shift amount based on the scaling factor:
7165 // log2(sizeof(IdxTy)) - log2(8).
7167 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7168 // Is the constant foldable in the shift of the addressing mode?
7169 // I.e., shift amount is between 1 and 4 inclusive.
7170 if (ShiftAmt == 0 || ShiftAmt > 4)
7174 case Instruction::Trunc:
7175 // Check if this is a noop.
7176 // trunc(sext ty1 to ty2) to ty1.
7177 if (Instr->getType() == Ext->getOperand(0)->getType())
7184 // At this point we can use the bfm family, so this extension is free
7190 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7191 unsigned &RequiredAligment) const {
7192 if (!LoadedType.isSimple() ||
7193 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7195 // Cyclone supports unaligned accesses.
7196 RequiredAligment = 0;
7197 unsigned NumBits = LoadedType.getSizeInBits();
7198 return NumBits == 32 || NumBits == 64;
7201 /// \brief Lower an interleaved load into a ldN intrinsic.
7203 /// E.g. Lower an interleaved load (Factor = 2):
7204 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7205 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7206 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7209 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7210 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7211 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7212 bool AArch64TargetLowering::lowerInterleavedLoad(
7213 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7214 ArrayRef<unsigned> Indices, unsigned Factor) const {
7215 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7216 "Invalid interleave factor");
7217 assert(!Shuffles.empty() && "Empty shufflevector input");
7218 assert(Shuffles.size() == Indices.size() &&
7219 "Unmatched number of shufflevectors and indices");
7221 const DataLayout &DL = LI->getModule()->getDataLayout();
7223 VectorType *VecTy = Shuffles[0]->getType();
7224 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7226 // Skip if we do not have NEON and skip illegal vector types.
7227 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7230 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7231 // load integer vectors first and then convert to pointer vectors.
7232 Type *EltTy = VecTy->getVectorElementType();
7233 if (EltTy->isPointerTy())
7235 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7237 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7238 Type *Tys[2] = {VecTy, PtrTy};
7239 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7240 Intrinsic::aarch64_neon_ld3,
7241 Intrinsic::aarch64_neon_ld4};
7243 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7245 IRBuilder<> Builder(LI);
7246 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7248 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7250 // Replace uses of each shufflevector with the corresponding vector loaded
7252 for (unsigned i = 0; i < Shuffles.size(); i++) {
7253 ShuffleVectorInst *SVI = Shuffles[i];
7254 unsigned Index = Indices[i];
7256 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7258 // Convert the integer vector to pointer vector if the element is pointer.
7259 if (EltTy->isPointerTy())
7260 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7262 SVI->replaceAllUsesWith(SubVec);
7268 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7270 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7271 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7273 SmallVector<Constant *, 16> Mask;
7274 for (unsigned i = 0; i < NumElts; i++)
7275 Mask.push_back(Builder.getInt32(Start + i));
7277 return ConstantVector::get(Mask);
7280 /// \brief Lower an interleaved store into a stN intrinsic.
7282 /// E.g. Lower an interleaved store (Factor = 3):
7283 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7284 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7285 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7288 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7289 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7290 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7291 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7293 /// Note that the new shufflevectors will be removed and we'll only generate one
7294 /// st3 instruction in CodeGen.
7296 /// Example for a more general valid mask (Factor 3). Lower:
7297 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7298 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7299 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7302 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7303 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7304 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7305 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7306 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7307 ShuffleVectorInst *SVI,
7308 unsigned Factor) const {
7309 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7310 "Invalid interleave factor");
7312 VectorType *VecTy = SVI->getType();
7313 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7314 "Invalid interleaved store");
7316 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7317 Type *EltTy = VecTy->getVectorElementType();
7318 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7320 const DataLayout &DL = SI->getModule()->getDataLayout();
7321 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7323 // Skip if we do not have NEON and skip illegal vector types.
7324 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7327 Value *Op0 = SVI->getOperand(0);
7328 Value *Op1 = SVI->getOperand(1);
7329 IRBuilder<> Builder(SI);
7331 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7332 // vectors to integer vectors.
7333 if (EltTy->isPointerTy()) {
7334 Type *IntTy = DL.getIntPtrType(EltTy);
7335 unsigned NumOpElts =
7336 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7338 // Convert to the corresponding integer vector.
7339 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7340 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7341 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7343 SubVecTy = VectorType::get(IntTy, LaneLen);
7346 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7347 Type *Tys[2] = {SubVecTy, PtrTy};
7348 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7349 Intrinsic::aarch64_neon_st3,
7350 Intrinsic::aarch64_neon_st4};
7352 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7354 SmallVector<Value *, 5> Ops;
7356 // Split the shufflevector operands into sub vectors for the new stN call.
7357 auto Mask = SVI->getShuffleMask();
7358 for (unsigned i = 0; i < Factor; i++) {
7360 Ops.push_back(Builder.CreateShuffleVector(
7361 Op0, Op1, getSequentialMask(Builder, Mask[i], LaneLen)));
7363 unsigned StartMask = 0;
7364 for (unsigned j = 1; j < LaneLen; j++) {
7365 if (Mask[j*Factor + i] >= 0) {
7366 StartMask = Mask[j*Factor + i] - j;
7370 // Note: If all elements in a chunk are undefs, StartMask=0!
7371 // Note: Filling undef gaps with random elements is ok, since
7372 // those elements were being written anyway (with undefs).
7373 // In the case of all undefs we're defaulting to using elems from 0
7374 // Note: StartMask cannot be negative, it's checked in isReInterleaveMask
7375 Ops.push_back(Builder.CreateShuffleVector(
7376 Op0, Op1, getSequentialMask(Builder, StartMask, LaneLen)));
7380 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7381 Builder.CreateCall(StNFunc, Ops);
7385 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7386 unsigned AlignCheck) {
7387 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7388 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7391 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7392 unsigned SrcAlign, bool IsMemset,
7395 MachineFunction &MF) const {
7396 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7397 // instruction to materialize the v2i64 zero and one store (with restrictive
7398 // addressing mode). Just do two i64 store of zero-registers.
7400 const Function *F = MF.getFunction();
7401 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7402 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7403 (memOpAlign(SrcAlign, DstAlign, 16) ||
7404 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7408 (memOpAlign(SrcAlign, DstAlign, 8) ||
7409 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7413 (memOpAlign(SrcAlign, DstAlign, 4) ||
7414 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7420 // 12-bit optionally shifted immediates are legal for adds.
7421 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7422 // Avoid UB for INT64_MIN.
7423 if (Immed == std::numeric_limits<int64_t>::min())
7425 // Same encoding for add/sub, just flip the sign.
7426 Immed = std::abs(Immed);
7427 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7430 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7431 // immediates is the same as for an add or a sub.
7432 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7433 return isLegalAddImmediate(Immed);
7436 /// isLegalAddressingMode - Return true if the addressing mode represented
7437 /// by AM is legal for this target, for a load/store of the specified type.
7438 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7439 const AddrMode &AM, Type *Ty,
7440 unsigned AS) const {
7441 // AArch64 has five basic addressing modes:
7443 // reg + 9-bit signed offset
7444 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7446 // reg + SIZE_IN_BYTES * reg
7448 // No global is ever allowed as a base.
7452 // No reg+reg+imm addressing.
7453 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7456 // check reg + imm case:
7457 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7458 uint64_t NumBytes = 0;
7459 if (Ty->isSized()) {
7460 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7461 NumBytes = NumBits / 8;
7462 if (!isPowerOf2_64(NumBits))
7467 int64_t Offset = AM.BaseOffs;
7469 // 9-bit signed offset
7470 if (isInt<9>(Offset))
7473 // 12-bit unsigned offset
7474 unsigned shift = Log2_64(NumBytes);
7475 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7476 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7477 (Offset >> shift) << shift == Offset)
7482 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7484 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7487 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7488 const AddrMode &AM, Type *Ty,
7489 unsigned AS) const {
7490 // Scaling factors are not free at all.
7491 // Operands | Rt Latency
7492 // -------------------------------------------
7494 // -------------------------------------------
7495 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7496 // Rt, [Xn, Wm, <extend> #imm] |
7497 if (isLegalAddressingMode(DL, AM, Ty, AS))
7498 // Scale represents reg2 * scale, thus account for 1 if
7499 // it is not equal to 0 or 1.
7500 return AM.Scale != 0 && AM.Scale != 1;
7504 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7505 VT = VT.getScalarType();
7510 switch (VT.getSimpleVT().SimpleTy) {
7522 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7523 // LR is a callee-save register, but we must treat it as clobbered by any call
7524 // site. Hence we include LR in the scratch registers, which are in turn added
7525 // as implicit-defs for stackmaps and patchpoints.
7526 static const MCPhysReg ScratchRegs[] = {
7527 AArch64::X16, AArch64::X17, AArch64::LR, 0
7533 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7534 EVT VT = N->getValueType(0);
7535 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7536 // it with shift to let it be lowered to UBFX.
7537 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7538 isa<ConstantSDNode>(N->getOperand(1))) {
7539 uint64_t TruncMask = N->getConstantOperandVal(1);
7540 if (isMask_64(TruncMask) &&
7541 N->getOperand(0).getOpcode() == ISD::SRL &&
7542 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7548 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7550 assert(Ty->isIntegerTy());
7552 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7556 int64_t Val = Imm.getSExtValue();
7557 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7560 if ((int64_t)Val < 0)
7563 Val &= (1LL << 32) - 1;
7565 unsigned LZ = countLeadingZeros((uint64_t)Val);
7566 unsigned Shift = (63 - LZ) / 16;
7567 // MOVZ is free so return true for one or fewer MOVK.
7571 /// Turn vector tests of the signbit in the form of:
7572 /// xor (sra X, elt_size(X)-1), -1
7575 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7576 const AArch64Subtarget *Subtarget) {
7577 EVT VT = N->getValueType(0);
7578 if (!Subtarget->hasNEON() || !VT.isVector())
7581 // There must be a shift right algebraic before the xor, and the xor must be a
7583 SDValue Shift = N->getOperand(0);
7584 SDValue Ones = N->getOperand(1);
7585 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7586 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7589 // The shift should be smearing the sign bit across each vector element.
7590 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7591 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7592 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7595 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7598 // Generate SUBS and CSEL for integer abs.
7599 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7600 EVT VT = N->getValueType(0);
7602 SDValue N0 = N->getOperand(0);
7603 SDValue N1 = N->getOperand(1);
7606 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7607 // and change it to SUB and CSEL.
7608 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7609 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7610 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7611 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7612 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7613 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7615 // Generate SUBS & CSEL.
7617 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7618 N0.getOperand(0), DAG.getConstant(0, DL, VT));
7619 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7620 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7621 SDValue(Cmp.getNode(), 1));
7626 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7627 TargetLowering::DAGCombinerInfo &DCI,
7628 const AArch64Subtarget *Subtarget) {
7629 if (DCI.isBeforeLegalizeOps())
7632 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7635 return performIntegerAbsCombine(N, DAG);
7639 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7641 std::vector<SDNode *> *Created) const {
7642 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7643 if (isIntDivCheap(N->getValueType(0), Attr))
7644 return SDValue(N,0); // Lower SDIV as SDIV
7646 // fold (sdiv X, pow2)
7647 EVT VT = N->getValueType(0);
7648 if ((VT != MVT::i32 && VT != MVT::i64) ||
7649 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7653 SDValue N0 = N->getOperand(0);
7654 unsigned Lg2 = Divisor.countTrailingZeros();
7655 SDValue Zero = DAG.getConstant(0, DL, VT);
7656 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7658 // Add (N0 < 0) ? Pow2 - 1 : 0;
7660 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7661 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7662 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7665 Created->push_back(Cmp.getNode());
7666 Created->push_back(Add.getNode());
7667 Created->push_back(CSel.getNode());
7672 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7674 // If we're dividing by a positive value, we're done. Otherwise, we must
7675 // negate the result.
7676 if (Divisor.isNonNegative())
7680 Created->push_back(SRA.getNode());
7681 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7684 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7685 TargetLowering::DAGCombinerInfo &DCI,
7686 const AArch64Subtarget *Subtarget) {
7687 if (DCI.isBeforeLegalizeOps())
7690 // The below optimizations require a constant RHS.
7691 if (!isa<ConstantSDNode>(N->getOperand(1)))
7694 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7695 const APInt &ConstValue = C->getAPIntValue();
7697 // Multiplication of a power of two plus/minus one can be done more
7698 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7699 // future CPUs have a cheaper MADD instruction, this may need to be
7700 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7701 // 64-bit is 5 cycles, so this is always a win.
7702 // More aggressively, some multiplications N0 * C can be lowered to
7703 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7704 // e.g. 6=3*2=(2+1)*2.
7705 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7706 // which equals to (1+2)*16-(1+2).
7707 SDValue N0 = N->getOperand(0);
7708 // TrailingZeroes is used to test if the mul can be lowered to
7710 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7711 if (TrailingZeroes) {
7712 // Conservatively do not lower to shift+add+shift if the mul might be
7713 // folded into smul or umul.
7714 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7715 isZeroExtended(N0.getNode(), DAG)))
7717 // Conservatively do not lower to shift+add+shift if the mul might be
7718 // folded into madd or msub.
7719 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7720 N->use_begin()->getOpcode() == ISD::SUB))
7723 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7724 // and shift+add+shift.
7725 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7727 unsigned ShiftAmt, AddSubOpc;
7728 // Is the shifted value the LHS operand of the add/sub?
7729 bool ShiftValUseIsN0 = true;
7730 // Do we need to negate the result?
7731 bool NegateResult = false;
7733 if (ConstValue.isNonNegative()) {
7734 // (mul x, 2^N + 1) => (add (shl x, N), x)
7735 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7736 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7737 APInt SCVMinus1 = ShiftedConstValue - 1;
7738 APInt CVPlus1 = ConstValue + 1;
7739 if (SCVMinus1.isPowerOf2()) {
7740 ShiftAmt = SCVMinus1.logBase2();
7741 AddSubOpc = ISD::ADD;
7742 } else if (CVPlus1.isPowerOf2()) {
7743 ShiftAmt = CVPlus1.logBase2();
7744 AddSubOpc = ISD::SUB;
7748 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7749 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7750 APInt CVNegPlus1 = -ConstValue + 1;
7751 APInt CVNegMinus1 = -ConstValue - 1;
7752 if (CVNegPlus1.isPowerOf2()) {
7753 ShiftAmt = CVNegPlus1.logBase2();
7754 AddSubOpc = ISD::SUB;
7755 ShiftValUseIsN0 = false;
7756 } else if (CVNegMinus1.isPowerOf2()) {
7757 ShiftAmt = CVNegMinus1.logBase2();
7758 AddSubOpc = ISD::ADD;
7759 NegateResult = true;
7765 EVT VT = N->getValueType(0);
7766 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
7767 DAG.getConstant(ShiftAmt, DL, MVT::i64));
7769 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7770 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7771 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
7772 assert(!(NegateResult && TrailingZeroes) &&
7773 "NegateResult and TrailingZeroes cannot both be true for now.");
7774 // Negate the result.
7776 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7777 // Shift the result.
7779 return DAG.getNode(ISD::SHL, DL, VT, Res,
7780 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7784 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7785 SelectionDAG &DAG) {
7786 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7787 // optimize away operation when it's from a constant.
7789 // The general transformation is:
7790 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7791 // AND(VECTOR_CMP(x,y), constant2)
7792 // constant2 = UNARYOP(constant)
7794 // Early exit if this isn't a vector operation, the operand of the
7795 // unary operation isn't a bitwise AND, or if the sizes of the operations
7797 EVT VT = N->getValueType(0);
7798 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7799 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7800 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7803 // Now check that the other operand of the AND is a constant. We could
7804 // make the transformation for non-constant splats as well, but it's unclear
7805 // that would be a benefit as it would not eliminate any operations, just
7806 // perform one more step in scalar code before moving to the vector unit.
7807 if (BuildVectorSDNode *BV =
7808 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7809 // Bail out if the vector isn't a constant.
7810 if (!BV->isConstant())
7813 // Everything checks out. Build up the new and improved node.
7815 EVT IntVT = BV->getValueType(0);
7816 // Create a new constant of the appropriate type for the transformed
7818 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7819 // The AND node needs bitcasts to/from an integer vector type around it.
7820 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7821 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7822 N->getOperand(0)->getOperand(0), MaskConst);
7823 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7830 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7831 const AArch64Subtarget *Subtarget) {
7832 // First try to optimize away the conversion when it's conditionally from
7833 // a constant. Vectors only.
7834 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7837 EVT VT = N->getValueType(0);
7838 if (VT != MVT::f32 && VT != MVT::f64)
7841 // Only optimize when the source and destination types have the same width.
7842 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
7845 // If the result of an integer load is only used by an integer-to-float
7846 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7847 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7848 SDValue N0 = N->getOperand(0);
7849 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7850 // Do not change the width of a volatile load.
7851 !cast<LoadSDNode>(N0)->isVolatile()) {
7852 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7853 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7854 LN0->getPointerInfo(), LN0->getAlignment(),
7855 LN0->getMemOperand()->getFlags());
7857 // Make sure successors of the original load stay after it by updating them
7858 // to use the new Chain.
7859 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7862 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7863 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7869 /// Fold a floating-point multiply by power of two into floating-point to
7870 /// fixed-point conversion.
7871 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7872 TargetLowering::DAGCombinerInfo &DCI,
7873 const AArch64Subtarget *Subtarget) {
7874 if (!Subtarget->hasNEON())
7877 SDValue Op = N->getOperand(0);
7878 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7879 Op.getOpcode() != ISD::FMUL)
7882 SDValue ConstVec = Op->getOperand(1);
7883 if (!isa<BuildVectorSDNode>(ConstVec))
7886 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7887 uint32_t FloatBits = FloatTy.getSizeInBits();
7888 if (FloatBits != 32 && FloatBits != 64)
7891 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7892 uint32_t IntBits = IntTy.getSizeInBits();
7893 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7896 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7897 if (IntBits > FloatBits)
7900 BitVector UndefElements;
7901 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7902 int32_t Bits = IntBits == 64 ? 64 : 32;
7903 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7904 if (C == -1 || C == 0 || C > Bits)
7908 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7913 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7916 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7920 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7923 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7924 "Illegal vector type after legalization");
7927 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7928 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7929 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7931 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7932 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7933 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7934 // We can handle smaller integers by generating an extra trunc.
7935 if (IntBits < FloatBits)
7936 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7941 /// Fold a floating-point divide by power of two into fixed-point to
7942 /// floating-point conversion.
7943 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7944 TargetLowering::DAGCombinerInfo &DCI,
7945 const AArch64Subtarget *Subtarget) {
7946 if (!Subtarget->hasNEON())
7949 SDValue Op = N->getOperand(0);
7950 unsigned Opc = Op->getOpcode();
7951 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7952 !Op.getOperand(0).getValueType().isSimple() ||
7953 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7956 SDValue ConstVec = N->getOperand(1);
7957 if (!isa<BuildVectorSDNode>(ConstVec))
7960 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7961 int32_t IntBits = IntTy.getSizeInBits();
7962 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7965 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7966 int32_t FloatBits = FloatTy.getSizeInBits();
7967 if (FloatBits != 32 && FloatBits != 64)
7970 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7971 if (IntBits > FloatBits)
7974 BitVector UndefElements;
7975 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7976 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7977 if (C == -1 || C == 0 || C > FloatBits)
7981 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7986 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7989 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
7993 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7997 SDValue ConvInput = Op.getOperand(0);
7998 bool IsSigned = Opc == ISD::SINT_TO_FP;
7999 if (IntBits < FloatBits)
8000 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8003 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8004 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8005 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8006 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8007 DAG.getConstant(C, DL, MVT::i32));
8010 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8011 /// searches for and classifies those shifts.
8012 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8014 if (N.getOpcode() == ISD::SHL)
8016 else if (N.getOpcode() == ISD::SRL)
8021 if (!isa<ConstantSDNode>(N.getOperand(1)))
8024 ShiftAmount = N->getConstantOperandVal(1);
8025 Src = N->getOperand(0);
8029 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8030 /// registers viewed as a high/low pair. This function looks for the pattern:
8031 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8032 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
8034 static SDValue tryCombineToEXTR(SDNode *N,
8035 TargetLowering::DAGCombinerInfo &DCI) {
8036 SelectionDAG &DAG = DCI.DAG;
8038 EVT VT = N->getValueType(0);
8040 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8042 if (VT != MVT::i32 && VT != MVT::i64)
8046 uint32_t ShiftLHS = 0;
8048 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8052 uint32_t ShiftRHS = 0;
8054 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8057 // If they're both trying to come from the high part of the register, they're
8058 // not really an EXTR.
8059 if (LHSFromHi == RHSFromHi)
8062 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8066 std::swap(LHS, RHS);
8067 std::swap(ShiftLHS, ShiftRHS);
8070 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8071 DAG.getConstant(ShiftRHS, DL, MVT::i64));
8074 static SDValue tryCombineToBSL(SDNode *N,
8075 TargetLowering::DAGCombinerInfo &DCI) {
8076 EVT VT = N->getValueType(0);
8077 SelectionDAG &DAG = DCI.DAG;
8083 SDValue N0 = N->getOperand(0);
8084 if (N0.getOpcode() != ISD::AND)
8087 SDValue N1 = N->getOperand(1);
8088 if (N1.getOpcode() != ISD::AND)
8091 // We only have to look for constant vectors here since the general, variable
8092 // case can be handled in TableGen.
8093 unsigned Bits = VT.getScalarSizeInBits();
8094 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8095 for (int i = 1; i >= 0; --i)
8096 for (int j = 1; j >= 0; --j) {
8097 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8098 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8102 bool FoundMatch = true;
8103 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8104 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8105 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8107 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8114 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8115 N0->getOperand(1 - i), N1->getOperand(1 - j));
8121 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8122 const AArch64Subtarget *Subtarget) {
8123 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8124 SelectionDAG &DAG = DCI.DAG;
8125 EVT VT = N->getValueType(0);
8127 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8130 if (SDValue Res = tryCombineToEXTR(N, DCI))
8133 if (SDValue Res = tryCombineToBSL(N, DCI))
8139 static SDValue performSRLCombine(SDNode *N,
8140 TargetLowering::DAGCombinerInfo &DCI) {
8141 SelectionDAG &DAG = DCI.DAG;
8142 EVT VT = N->getValueType(0);
8143 if (VT != MVT::i32 && VT != MVT::i64)
8146 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8147 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8148 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8149 SDValue N0 = N->getOperand(0);
8150 if (N0.getOpcode() == ISD::BSWAP) {
8152 SDValue N1 = N->getOperand(1);
8153 SDValue N00 = N0.getOperand(0);
8154 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8155 uint64_t ShiftAmt = C->getZExtValue();
8156 if (VT == MVT::i32 && ShiftAmt == 16 &&
8157 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8158 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8159 if (VT == MVT::i64 && ShiftAmt == 32 &&
8160 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8161 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8167 static SDValue performBitcastCombine(SDNode *N,
8168 TargetLowering::DAGCombinerInfo &DCI,
8169 SelectionDAG &DAG) {
8170 // Wait 'til after everything is legalized to try this. That way we have
8171 // legal vector types and such.
8172 if (DCI.isBeforeLegalizeOps())
8175 // Remove extraneous bitcasts around an extract_subvector.
8177 // (v4i16 (bitconvert
8178 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8180 // (extract_subvector ((v8i16 ...), (i64 4)))
8182 // Only interested in 64-bit vectors as the ultimate result.
8183 EVT VT = N->getValueType(0);
8186 if (VT.getSimpleVT().getSizeInBits() != 64)
8188 // Is the operand an extract_subvector starting at the beginning or halfway
8189 // point of the vector? A low half may also come through as an
8190 // EXTRACT_SUBREG, so look for that, too.
8191 SDValue Op0 = N->getOperand(0);
8192 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8193 !(Op0->isMachineOpcode() &&
8194 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8196 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8197 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8198 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8200 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8201 if (idx != AArch64::dsub)
8203 // The dsub reference is equivalent to a lane zero subvector reference.
8206 // Look through the bitcast of the input to the extract.
8207 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8209 SDValue Source = Op0->getOperand(0)->getOperand(0);
8210 // If the source type has twice the number of elements as our destination
8211 // type, we know this is an extract of the high or low half of the vector.
8212 EVT SVT = Source->getValueType(0);
8213 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8216 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8218 // Create the simplified form to just extract the low or high half of the
8219 // vector directly rather than bothering with the bitcasts.
8221 unsigned NumElements = VT.getVectorNumElements();
8223 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8224 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8226 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8227 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8233 static SDValue performConcatVectorsCombine(SDNode *N,
8234 TargetLowering::DAGCombinerInfo &DCI,
8235 SelectionDAG &DAG) {
8237 EVT VT = N->getValueType(0);
8238 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8240 // Optimize concat_vectors of truncated vectors, where the intermediate
8241 // type is illegal, to avoid said illegality, e.g.,
8242 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8243 // (v2i16 (truncate (v2i64)))))
8245 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8246 // (v4i32 (bitcast (v2i64))),
8248 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8249 // on both input and result type, so we might generate worse code.
8250 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8251 if (N->getNumOperands() == 2 &&
8252 N0->getOpcode() == ISD::TRUNCATE &&
8253 N1->getOpcode() == ISD::TRUNCATE) {
8254 SDValue N00 = N0->getOperand(0);
8255 SDValue N10 = N1->getOperand(0);
8256 EVT N00VT = N00.getValueType();
8258 if (N00VT == N10.getValueType() &&
8259 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8260 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8261 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8262 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8263 for (size_t i = 0; i < Mask.size(); ++i)
8265 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8266 DAG.getVectorShuffle(
8268 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8269 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8273 // Wait 'til after everything is legalized to try this. That way we have
8274 // legal vector types and such.
8275 if (DCI.isBeforeLegalizeOps())
8278 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8279 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8280 // canonicalise to that.
8281 if (N0 == N1 && VT.getVectorNumElements() == 2) {
8282 assert(VT.getScalarSizeInBits() == 64);
8283 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8284 DAG.getConstant(0, dl, MVT::i64));
8287 // Canonicalise concat_vectors so that the right-hand vector has as few
8288 // bit-casts as possible before its real operation. The primary matching
8289 // destination for these operations will be the narrowing "2" instructions,
8290 // which depend on the operation being performed on this right-hand vector.
8292 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8294 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8296 if (N1->getOpcode() != ISD::BITCAST)
8298 SDValue RHS = N1->getOperand(0);
8299 MVT RHSTy = RHS.getValueType().getSimpleVT();
8300 // If the RHS is not a vector, this is not the pattern we're looking for.
8301 if (!RHSTy.isVector())
8304 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8306 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8307 RHSTy.getVectorNumElements() * 2);
8308 return DAG.getNode(ISD::BITCAST, dl, VT,
8309 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8310 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8314 static SDValue tryCombineFixedPointConvert(SDNode *N,
8315 TargetLowering::DAGCombinerInfo &DCI,
8316 SelectionDAG &DAG) {
8317 // Wait 'til after everything is legalized to try this. That way we have
8318 // legal vector types and such.
8319 if (DCI.isBeforeLegalizeOps())
8321 // Transform a scalar conversion of a value from a lane extract into a
8322 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8323 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8324 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8326 // The second form interacts better with instruction selection and the
8327 // register allocator to avoid cross-class register copies that aren't
8328 // coalescable due to a lane reference.
8330 // Check the operand and see if it originates from a lane extract.
8331 SDValue Op1 = N->getOperand(1);
8332 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8333 // Yep, no additional predication needed. Perform the transform.
8334 SDValue IID = N->getOperand(0);
8335 SDValue Shift = N->getOperand(2);
8336 SDValue Vec = Op1.getOperand(0);
8337 SDValue Lane = Op1.getOperand(1);
8338 EVT ResTy = N->getValueType(0);
8342 // The vector width should be 128 bits by the time we get here, even
8343 // if it started as 64 bits (the extract_vector handling will have
8345 assert(Vec.getValueSizeInBits() == 128 &&
8346 "unexpected vector size on extract_vector_elt!");
8347 if (Vec.getValueType() == MVT::v4i32)
8348 VecResTy = MVT::v4f32;
8349 else if (Vec.getValueType() == MVT::v2i64)
8350 VecResTy = MVT::v2f64;
8352 llvm_unreachable("unexpected vector type!");
8355 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8356 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8361 // AArch64 high-vector "long" operations are formed by performing the non-high
8362 // version on an extract_subvector of each operand which gets the high half:
8364 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8366 // However, there are cases which don't have an extract_high explicitly, but
8367 // have another operation that can be made compatible with one for free. For
8370 // (dupv64 scalar) --> (extract_high (dup128 scalar))
8372 // This routine does the actual conversion of such DUPs, once outer routines
8373 // have determined that everything else is in order.
8374 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8376 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8377 switch (N.getOpcode()) {
8378 case AArch64ISD::DUP:
8379 case AArch64ISD::DUPLANE8:
8380 case AArch64ISD::DUPLANE16:
8381 case AArch64ISD::DUPLANE32:
8382 case AArch64ISD::DUPLANE64:
8383 case AArch64ISD::MOVI:
8384 case AArch64ISD::MOVIshift:
8385 case AArch64ISD::MOVIedit:
8386 case AArch64ISD::MOVImsl:
8387 case AArch64ISD::MVNIshift:
8388 case AArch64ISD::MVNImsl:
8391 // FMOV could be supported, but isn't very useful, as it would only occur
8392 // if you passed a bitcast' floating point immediate to an eligible long
8393 // integer op (addl, smull, ...).
8397 MVT NarrowTy = N.getSimpleValueType();
8398 if (!NarrowTy.is64BitVector())
8401 MVT ElementTy = NarrowTy.getVectorElementType();
8402 unsigned NumElems = NarrowTy.getVectorNumElements();
8403 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8406 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8407 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8408 DAG.getConstant(NumElems, dl, MVT::i64));
8411 static bool isEssentiallyExtractSubvector(SDValue N) {
8412 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8415 return N.getOpcode() == ISD::BITCAST &&
8416 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8419 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8420 struct GenericSetCCInfo {
8421 const SDValue *Opnd0;
8422 const SDValue *Opnd1;
8426 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8427 struct AArch64SetCCInfo {
8429 AArch64CC::CondCode CC;
8432 /// \brief Helper structure to keep track of SetCC information.
8434 GenericSetCCInfo Generic;
8435 AArch64SetCCInfo AArch64;
8438 /// \brief Helper structure to be able to read SetCC information. If set to
8439 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8440 /// GenericSetCCInfo.
8441 struct SetCCInfoAndKind {
8446 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8448 /// AArch64 lowered one.
8449 /// \p SetCCInfo is filled accordingly.
8450 /// \post SetCCInfo is meanginfull only when this function returns true.
8451 /// \return True when Op is a kind of SET_CC operation.
8452 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8453 // If this is a setcc, this is straight forward.
8454 if (Op.getOpcode() == ISD::SETCC) {
8455 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8456 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8457 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8458 SetCCInfo.IsAArch64 = false;
8461 // Otherwise, check if this is a matching csel instruction.
8465 if (Op.getOpcode() != AArch64ISD::CSEL)
8467 // Set the information about the operands.
8468 // TODO: we want the operands of the Cmp not the csel
8469 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8470 SetCCInfo.IsAArch64 = true;
8471 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8472 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8474 // Check that the operands matches the constraints:
8475 // (1) Both operands must be constants.
8476 // (2) One must be 1 and the other must be 0.
8477 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8478 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8481 if (!TValue || !FValue)
8485 if (!TValue->isOne()) {
8486 // Update the comparison when we are interested in !cc.
8487 std::swap(TValue, FValue);
8488 SetCCInfo.Info.AArch64.CC =
8489 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8491 return TValue->isOne() && FValue->isNullValue();
8494 // Returns true if Op is setcc or zext of setcc.
8495 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8496 if (isSetCC(Op, Info))
8498 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8499 isSetCC(Op->getOperand(0), Info));
8502 // The folding we want to perform is:
8503 // (add x, [zext] (setcc cc ...) )
8505 // (csel x, (add x, 1), !cc ...)
8507 // The latter will get matched to a CSINC instruction.
8508 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8509 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8510 SDValue LHS = Op->getOperand(0);
8511 SDValue RHS = Op->getOperand(1);
8512 SetCCInfoAndKind InfoAndKind;
8514 // If neither operand is a SET_CC, give up.
8515 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8516 std::swap(LHS, RHS);
8517 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8521 // FIXME: This could be generatized to work for FP comparisons.
8522 EVT CmpVT = InfoAndKind.IsAArch64
8523 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8524 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8525 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8531 if (InfoAndKind.IsAArch64) {
8532 CCVal = DAG.getConstant(
8533 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8535 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8537 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8538 *InfoAndKind.Info.Generic.Opnd1,
8539 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8542 EVT VT = Op->getValueType(0);
8543 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8544 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8547 // The basic add/sub long vector instructions have variants with "2" on the end
8548 // which act on the high-half of their inputs. They are normally matched by
8551 // (add (zeroext (extract_high LHS)),
8552 // (zeroext (extract_high RHS)))
8553 // -> uaddl2 vD, vN, vM
8555 // However, if one of the extracts is something like a duplicate, this
8556 // instruction can still be used profitably. This function puts the DAG into a
8557 // more appropriate form for those patterns to trigger.
8558 static SDValue performAddSubLongCombine(SDNode *N,
8559 TargetLowering::DAGCombinerInfo &DCI,
8560 SelectionDAG &DAG) {
8561 if (DCI.isBeforeLegalizeOps())
8564 MVT VT = N->getSimpleValueType(0);
8565 if (!VT.is128BitVector()) {
8566 if (N->getOpcode() == ISD::ADD)
8567 return performSetccAddFolding(N, DAG);
8571 // Make sure both branches are extended in the same way.
8572 SDValue LHS = N->getOperand(0);
8573 SDValue RHS = N->getOperand(1);
8574 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8575 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8576 LHS.getOpcode() != RHS.getOpcode())
8579 unsigned ExtType = LHS.getOpcode();
8581 // It's not worth doing if at least one of the inputs isn't already an
8582 // extract, but we don't know which it'll be so we have to try both.
8583 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8584 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8588 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8589 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8590 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8594 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8597 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8600 // Massage DAGs which we can use the high-half "long" operations on into
8601 // something isel will recognize better. E.g.
8603 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8604 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8605 // (extract_high (v2i64 (dup128 scalar)))))
8607 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8608 TargetLowering::DAGCombinerInfo &DCI,
8609 SelectionDAG &DAG) {
8610 if (DCI.isBeforeLegalizeOps())
8613 SDValue LHS = N->getOperand(1);
8614 SDValue RHS = N->getOperand(2);
8615 assert(LHS.getValueType().is64BitVector() &&
8616 RHS.getValueType().is64BitVector() &&
8617 "unexpected shape for long operation");
8619 // Either node could be a DUP, but it's not worth doing both of them (you'd
8620 // just as well use the non-high version) so look for a corresponding extract
8621 // operation on the other "wing".
8622 if (isEssentiallyExtractSubvector(LHS)) {
8623 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8626 } else if (isEssentiallyExtractSubvector(RHS)) {
8627 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8632 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8633 N->getOperand(0), LHS, RHS);
8636 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8637 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8638 unsigned ElemBits = ElemTy.getSizeInBits();
8640 int64_t ShiftAmount;
8641 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8642 APInt SplatValue, SplatUndef;
8643 unsigned SplatBitSize;
8645 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8646 HasAnyUndefs, ElemBits) ||
8647 SplatBitSize != ElemBits)
8650 ShiftAmount = SplatValue.getSExtValue();
8651 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8652 ShiftAmount = CVN->getSExtValue();
8660 llvm_unreachable("Unknown shift intrinsic");
8661 case Intrinsic::aarch64_neon_sqshl:
8662 Opcode = AArch64ISD::SQSHL_I;
8663 IsRightShift = false;
8665 case Intrinsic::aarch64_neon_uqshl:
8666 Opcode = AArch64ISD::UQSHL_I;
8667 IsRightShift = false;
8669 case Intrinsic::aarch64_neon_srshl:
8670 Opcode = AArch64ISD::SRSHR_I;
8671 IsRightShift = true;
8673 case Intrinsic::aarch64_neon_urshl:
8674 Opcode = AArch64ISD::URSHR_I;
8675 IsRightShift = true;
8677 case Intrinsic::aarch64_neon_sqshlu:
8678 Opcode = AArch64ISD::SQSHLU_I;
8679 IsRightShift = false;
8683 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8685 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8686 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8687 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8689 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8690 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8696 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8697 // the intrinsics must be legal and take an i32, this means there's almost
8698 // certainly going to be a zext in the DAG which we can eliminate.
8699 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8700 SDValue AndN = N->getOperand(2);
8701 if (AndN.getOpcode() != ISD::AND)
8704 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8705 if (!CMask || CMask->getZExtValue() != Mask)
8708 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8709 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8712 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8713 SelectionDAG &DAG) {
8715 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8716 DAG.getNode(Opc, dl,
8717 N->getOperand(1).getSimpleValueType(),
8719 DAG.getConstant(0, dl, MVT::i64));
8722 static SDValue performIntrinsicCombine(SDNode *N,
8723 TargetLowering::DAGCombinerInfo &DCI,
8724 const AArch64Subtarget *Subtarget) {
8725 SelectionDAG &DAG = DCI.DAG;
8726 unsigned IID = getIntrinsicID(N);
8730 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8731 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8732 return tryCombineFixedPointConvert(N, DCI, DAG);
8733 case Intrinsic::aarch64_neon_saddv:
8734 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8735 case Intrinsic::aarch64_neon_uaddv:
8736 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8737 case Intrinsic::aarch64_neon_sminv:
8738 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8739 case Intrinsic::aarch64_neon_uminv:
8740 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8741 case Intrinsic::aarch64_neon_smaxv:
8742 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8743 case Intrinsic::aarch64_neon_umaxv:
8744 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8745 case Intrinsic::aarch64_neon_fmax:
8746 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8747 N->getOperand(1), N->getOperand(2));
8748 case Intrinsic::aarch64_neon_fmin:
8749 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8750 N->getOperand(1), N->getOperand(2));
8751 case Intrinsic::aarch64_neon_fmaxnm:
8752 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8753 N->getOperand(1), N->getOperand(2));
8754 case Intrinsic::aarch64_neon_fminnm:
8755 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8756 N->getOperand(1), N->getOperand(2));
8757 case Intrinsic::aarch64_neon_smull:
8758 case Intrinsic::aarch64_neon_umull:
8759 case Intrinsic::aarch64_neon_pmull:
8760 case Intrinsic::aarch64_neon_sqdmull:
8761 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8762 case Intrinsic::aarch64_neon_sqshl:
8763 case Intrinsic::aarch64_neon_uqshl:
8764 case Intrinsic::aarch64_neon_sqshlu:
8765 case Intrinsic::aarch64_neon_srshl:
8766 case Intrinsic::aarch64_neon_urshl:
8767 return tryCombineShiftImm(IID, N, DAG);
8768 case Intrinsic::aarch64_crc32b:
8769 case Intrinsic::aarch64_crc32cb:
8770 return tryCombineCRC32(0xff, N, DAG);
8771 case Intrinsic::aarch64_crc32h:
8772 case Intrinsic::aarch64_crc32ch:
8773 return tryCombineCRC32(0xffff, N, DAG);
8778 static SDValue performExtendCombine(SDNode *N,
8779 TargetLowering::DAGCombinerInfo &DCI,
8780 SelectionDAG &DAG) {
8781 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8782 // we can convert that DUP into another extract_high (of a bigger DUP), which
8783 // helps the backend to decide that an sabdl2 would be useful, saving a real
8784 // extract_high operation.
8785 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8786 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8787 SDNode *ABDNode = N->getOperand(0).getNode();
8788 unsigned IID = getIntrinsicID(ABDNode);
8789 if (IID == Intrinsic::aarch64_neon_sabd ||
8790 IID == Intrinsic::aarch64_neon_uabd) {
8791 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8792 if (!NewABD.getNode())
8795 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8800 // This is effectively a custom type legalization for AArch64.
8802 // Type legalization will split an extend of a small, legal, type to a larger
8803 // illegal type by first splitting the destination type, often creating
8804 // illegal source types, which then get legalized in isel-confusing ways,
8805 // leading to really terrible codegen. E.g.,
8806 // %result = v8i32 sext v8i8 %value
8808 // %losrc = extract_subreg %value, ...
8809 // %hisrc = extract_subreg %value, ...
8810 // %lo = v4i32 sext v4i8 %losrc
8811 // %hi = v4i32 sext v4i8 %hisrc
8812 // Things go rapidly downhill from there.
8814 // For AArch64, the [sz]ext vector instructions can only go up one element
8815 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8816 // take two instructions.
8818 // This implies that the most efficient way to do the extend from v8i8
8819 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8820 // the normal splitting to happen for the v8i16->v8i32.
8822 // This is pre-legalization to catch some cases where the default
8823 // type legalization will create ill-tempered code.
8824 if (!DCI.isBeforeLegalizeOps())
8827 // We're only interested in cleaning things up for non-legal vector types
8828 // here. If both the source and destination are legal, things will just
8829 // work naturally without any fiddling.
8830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8831 EVT ResVT = N->getValueType(0);
8832 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8834 // If the vector type isn't a simple VT, it's beyond the scope of what
8835 // we're worried about here. Let legalization do its thing and hope for
8837 SDValue Src = N->getOperand(0);
8838 EVT SrcVT = Src->getValueType(0);
8839 if (!ResVT.isSimple() || !SrcVT.isSimple())
8842 // If the source VT is a 64-bit vector, we can play games and get the
8843 // better results we want.
8844 if (SrcVT.getSizeInBits() != 64)
8847 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
8848 unsigned ElementCount = SrcVT.getVectorNumElements();
8849 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8851 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8853 // Now split the rest of the operation into two halves, each with a 64
8857 unsigned NumElements = ResVT.getVectorNumElements();
8858 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8859 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8860 ResVT.getVectorElementType(), NumElements / 2);
8862 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8863 LoVT.getVectorNumElements());
8864 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8865 DAG.getConstant(0, DL, MVT::i64));
8866 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8867 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8868 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8869 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8871 // Now combine the parts back together so we still have a single result
8872 // like the combiner expects.
8873 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8876 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
8877 SDValue SplatVal, unsigned NumVecElts) {
8878 unsigned OrigAlignment = St.getAlignment();
8879 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
8881 // Create scalar stores. This is at least as good as the code sequence for a
8882 // split unaligned store which is a dup.s, ext.b, and two stores.
8883 // Most of the time the three stores should be replaced by store pair
8884 // instructions (stp).
8886 SDValue BasePtr = St.getBasePtr();
8888 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, St.getPointerInfo(),
8889 OrigAlignment, St.getMemOperand()->getFlags());
8891 unsigned Offset = EltOffset;
8892 while (--NumVecElts) {
8893 unsigned Alignment = MinAlign(OrigAlignment, Offset);
8894 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8895 DAG.getConstant(Offset, DL, MVT::i64));
8896 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8897 St.getPointerInfo(), Alignment,
8898 St.getMemOperand()->getFlags());
8899 Offset += EltOffset;
8904 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
8905 /// load store optimizer pass will merge them to store pair stores. This should
8906 /// be better than a movi to create the vector zero followed by a vector store
8907 /// if the zero constant is not re-used, since one instructions and one register
8908 /// live range will be removed.
8910 /// For example, the final generated code should be:
8912 /// stp xzr, xzr, [x0]
8919 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8920 SDValue StVal = St.getValue();
8921 EVT VT = StVal.getValueType();
8923 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
8924 // 2, 3 or 4 i32 elements.
8925 int NumVecElts = VT.getVectorNumElements();
8926 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
8927 VT.getVectorElementType().getSizeInBits() == 64) ||
8928 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
8929 VT.getVectorElementType().getSizeInBits() == 32)))
8932 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
8935 // If the zero constant has more than one use then the vector store could be
8936 // better since the constant mov will be amortized and stp q instructions
8937 // should be able to be formed.
8938 if (!StVal.hasOneUse())
8941 // If the immediate offset of the address operand is too large for the stp
8942 // instruction, then bail out.
8943 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
8944 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
8945 if (Offset < -512 || Offset > 504)
8949 for (int I = 0; I < NumVecElts; ++I) {
8950 SDValue EltVal = StVal.getOperand(I);
8951 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
8955 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
8956 // undoing this transformation.
8957 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
8958 ? DAG.getRegister(AArch64::WZR, MVT::i32)
8959 : DAG.getRegister(AArch64::XZR, MVT::i64);
8960 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
8963 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8964 /// value. The load store optimizer pass will merge them to store pair stores.
8965 /// This has better performance than a splat of the scalar followed by a split
8966 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8967 /// followed by an ext.b and two stores.
8968 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8969 SDValue StVal = St.getValue();
8970 EVT VT = StVal.getValueType();
8972 // Don't replace floating point stores, they possibly won't be transformed to
8973 // stp because of the store pair suppress pass.
8974 if (VT.isFloatingPoint())
8977 // We can express a splat as store pair(s) for 2 or 4 elements.
8978 unsigned NumVecElts = VT.getVectorNumElements();
8979 if (NumVecElts != 4 && NumVecElts != 2)
8982 // Check that this is a splat.
8983 // Make sure that each of the relevant vector element locations are inserted
8984 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
8985 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
8987 for (unsigned I = 0; I < NumVecElts; ++I) {
8988 // Check for insert vector elements.
8989 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8992 // Check that same value is inserted at each vector element.
8994 SplatVal = StVal.getOperand(1);
8995 else if (StVal.getOperand(1) != SplatVal)
8998 // Check insert element index.
8999 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9002 uint64_t IndexVal = CIndex->getZExtValue();
9003 if (IndexVal >= NumVecElts)
9005 IndexNotInserted.reset(IndexVal);
9007 StVal = StVal.getOperand(0);
9009 // Check that all vector element locations were inserted to.
9010 if (IndexNotInserted.any())
9013 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9016 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9018 const AArch64Subtarget *Subtarget) {
9019 if (!DCI.isBeforeLegalize())
9022 StoreSDNode *S = cast<StoreSDNode>(N);
9023 if (S->isVolatile())
9026 SDValue StVal = S->getValue();
9027 EVT VT = StVal.getValueType();
9031 // If we get a splat of zeros, convert this vector store to a store of
9032 // scalars. They will be merged into store pairs of xzr thereby removing one
9033 // instruction and one register.
9034 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9035 return ReplacedZeroSplat;
9037 // FIXME: The logic for deciding if an unaligned store should be split should
9038 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9039 // a call to that function here.
9041 if (!Subtarget->isMisaligned128StoreSlow())
9044 // Don't split at -Oz.
9045 if (DAG.getMachineFunction().getFunction()->optForMinSize())
9048 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9049 // those up regresses performance on micro-benchmarks and olden/bh.
9050 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9053 // Split unaligned 16B stores. They are terrible for performance.
9054 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9055 // extensions can use this to mark that it does not want splitting to happen
9056 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9057 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9058 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9059 S->getAlignment() <= 2)
9062 // If we get a splat of a scalar convert this vector store to a store of
9063 // scalars. They will be merged into store pairs thereby removing two
9065 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9066 return ReplacedSplat;
9069 unsigned NumElts = VT.getVectorNumElements() / 2;
9070 // Split VT into two.
9072 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9073 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9074 DAG.getConstant(0, DL, MVT::i64));
9075 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9076 DAG.getConstant(NumElts, DL, MVT::i64));
9077 SDValue BasePtr = S->getBasePtr();
9079 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9080 S->getAlignment(), S->getMemOperand()->getFlags());
9081 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9082 DAG.getConstant(8, DL, MVT::i64));
9083 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9084 S->getPointerInfo(), S->getAlignment(),
9085 S->getMemOperand()->getFlags());
9088 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9089 /// post-increment LD1R.
9090 static SDValue performPostLD1Combine(SDNode *N,
9091 TargetLowering::DAGCombinerInfo &DCI,
9093 if (DCI.isBeforeLegalizeOps())
9096 SelectionDAG &DAG = DCI.DAG;
9097 EVT VT = N->getValueType(0);
9099 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9100 SDNode *LD = N->getOperand(LoadIdx).getNode();
9101 // If it is not LOAD, can not do such combine.
9102 if (LD->getOpcode() != ISD::LOAD)
9105 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9106 EVT MemVT = LoadSDN->getMemoryVT();
9107 // Check if memory operand is the same type as the vector element.
9108 if (MemVT != VT.getVectorElementType())
9111 // Check if there are other uses. If so, do not combine as it will introduce
9113 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9115 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9121 SDValue Addr = LD->getOperand(1);
9122 SDValue Vector = N->getOperand(0);
9123 // Search for a use of the address operand that is an increment.
9124 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9125 Addr.getNode()->use_end(); UI != UE; ++UI) {
9127 if (User->getOpcode() != ISD::ADD
9128 || UI.getUse().getResNo() != Addr.getResNo())
9131 // Check that the add is independent of the load. Otherwise, folding it
9132 // would create a cycle.
9133 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9135 // Also check that add is not used in the vector operand. This would also
9137 if (User->isPredecessorOf(Vector.getNode()))
9140 // If the increment is a constant, it must match the memory ref size.
9141 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9142 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9143 uint32_t IncVal = CInc->getZExtValue();
9144 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9145 if (IncVal != NumBytes)
9147 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9150 // Finally, check that the vector doesn't depend on the load.
9151 // Again, this would create a cycle.
9152 // The load depending on the vector is fine, as that's the case for the
9153 // LD1*post we'll eventually generate anyway.
9154 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9157 SmallVector<SDValue, 8> Ops;
9158 Ops.push_back(LD->getOperand(0)); // Chain
9160 Ops.push_back(Vector); // The vector to be inserted
9161 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9163 Ops.push_back(Addr);
9166 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9167 SDVTList SDTys = DAG.getVTList(Tys);
9168 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9169 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9171 LoadSDN->getMemOperand());
9174 SDValue NewResults[] = {
9175 SDValue(LD, 0), // The result of load
9176 SDValue(UpdN.getNode(), 2) // Chain
9178 DCI.CombineTo(LD, NewResults);
9179 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9180 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9187 /// Simplify \Addr given that the top byte of it is ignored by HW during
9188 /// address translation.
9189 static bool performTBISimplification(SDValue Addr,
9190 TargetLowering::DAGCombinerInfo &DCI,
9191 SelectionDAG &DAG) {
9192 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9193 APInt KnownZero, KnownOne;
9194 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9195 DCI.isBeforeLegalizeOps());
9196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9197 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9198 DCI.CommitTargetLoweringOpt(TLO);
9204 static SDValue performSTORECombine(SDNode *N,
9205 TargetLowering::DAGCombinerInfo &DCI,
9207 const AArch64Subtarget *Subtarget) {
9208 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9211 if (Subtarget->supportsAddressTopByteIgnored() &&
9212 performTBISimplification(N->getOperand(2), DCI, DAG))
9213 return SDValue(N, 0);
9218 /// This function handles the log2-shuffle pattern produced by the
9219 /// LoopVectorizer for the across vector reduction. It consists of
9220 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9221 /// are reduced, where s is an induction variable from 0 to
9222 /// log2(NumVectorElements).
9223 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9225 SelectionDAG &DAG) {
9226 EVT VTy = OpV->getOperand(0).getValueType();
9227 if (!VTy.isVector())
9230 int NumVecElts = VTy.getVectorNumElements();
9231 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9232 if (NumVecElts != 4)
9235 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9239 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
9240 SDValue PreOp = OpV;
9241 // Iterate over each step of the across vector reduction.
9242 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
9243 SDValue CurOp = PreOp.getOperand(0);
9244 SDValue Shuffle = PreOp.getOperand(1);
9245 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
9246 // Try to swap the 1st and 2nd operand as add and min/max instructions
9248 CurOp = PreOp.getOperand(1);
9249 Shuffle = PreOp.getOperand(0);
9250 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9254 // Check if the input vector is fed by the operator we want to handle,
9255 // except the last step; the very first input vector is not necessarily
9256 // the same operator we are handling.
9257 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9260 // Check if it forms one step of the across vector reduction.
9262 // %cur = add %1, %0
9263 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9264 // %pre = add %cur, %shuffle
9265 if (Shuffle.getOperand(0) != CurOp)
9268 int NumMaskElts = 1 << CurStep;
9269 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9270 // Check mask values in each step.
9271 // We expect the shuffle mask in each step follows a specific pattern
9272 // denoted here by the <M, U> form, where M is a sequence of integers
9273 // starting from NumMaskElts, increasing by 1, and the number integers
9274 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9275 // of undef in U should be NumVecElts - NumMaskElts.
9276 // E.g., for <8 x i16>, mask values in each step should be :
9277 // step 0 : <1,u,u,u,u,u,u,u>
9278 // step 1 : <2,3,u,u,u,u,u,u>
9279 // step 2 : <4,5,6,7,u,u,u,u>
9280 for (int i = 0; i < NumVecElts; ++i)
9281 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9282 (i >= NumMaskElts && !(Mask[i] < 0)))
9288 bool IsIntrinsic = false;
9292 llvm_unreachable("Unexpected operator for across vector reduction");
9294 Opcode = AArch64ISD::UADDV;
9297 Opcode = AArch64ISD::SMAXV;
9300 Opcode = AArch64ISD::UMAXV;
9303 Opcode = AArch64ISD::SMINV;
9306 Opcode = AArch64ISD::UMINV;
9309 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9313 Opcode = Intrinsic::aarch64_neon_fminnmv;
9320 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9321 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9323 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9324 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9325 DAG.getConstant(0, DL, MVT::i64));
9328 /// Target-specific DAG combine for the across vector min/max reductions.
9329 /// This function specifically handles the final clean-up step of the vector
9330 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9331 /// pattern, which narrows down and finds the final min/max value from all
9332 /// elements of the vector.
9333 /// For example, for a <16 x i8> vector :
9334 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9335 /// %smax0 = smax %arr, svn0
9336 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9337 /// %smax1 = smax %smax0, %svn1
9338 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9339 /// %smax2 = smax %smax1, svn2
9340 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9341 /// %sc = setcc %smax2, %svn3, gt
9342 /// %n0 = extract_vector_elt %sc, #0
9343 /// %n1 = extract_vector_elt %smax2, #0
9344 /// %n2 = extract_vector_elt $smax2, #1
9345 /// %result = select %n0, %n1, n2
9348 /// %result = extract_vector_elt %1, 0
9350 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9351 const AArch64Subtarget *Subtarget) {
9352 if (!Subtarget->hasNEON())
9355 SDValue N0 = N->getOperand(0);
9356 SDValue IfTrue = N->getOperand(1);
9357 SDValue IfFalse = N->getOperand(2);
9359 // Check if the SELECT merges up the final result of the min/max
9361 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9362 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9363 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9366 // Expect N0 is fed by SETCC.
9367 SDValue SetCC = N0.getOperand(0);
9368 EVT SetCCVT = SetCC.getValueType();
9369 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9370 SetCCVT.getVectorElementType() != MVT::i1)
9373 SDValue VectorOp = SetCC.getOperand(0);
9374 unsigned Op = VectorOp->getOpcode();
9375 // Check if the input vector is fed by the operator we want to handle.
9376 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9377 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9380 EVT VTy = VectorOp.getValueType();
9381 if (!VTy.isVector())
9384 if (VTy.getSizeInBits() < 64)
9387 EVT EltTy = VTy.getVectorElementType();
9388 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9389 if (EltTy != MVT::f32)
9392 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9396 // Check if extracting from the same vector.
9398 // %sc = setcc %vector, %svn1, gt
9399 // %n0 = extract_vector_elt %sc, #0
9400 // %n1 = extract_vector_elt %vector, #0
9401 // %n2 = extract_vector_elt $vector, #1
9402 if (!(VectorOp == IfTrue->getOperand(0) &&
9403 VectorOp == IfFalse->getOperand(0)))
9406 // Check if the condition code is matched with the operator type.
9407 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9408 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9409 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9410 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9411 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9412 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9413 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9414 CC != ISD::SETGE) ||
9415 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9416 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9420 // Expect to check only lane 0 from the vector SETCC.
9421 if (!isNullConstant(N0.getOperand(1)))
9424 // Expect to extract the true value from lane 0.
9425 if (!isNullConstant(IfTrue.getOperand(1)))
9428 // Expect to extract the false value from lane 1.
9429 if (!isOneConstant(IfFalse.getOperand(1)))
9432 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9435 /// Target-specific DAG combine for the across vector add reduction.
9436 /// This function specifically handles the final clean-up step of the vector
9437 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9438 /// pattern, which adds all elements of a vector together.
9439 /// For example, for a <4 x i32> vector :
9440 /// %1 = vector_shuffle %0, <2,3,u,u>
9442 /// %3 = vector_shuffle %2, <1,u,u,u>
9444 /// %result = extract_vector_elt %4, 0
9447 /// %result = extract_vector_elt %0, 0
9449 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9450 const AArch64Subtarget *Subtarget) {
9451 if (!Subtarget->hasNEON())
9453 SDValue N0 = N->getOperand(0);
9454 SDValue N1 = N->getOperand(1);
9456 // Check if the input vector is fed by the ADD.
9457 if (N0->getOpcode() != ISD::ADD)
9460 // The vector extract idx must constant zero because we only expect the final
9461 // result of the reduction is placed in lane 0.
9462 if (!isNullConstant(N1))
9465 EVT VTy = N0.getValueType();
9466 if (!VTy.isVector())
9469 EVT EltTy = VTy.getVectorElementType();
9470 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9473 if (VTy.getSizeInBits() < 64)
9476 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9479 /// Target-specific DAG combine function for NEON load/store intrinsics
9480 /// to merge base address updates.
9481 static SDValue performNEONPostLDSTCombine(SDNode *N,
9482 TargetLowering::DAGCombinerInfo &DCI,
9483 SelectionDAG &DAG) {
9484 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9487 unsigned AddrOpIdx = N->getNumOperands() - 1;
9488 SDValue Addr = N->getOperand(AddrOpIdx);
9490 // Search for a use of the address operand that is an increment.
9491 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9492 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9494 if (User->getOpcode() != ISD::ADD ||
9495 UI.getUse().getResNo() != Addr.getResNo())
9498 // Check that the add is independent of the load/store. Otherwise, folding
9499 // it would create a cycle.
9500 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9503 // Find the new opcode for the updating load/store.
9504 bool IsStore = false;
9505 bool IsLaneOp = false;
9506 bool IsDupOp = false;
9507 unsigned NewOpc = 0;
9508 unsigned NumVecs = 0;
9509 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9511 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9512 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9514 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9516 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9518 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9519 NumVecs = 2; IsStore = true; break;
9520 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9521 NumVecs = 3; IsStore = true; break;
9522 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9523 NumVecs = 4; IsStore = true; break;
9524 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9526 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9528 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9530 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9531 NumVecs = 2; IsStore = true; break;
9532 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9533 NumVecs = 3; IsStore = true; break;
9534 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9535 NumVecs = 4; IsStore = true; break;
9536 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9537 NumVecs = 2; IsDupOp = true; break;
9538 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9539 NumVecs = 3; IsDupOp = true; break;
9540 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9541 NumVecs = 4; IsDupOp = true; break;
9542 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9543 NumVecs = 2; IsLaneOp = true; break;
9544 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9545 NumVecs = 3; IsLaneOp = true; break;
9546 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9547 NumVecs = 4; IsLaneOp = true; break;
9548 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9549 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9550 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9551 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9552 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9553 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9558 VecTy = N->getOperand(2).getValueType();
9560 VecTy = N->getValueType(0);
9562 // If the increment is a constant, it must match the memory ref size.
9563 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9564 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9565 uint32_t IncVal = CInc->getZExtValue();
9566 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9567 if (IsLaneOp || IsDupOp)
9568 NumBytes /= VecTy.getVectorNumElements();
9569 if (IncVal != NumBytes)
9571 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9573 SmallVector<SDValue, 8> Ops;
9574 Ops.push_back(N->getOperand(0)); // Incoming chain
9575 // Load lane and store have vector list as input.
9576 if (IsLaneOp || IsStore)
9577 for (unsigned i = 2; i < AddrOpIdx; ++i)
9578 Ops.push_back(N->getOperand(i));
9579 Ops.push_back(Addr); // Base register
9584 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9586 for (n = 0; n < NumResultVecs; ++n)
9588 Tys[n++] = MVT::i64; // Type of write back register
9589 Tys[n] = MVT::Other; // Type of the chain
9590 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9592 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9593 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9594 MemInt->getMemoryVT(),
9595 MemInt->getMemOperand());
9598 std::vector<SDValue> NewResults;
9599 for (unsigned i = 0; i < NumResultVecs; ++i) {
9600 NewResults.push_back(SDValue(UpdN.getNode(), i));
9602 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9603 DCI.CombineTo(N, NewResults);
9604 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9611 // Checks to see if the value is the prescribed width and returns information
9612 // about its extension mode.
9614 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9615 ExtType = ISD::NON_EXTLOAD;
9616 switch(V.getNode()->getOpcode()) {
9620 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9621 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9622 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9623 ExtType = LoadNode->getExtensionType();
9628 case ISD::AssertSext: {
9629 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9630 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9631 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9632 ExtType = ISD::SEXTLOAD;
9637 case ISD::AssertZext: {
9638 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9639 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9640 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9641 ExtType = ISD::ZEXTLOAD;
9647 case ISD::TargetConstant: {
9648 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9656 // This function does a whole lot of voodoo to determine if the tests are
9657 // equivalent without and with a mask. Essentially what happens is that given a
9660 // +-------------+ +-------------+ +-------------+ +-------------+
9661 // | Input | | AddConstant | | CompConstant| | CC |
9662 // +-------------+ +-------------+ +-------------+ +-------------+
9664 // V V | +----------+
9665 // +-------------+ +----+ | |
9666 // | ADD | |0xff| | |
9667 // +-------------+ +----+ | |
9670 // +-------------+ | |
9672 // +-------------+ | |
9681 // The AND node may be safely removed for some combinations of inputs. In
9682 // particular we need to take into account the extension type of the Input,
9683 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9684 // width of the input (this can work for any width inputs, the above graph is
9685 // specific to 8 bits.
9687 // The specific equations were worked out by generating output tables for each
9688 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9689 // problem was simplified by working with 4 bit inputs, which means we only
9690 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9691 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9692 // patterns present in both extensions (0,7). For every distinct set of
9693 // AddConstant and CompConstants bit patterns we can consider the masked and
9694 // unmasked versions to be equivalent if the result of this function is true for
9695 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9698 // and w10, w8, #0x0f
9700 // cset w9, AArch64CC
9702 // cset w11, AArch64CC
9707 // Since the above function shows when the outputs are equivalent it defines
9708 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9709 // would be expensive to run during compiles. The equations below were written
9710 // in a test harness that confirmed they gave equivalent outputs to the above
9711 // for all inputs function, so they can be used determine if the removal is
9714 // isEquivalentMaskless() is the code for testing if the AND can be removed
9715 // factored out of the DAG recognition as the DAG can take several forms.
9717 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9718 ISD::LoadExtType ExtType, int AddConstant,
9720 // By being careful about our equations and only writing the in term
9721 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9722 // make them generally applicable to all bit widths.
9723 int MaxUInt = (1 << width);
9725 // For the purposes of these comparisons sign extending the type is
9726 // equivalent to zero extending the add and displacing it by half the integer
9727 // width. Provided we are careful and make sure our equations are valid over
9728 // the whole range we can just adjust the input and avoid writing equations
9729 // for sign extended inputs.
9730 if (ExtType == ISD::SEXTLOAD)
9731 AddConstant -= (1 << (width-1));
9735 case AArch64CC::GT: {
9736 if ((AddConstant == 0) ||
9737 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9738 (AddConstant >= 0 && CompConstant < 0) ||
9739 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9743 case AArch64CC::GE: {
9744 if ((AddConstant == 0) ||
9745 (AddConstant >= 0 && CompConstant <= 0) ||
9746 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9750 case AArch64CC::LS: {
9751 if ((AddConstant >= 0 && CompConstant < 0) ||
9752 (AddConstant <= 0 && CompConstant >= -1 &&
9753 CompConstant < AddConstant + MaxUInt))
9757 case AArch64CC::MI: {
9758 if ((AddConstant == 0) ||
9759 (AddConstant > 0 && CompConstant <= 0) ||
9760 (AddConstant < 0 && CompConstant <= AddConstant))
9764 case AArch64CC::HS: {
9765 if ((AddConstant >= 0 && CompConstant <= 0) ||
9766 (AddConstant <= 0 && CompConstant >= 0 &&
9767 CompConstant <= AddConstant + MaxUInt))
9771 case AArch64CC::NE: {
9772 if ((AddConstant > 0 && CompConstant < 0) ||
9773 (AddConstant < 0 && CompConstant >= 0 &&
9774 CompConstant < AddConstant + MaxUInt) ||
9775 (AddConstant >= 0 && CompConstant >= 0 &&
9776 CompConstant >= AddConstant) ||
9777 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9786 case AArch64CC::Invalid:
9794 SDValue performCONDCombine(SDNode *N,
9795 TargetLowering::DAGCombinerInfo &DCI,
9796 SelectionDAG &DAG, unsigned CCIndex,
9797 unsigned CmpIndex) {
9798 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9799 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9800 unsigned CondOpcode = SubsNode->getOpcode();
9802 if (CondOpcode != AArch64ISD::SUBS)
9805 // There is a SUBS feeding this condition. Is it fed by a mask we can
9808 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9809 unsigned MaskBits = 0;
9811 if (AndNode->getOpcode() != ISD::AND)
9814 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9815 uint32_t CNV = CN->getZExtValue();
9818 else if (CNV == 65535)
9825 SDValue AddValue = AndNode->getOperand(0);
9827 if (AddValue.getOpcode() != ISD::ADD)
9830 // The basic dag structure is correct, grab the inputs and validate them.
9832 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9833 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9834 SDValue SubsInputValue = SubsNode->getOperand(1);
9836 // The mask is present and the provenance of all the values is a smaller type,
9837 // lets see if the mask is superfluous.
9839 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9840 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9843 ISD::LoadExtType ExtType;
9845 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9846 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9847 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9850 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9851 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9852 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9855 // The AND is not necessary, remove it.
9857 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9858 SubsNode->getValueType(1));
9859 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9861 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9862 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9864 return SDValue(N, 0);
9867 // Optimize compare with zero and branch.
9868 static SDValue performBRCONDCombine(SDNode *N,
9869 TargetLowering::DAGCombinerInfo &DCI,
9870 SelectionDAG &DAG) {
9871 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9873 SDValue Chain = N->getOperand(0);
9874 SDValue Dest = N->getOperand(1);
9875 SDValue CCVal = N->getOperand(2);
9876 SDValue Cmp = N->getOperand(3);
9878 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9879 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9880 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9883 unsigned CmpOpc = Cmp.getOpcode();
9884 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9887 // Only attempt folding if there is only one use of the flag and no use of the
9889 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9892 SDValue LHS = Cmp.getOperand(0);
9893 SDValue RHS = Cmp.getOperand(1);
9895 assert(LHS.getValueType() == RHS.getValueType() &&
9896 "Expected the value type to be the same for both operands!");
9897 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9900 if (isNullConstant(LHS))
9901 std::swap(LHS, RHS);
9903 if (!isNullConstant(RHS))
9906 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9907 LHS.getOpcode() == ISD::SRL)
9910 // Fold the compare into the branch instruction.
9912 if (CC == AArch64CC::EQ)
9913 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9915 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9917 // Do not add new nodes to DAG combiner worklist.
9918 DCI.CombineTo(N, BR, false);
9923 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9924 // as well as whether the test should be inverted. This code is required to
9925 // catch these cases (as opposed to standard dag combines) because
9926 // AArch64ISD::TBZ is matched during legalization.
9927 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9928 SelectionDAG &DAG) {
9930 if (!Op->hasOneUse())
9933 // We don't handle undef/constant-fold cases below, as they should have
9934 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9937 // (tbz (trunc x), b) -> (tbz x, b)
9938 // This case is just here to enable more of the below cases to be caught.
9939 if (Op->getOpcode() == ISD::TRUNCATE &&
9940 Bit < Op->getValueType(0).getSizeInBits()) {
9941 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9944 if (Op->getNumOperands() != 2)
9947 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9951 switch (Op->getOpcode()) {
9955 // (tbz (and x, m), b) -> (tbz x, b)
9957 if ((C->getZExtValue() >> Bit) & 1)
9958 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9961 // (tbz (shl x, c), b) -> (tbz x, b-c)
9963 if (C->getZExtValue() <= Bit &&
9964 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9965 Bit = Bit - C->getZExtValue();
9966 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9970 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9972 Bit = Bit + C->getZExtValue();
9973 if (Bit >= Op->getValueType(0).getSizeInBits())
9974 Bit = Op->getValueType(0).getSizeInBits() - 1;
9975 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9977 // (tbz (srl x, c), b) -> (tbz x, b+c)
9979 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9980 Bit = Bit + C->getZExtValue();
9981 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9985 // (tbz (xor x, -1), b) -> (tbnz x, b)
9987 if ((C->getZExtValue() >> Bit) & 1)
9989 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9993 // Optimize test single bit zero/non-zero and branch.
9994 static SDValue performTBZCombine(SDNode *N,
9995 TargetLowering::DAGCombinerInfo &DCI,
9996 SelectionDAG &DAG) {
9997 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9998 bool Invert = false;
9999 SDValue TestSrc = N->getOperand(1);
10000 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10002 if (TestSrc == NewTestSrc)
10005 unsigned NewOpc = N->getOpcode();
10007 if (NewOpc == AArch64ISD::TBZ)
10008 NewOpc = AArch64ISD::TBNZ;
10010 assert(NewOpc == AArch64ISD::TBNZ);
10011 NewOpc = AArch64ISD::TBZ;
10016 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10017 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10020 // vselect (v1i1 setcc) ->
10021 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
10022 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10023 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10025 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10026 SDValue N0 = N->getOperand(0);
10027 EVT CCVT = N0.getValueType();
10029 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10030 CCVT.getVectorElementType() != MVT::i1)
10033 EVT ResVT = N->getValueType(0);
10034 EVT CmpVT = N0.getOperand(0).getValueType();
10035 // Only combine when the result type is of the same size as the compared
10037 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10040 SDValue IfTrue = N->getOperand(1);
10041 SDValue IfFalse = N->getOperand(2);
10043 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10044 N0.getOperand(0), N0.getOperand(1),
10045 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10046 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10050 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10051 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10052 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10053 /// with a vector one followed by a DUP shuffle on the result.
10054 static SDValue performSelectCombine(SDNode *N,
10055 TargetLowering::DAGCombinerInfo &DCI) {
10056 SelectionDAG &DAG = DCI.DAG;
10057 SDValue N0 = N->getOperand(0);
10058 EVT ResVT = N->getValueType(0);
10060 if (N0.getOpcode() != ISD::SETCC)
10063 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10064 // scalar SetCCResultType. We also don't expect vectors, because we assume
10065 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10066 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10067 "Scalar-SETCC feeding SELECT has unexpected result type!");
10069 // If NumMaskElts == 0, the comparison is larger than select result. The
10070 // largest real NEON comparison is 64-bits per lane, which means the result is
10071 // at most 32-bits and an illegal vector. Just bail out for now.
10072 EVT SrcVT = N0.getOperand(0).getValueType();
10074 // Don't try to do this optimization when the setcc itself has i1 operands.
10075 // There are no legal vectors of i1, so this would be pointless.
10076 if (SrcVT == MVT::i1)
10079 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10080 if (!ResVT.isVector() || NumMaskElts == 0)
10083 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10084 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10086 // Also bail out if the vector CCVT isn't the same size as ResVT.
10087 // This can happen if the SETCC operand size doesn't divide the ResVT size
10088 // (e.g., f64 vs v3f32).
10089 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10092 // Make sure we didn't create illegal types, if we're not supposed to.
10093 assert(DCI.isBeforeLegalize() ||
10094 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10096 // First perform a vector comparison, where lane 0 is the one we're interested
10100 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10102 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10103 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10105 // Now duplicate the comparison mask we want across all other lanes.
10106 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10107 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10108 Mask = DAG.getNode(ISD::BITCAST, DL,
10109 ResVT.changeVectorElementTypeToInteger(), Mask);
10111 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10114 /// Get rid of unnecessary NVCASTs (that don't change the type).
10115 static SDValue performNVCASTCombine(SDNode *N) {
10116 if (N->getValueType(0) == N->getOperand(0).getValueType())
10117 return N->getOperand(0);
10122 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10123 DAGCombinerInfo &DCI) const {
10124 SelectionDAG &DAG = DCI.DAG;
10125 switch (N->getOpcode()) {
10130 return performAddSubLongCombine(N, DCI, DAG);
10132 return performXorCombine(N, DAG, DCI, Subtarget);
10134 return performMulCombine(N, DAG, DCI, Subtarget);
10135 case ISD::SINT_TO_FP:
10136 case ISD::UINT_TO_FP:
10137 return performIntToFpCombine(N, DAG, Subtarget);
10138 case ISD::FP_TO_SINT:
10139 case ISD::FP_TO_UINT:
10140 return performFpToIntCombine(N, DAG, DCI, Subtarget);
10142 return performFDivCombine(N, DAG, DCI, Subtarget);
10144 return performORCombine(N, DCI, Subtarget);
10146 return performSRLCombine(N, DCI);
10147 case ISD::INTRINSIC_WO_CHAIN:
10148 return performIntrinsicCombine(N, DCI, Subtarget);
10149 case ISD::ANY_EXTEND:
10150 case ISD::ZERO_EXTEND:
10151 case ISD::SIGN_EXTEND:
10152 return performExtendCombine(N, DCI, DAG);
10154 return performBitcastCombine(N, DCI, DAG);
10155 case ISD::CONCAT_VECTORS:
10156 return performConcatVectorsCombine(N, DCI, DAG);
10157 case ISD::SELECT: {
10158 SDValue RV = performSelectCombine(N, DCI);
10160 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10164 return performVSelectCombine(N, DCI.DAG);
10166 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10167 return SDValue(N, 0);
10170 return performSTORECombine(N, DCI, DAG, Subtarget);
10171 case AArch64ISD::BRCOND:
10172 return performBRCONDCombine(N, DCI, DAG);
10173 case AArch64ISD::TBNZ:
10174 case AArch64ISD::TBZ:
10175 return performTBZCombine(N, DCI, DAG);
10176 case AArch64ISD::CSEL:
10177 return performCONDCombine(N, DCI, DAG, 2, 3);
10178 case AArch64ISD::DUP:
10179 return performPostLD1Combine(N, DCI, false);
10180 case AArch64ISD::NVCAST:
10181 return performNVCASTCombine(N);
10182 case ISD::INSERT_VECTOR_ELT:
10183 return performPostLD1Combine(N, DCI, true);
10184 case ISD::EXTRACT_VECTOR_ELT:
10185 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
10186 case ISD::INTRINSIC_VOID:
10187 case ISD::INTRINSIC_W_CHAIN:
10188 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10189 case Intrinsic::aarch64_neon_ld2:
10190 case Intrinsic::aarch64_neon_ld3:
10191 case Intrinsic::aarch64_neon_ld4:
10192 case Intrinsic::aarch64_neon_ld1x2:
10193 case Intrinsic::aarch64_neon_ld1x3:
10194 case Intrinsic::aarch64_neon_ld1x4:
10195 case Intrinsic::aarch64_neon_ld2lane:
10196 case Intrinsic::aarch64_neon_ld3lane:
10197 case Intrinsic::aarch64_neon_ld4lane:
10198 case Intrinsic::aarch64_neon_ld2r:
10199 case Intrinsic::aarch64_neon_ld3r:
10200 case Intrinsic::aarch64_neon_ld4r:
10201 case Intrinsic::aarch64_neon_st2:
10202 case Intrinsic::aarch64_neon_st3:
10203 case Intrinsic::aarch64_neon_st4:
10204 case Intrinsic::aarch64_neon_st1x2:
10205 case Intrinsic::aarch64_neon_st1x3:
10206 case Intrinsic::aarch64_neon_st1x4:
10207 case Intrinsic::aarch64_neon_st2lane:
10208 case Intrinsic::aarch64_neon_st3lane:
10209 case Intrinsic::aarch64_neon_st4lane:
10210 return performNEONPostLDSTCombine(N, DCI, DAG);
10218 // Check if the return value is used as only a return value, as otherwise
10219 // we can't perform a tail-call. In particular, we need to check for
10220 // target ISD nodes that are returns and any other "odd" constructs
10221 // that the generic analysis code won't necessarily catch.
10222 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10223 SDValue &Chain) const {
10224 if (N->getNumValues() != 1)
10226 if (!N->hasNUsesOfValue(1, 0))
10229 SDValue TCChain = Chain;
10230 SDNode *Copy = *N->use_begin();
10231 if (Copy->getOpcode() == ISD::CopyToReg) {
10232 // If the copy has a glue operand, we conservatively assume it isn't safe to
10233 // perform a tail call.
10234 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10237 TCChain = Copy->getOperand(0);
10238 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10241 bool HasRet = false;
10242 for (SDNode *Node : Copy->uses()) {
10243 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10255 // Return whether the an instruction can potentially be optimized to a tail
10256 // call. This will cause the optimizers to attempt to move, or duplicate,
10257 // return instructions to help enable tail call optimizations for this
10259 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
10260 return CI->isTailCall();
10263 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10265 ISD::MemIndexedMode &AM,
10267 SelectionDAG &DAG) const {
10268 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10271 Base = Op->getOperand(0);
10272 // All of the indexed addressing mode instructions take a signed
10273 // 9 bit immediate offset.
10274 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10275 int64_t RHSC = RHS->getSExtValue();
10276 if (Op->getOpcode() == ISD::SUB)
10277 RHSC = -(uint64_t)RHSC;
10278 if (!isInt<9>(RHSC))
10280 IsInc = (Op->getOpcode() == ISD::ADD);
10281 Offset = Op->getOperand(1);
10287 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10289 ISD::MemIndexedMode &AM,
10290 SelectionDAG &DAG) const {
10293 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10294 VT = LD->getMemoryVT();
10295 Ptr = LD->getBasePtr();
10296 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10297 VT = ST->getMemoryVT();
10298 Ptr = ST->getBasePtr();
10303 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10305 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10309 bool AArch64TargetLowering::getPostIndexedAddressParts(
10310 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10311 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10314 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10315 VT = LD->getMemoryVT();
10316 Ptr = LD->getBasePtr();
10317 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10318 VT = ST->getMemoryVT();
10319 Ptr = ST->getBasePtr();
10324 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10326 // Post-indexing updates the base, so it's not a valid transform
10327 // if that's not the same as the load's pointer.
10330 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10334 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10335 SelectionDAG &DAG) {
10337 SDValue Op = N->getOperand(0);
10339 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10343 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10344 DAG.getUNDEF(MVT::i32), Op,
10345 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10347 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10348 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10351 static void ReplaceReductionResults(SDNode *N,
10352 SmallVectorImpl<SDValue> &Results,
10353 SelectionDAG &DAG, unsigned InterOp,
10354 unsigned AcrossOp) {
10358 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10359 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10360 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10361 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10362 Results.push_back(SplitVal);
10365 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10367 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10368 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10369 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10370 DAG.getConstant(64, DL, MVT::i64)));
10371 return std::make_pair(Lo, Hi);
10374 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10375 SmallVectorImpl<SDValue> & Results,
10376 SelectionDAG &DAG) {
10377 assert(N->getValueType(0) == MVT::i128 &&
10378 "AtomicCmpSwap on types less than 128 should be legal");
10379 auto Desired = splitInt128(N->getOperand(2), DAG);
10380 auto New = splitInt128(N->getOperand(3), DAG);
10381 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10382 New.first, New.second, N->getOperand(0)};
10383 SDNode *CmpSwap = DAG.getMachineNode(
10384 AArch64::CMP_SWAP_128, SDLoc(N),
10385 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10387 MachineFunction &MF = DAG.getMachineFunction();
10388 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10389 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10390 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10392 Results.push_back(SDValue(CmpSwap, 0));
10393 Results.push_back(SDValue(CmpSwap, 1));
10394 Results.push_back(SDValue(CmpSwap, 3));
10397 void AArch64TargetLowering::ReplaceNodeResults(
10398 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10399 switch (N->getOpcode()) {
10401 llvm_unreachable("Don't know how to custom expand this");
10403 ReplaceBITCASTResults(N, Results, DAG);
10405 case AArch64ISD::SADDV:
10406 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10408 case AArch64ISD::UADDV:
10409 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10411 case AArch64ISD::SMINV:
10412 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10414 case AArch64ISD::UMINV:
10415 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10417 case AArch64ISD::SMAXV:
10418 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10420 case AArch64ISD::UMAXV:
10421 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10423 case ISD::FP_TO_UINT:
10424 case ISD::FP_TO_SINT:
10425 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10426 // Let normal code take care of it by not adding anything to Results.
10428 case ISD::ATOMIC_CMP_SWAP:
10429 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10434 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10435 if (!Subtarget->isTargetAndroid())
10437 return TargetLowering::useLoadStackGuardNode();
10440 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10441 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10442 // reciprocal if there are three or more FDIVs.
10446 TargetLoweringBase::LegalizeTypeAction
10447 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10448 MVT SVT = VT.getSimpleVT();
10449 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10450 // v4i16, v2i32 instead of to promote.
10451 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10452 || SVT == MVT::v1f32)
10453 return TypeWidenVector;
10455 return TargetLoweringBase::getPreferredVectorAction(VT);
10458 // Loads and stores less than 128-bits are already atomic; ones above that
10459 // are doomed anyway, so defer to the default libcall and blame the OS when
10460 // things go wrong.
10461 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10462 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10463 return Size == 128;
10466 // Loads and stores less than 128-bits are already atomic; ones above that
10467 // are doomed anyway, so defer to the default libcall and blame the OS when
10468 // things go wrong.
10469 TargetLowering::AtomicExpansionKind
10470 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10471 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10472 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10475 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10476 TargetLowering::AtomicExpansionKind
10477 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10478 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10479 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10482 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10483 AtomicCmpXchgInst *AI) const {
10484 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10485 // implement cmpxchg without spilling. If the address being exchanged is also
10486 // on the stack and close enough to the spill slot, this can lead to a
10487 // situation where the monitor always gets cleared and the atomic operation
10488 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10489 return getTargetMachine().getOptLevel() != 0;
10492 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10493 AtomicOrdering Ord) const {
10494 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10495 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10496 bool IsAcquire = isAcquireOrStronger(Ord);
10498 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10499 // intrinsic must return {i64, i64} and we have to recombine them into a
10500 // single i128 here.
10501 if (ValTy->getPrimitiveSizeInBits() == 128) {
10502 Intrinsic::ID Int =
10503 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10504 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10506 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10507 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10509 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10510 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10511 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10512 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10513 return Builder.CreateOr(
10514 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10517 Type *Tys[] = { Addr->getType() };
10518 Intrinsic::ID Int =
10519 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10520 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10522 return Builder.CreateTruncOrBitCast(
10523 Builder.CreateCall(Ldxr, Addr),
10524 cast<PointerType>(Addr->getType())->getElementType());
10527 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10528 IRBuilder<> &Builder) const {
10529 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10530 Builder.CreateCall(
10531 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10534 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10535 Value *Val, Value *Addr,
10536 AtomicOrdering Ord) const {
10537 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10538 bool IsRelease = isReleaseOrStronger(Ord);
10540 // Since the intrinsics must have legal type, the i128 intrinsics take two
10541 // parameters: "i64, i64". We must marshal Val into the appropriate form
10542 // before the call.
10543 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10544 Intrinsic::ID Int =
10545 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10546 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10547 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10549 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10550 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10551 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10552 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10555 Intrinsic::ID Int =
10556 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10557 Type *Tys[] = { Addr->getType() };
10558 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10560 return Builder.CreateCall(Stxr,
10561 {Builder.CreateZExtOrBitCast(
10562 Val, Stxr->getFunctionType()->getParamType(0)),
10566 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10567 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10568 return Ty->isArrayTy();
10571 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10576 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10577 if (!Subtarget->isTargetAndroid())
10578 return TargetLowering::getIRStackGuard(IRB);
10580 // Android provides a fixed TLS slot for the stack cookie. See the definition
10581 // of TLS_SLOT_STACK_GUARD in
10582 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10583 const unsigned TlsOffset = 0x28;
10584 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10585 Function *ThreadPointerFunc =
10586 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10587 return IRB.CreatePointerCast(
10588 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10589 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10592 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10593 if (!Subtarget->isTargetAndroid())
10594 return TargetLowering::getSafeStackPointerLocation(IRB);
10596 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10597 // definition of TLS_SLOT_SAFESTACK in
10598 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10599 const unsigned TlsOffset = 0x48;
10600 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10601 Function *ThreadPointerFunc =
10602 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10603 return IRB.CreatePointerCast(
10604 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10605 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10608 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10609 // Update IsSplitCSR in AArch64unctionInfo.
10610 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10611 AFI->setIsSplitCSR(true);
10614 void AArch64TargetLowering::insertCopiesSplitCSR(
10615 MachineBasicBlock *Entry,
10616 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10617 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10618 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10622 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10623 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10624 MachineBasicBlock::iterator MBBI = Entry->begin();
10625 for (const MCPhysReg *I = IStart; *I; ++I) {
10626 const TargetRegisterClass *RC = nullptr;
10627 if (AArch64::GPR64RegClass.contains(*I))
10628 RC = &AArch64::GPR64RegClass;
10629 else if (AArch64::FPR64RegClass.contains(*I))
10630 RC = &AArch64::FPR64RegClass;
10632 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10634 unsigned NewVR = MRI->createVirtualRegister(RC);
10635 // Create copy from CSR to a virtual register.
10636 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10637 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10638 // nounwind. If we want to generalize this later, we may need to emit
10639 // CFI pseudo-instructions.
10640 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10641 Attribute::NoUnwind) &&
10642 "Function should be nounwind in insertCopiesSplitCSR!");
10643 Entry->addLiveIn(*I);
10644 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10647 // Insert the copy-back instructions right before the terminator.
10648 for (auto *Exit : Exits)
10649 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10650 TII->get(TargetOpcode::COPY), *I)
10655 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10656 // Integer division on AArch64 is expensive. However, when aggressively
10657 // optimizing for code size, we prefer to use a div instruction, as it is
10658 // usually smaller than the alternative sequence.
10659 // The exception to this is vector division. Since AArch64 doesn't have vector
10660 // integer division, leaving the division as-is is a loss even in terms of
10661 // size, because it will have to be scalarized, while the alternative code
10662 // sequence can be performed in vector form.
10664 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10665 return OptSize && !VT.isVector();