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 "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/MachineValueType.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/Intrinsics.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/MC/MCRegisterInfo.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Compiler.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetCallingConv.h"
74 #include "llvm/Target/TargetInstrInfo.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Target/TargetOptions.h"
91 #define DEBUG_TYPE "aarch64-lower"
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99 cl::desc("Allow AArch64 SLI/SRI formation"),
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106 "aarch64-elf-ldtls-generation", cl::Hidden,
107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112 cl::desc("Enable AArch64 logical imm instruction "
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120 const AArch64Subtarget &STI)
121 : TargetLowering(TM), Subtarget(&STI) {
122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123 // we have to make something up. Arbitrarily, choose ZeroOrOne.
124 setBooleanContents(ZeroOrOneBooleanContent);
125 // When comparing vectors the result sets the different elements in the
126 // vector to all-one or all-zero.
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
129 // Set up the register classes.
130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
133 if (Subtarget->hasFPARMv8()) {
134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
140 if (Subtarget->hasNEON()) {
141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143 // Someone set us up the NEON.
144 addDRTypeForNEON(MVT::v2f32);
145 addDRTypeForNEON(MVT::v8i8);
146 addDRTypeForNEON(MVT::v4i16);
147 addDRTypeForNEON(MVT::v2i32);
148 addDRTypeForNEON(MVT::v1i64);
149 addDRTypeForNEON(MVT::v1f64);
150 addDRTypeForNEON(MVT::v4f16);
152 addQRTypeForNEON(MVT::v4f32);
153 addQRTypeForNEON(MVT::v2f64);
154 addQRTypeForNEON(MVT::v16i8);
155 addQRTypeForNEON(MVT::v8i16);
156 addQRTypeForNEON(MVT::v4i32);
157 addQRTypeForNEON(MVT::v2i64);
158 addQRTypeForNEON(MVT::v8f16);
161 // Compute derived properties from the register classes
162 computeRegisterProperties(Subtarget->getRegisterInfo());
164 // Provide all sorts of operation actions
165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167 setOperationAction(ISD::SETCC, MVT::i32, Custom);
168 setOperationAction(ISD::SETCC, MVT::i64, Custom);
169 setOperationAction(ISD::SETCC, MVT::f32, Custom);
170 setOperationAction(ISD::SETCC, MVT::f64, Custom);
171 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
172 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
173 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
174 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
175 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
176 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
177 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
178 setOperationAction(ISD::SELECT, MVT::i32, Custom);
179 setOperationAction(ISD::SELECT, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::f32, Custom);
181 setOperationAction(ISD::SELECT, MVT::f64, Custom);
182 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
183 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
184 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
186 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
189 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
190 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
191 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
193 setOperationAction(ISD::FREM, MVT::f32, Expand);
194 setOperationAction(ISD::FREM, MVT::f64, Expand);
195 setOperationAction(ISD::FREM, MVT::f80, Expand);
197 // Custom lowering hooks are needed for XOR
198 // to fold it into CSINC/CSINV.
199 setOperationAction(ISD::XOR, MVT::i32, Custom);
200 setOperationAction(ISD::XOR, MVT::i64, Custom);
202 // Virtually no operation on f128 is legal, but LLVM can't expand them when
203 // there's a valid register class, so we need custom operations in most cases.
204 setOperationAction(ISD::FABS, MVT::f128, Expand);
205 setOperationAction(ISD::FADD, MVT::f128, Custom);
206 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
207 setOperationAction(ISD::FCOS, MVT::f128, Expand);
208 setOperationAction(ISD::FDIV, MVT::f128, Custom);
209 setOperationAction(ISD::FMA, MVT::f128, Expand);
210 setOperationAction(ISD::FMUL, MVT::f128, Custom);
211 setOperationAction(ISD::FNEG, MVT::f128, Expand);
212 setOperationAction(ISD::FPOW, MVT::f128, Expand);
213 setOperationAction(ISD::FREM, MVT::f128, Expand);
214 setOperationAction(ISD::FRINT, MVT::f128, Expand);
215 setOperationAction(ISD::FSIN, MVT::f128, Expand);
216 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
217 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
218 setOperationAction(ISD::FSUB, MVT::f128, Custom);
219 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
220 setOperationAction(ISD::SETCC, MVT::f128, Custom);
221 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
222 setOperationAction(ISD::SELECT, MVT::f128, Custom);
223 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
224 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
226 // Lowering for many of the conversions is actually specified by the non-f128
227 // type. The LowerXXX function will be trivial when f128 isn't involved.
228 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
229 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
230 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
231 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
232 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
233 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
234 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
235 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
236 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
237 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
238 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
239 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
240 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
241 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
243 // Variable arguments.
244 setOperationAction(ISD::VASTART, MVT::Other, Custom);
245 setOperationAction(ISD::VAARG, MVT::Other, Custom);
246 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
247 setOperationAction(ISD::VAEND, MVT::Other, Expand);
249 // Variable-sized objects.
250 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
251 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
252 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
254 // Constant pool entries
255 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
258 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
260 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
261 setOperationAction(ISD::ADDC, MVT::i32, Custom);
262 setOperationAction(ISD::ADDE, MVT::i32, Custom);
263 setOperationAction(ISD::SUBC, MVT::i32, Custom);
264 setOperationAction(ISD::SUBE, MVT::i32, Custom);
265 setOperationAction(ISD::ADDC, MVT::i64, Custom);
266 setOperationAction(ISD::ADDE, MVT::i64, Custom);
267 setOperationAction(ISD::SUBC, MVT::i64, Custom);
268 setOperationAction(ISD::SUBE, MVT::i64, Custom);
270 // AArch64 lacks both left-rotate and popcount instructions.
271 setOperationAction(ISD::ROTL, MVT::i32, Expand);
272 setOperationAction(ISD::ROTL, MVT::i64, Expand);
273 for (MVT VT : MVT::vector_valuetypes()) {
274 setOperationAction(ISD::ROTL, VT, Expand);
275 setOperationAction(ISD::ROTR, VT, Expand);
278 // AArch64 doesn't have {U|S}MUL_LOHI.
279 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
280 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
282 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
283 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
285 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
287 for (MVT VT : MVT::vector_valuetypes()) {
288 setOperationAction(ISD::SDIVREM, VT, Expand);
289 setOperationAction(ISD::UDIVREM, VT, Expand);
291 setOperationAction(ISD::SREM, MVT::i32, Expand);
292 setOperationAction(ISD::SREM, MVT::i64, Expand);
293 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
294 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
295 setOperationAction(ISD::UREM, MVT::i32, Expand);
296 setOperationAction(ISD::UREM, MVT::i64, Expand);
298 // Custom lower Add/Sub/Mul with overflow.
299 setOperationAction(ISD::SADDO, MVT::i32, Custom);
300 setOperationAction(ISD::SADDO, MVT::i64, Custom);
301 setOperationAction(ISD::UADDO, MVT::i32, Custom);
302 setOperationAction(ISD::UADDO, MVT::i64, Custom);
303 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
304 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
305 setOperationAction(ISD::USUBO, MVT::i32, Custom);
306 setOperationAction(ISD::USUBO, MVT::i64, Custom);
307 setOperationAction(ISD::SMULO, MVT::i32, Custom);
308 setOperationAction(ISD::SMULO, MVT::i64, Custom);
309 setOperationAction(ISD::UMULO, MVT::i32, Custom);
310 setOperationAction(ISD::UMULO, MVT::i64, Custom);
312 setOperationAction(ISD::FSIN, MVT::f32, Expand);
313 setOperationAction(ISD::FSIN, MVT::f64, Expand);
314 setOperationAction(ISD::FCOS, MVT::f32, Expand);
315 setOperationAction(ISD::FCOS, MVT::f64, Expand);
316 setOperationAction(ISD::FPOW, MVT::f32, Expand);
317 setOperationAction(ISD::FPOW, MVT::f64, Expand);
318 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
319 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
321 // f16 is a storage-only type, always promote it to f32.
322 setOperationAction(ISD::SETCC, MVT::f16, Promote);
323 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
324 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
325 setOperationAction(ISD::SELECT, MVT::f16, Promote);
326 setOperationAction(ISD::FADD, MVT::f16, Promote);
327 setOperationAction(ISD::FSUB, MVT::f16, Promote);
328 setOperationAction(ISD::FMUL, MVT::f16, Promote);
329 setOperationAction(ISD::FDIV, MVT::f16, Promote);
330 setOperationAction(ISD::FREM, MVT::f16, Promote);
331 setOperationAction(ISD::FMA, MVT::f16, Promote);
332 setOperationAction(ISD::FNEG, MVT::f16, Promote);
333 setOperationAction(ISD::FABS, MVT::f16, Promote);
334 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
335 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
336 setOperationAction(ISD::FCOS, MVT::f16, Promote);
337 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
338 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
339 setOperationAction(ISD::FPOW, MVT::f16, Promote);
340 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
341 setOperationAction(ISD::FRINT, MVT::f16, Promote);
342 setOperationAction(ISD::FSIN, MVT::f16, Promote);
343 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
344 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
345 setOperationAction(ISD::FEXP, MVT::f16, Promote);
346 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
347 setOperationAction(ISD::FLOG, MVT::f16, Promote);
348 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
349 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
350 setOperationAction(ISD::FROUND, MVT::f16, Promote);
351 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
352 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
353 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
354 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
355 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
357 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
359 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
360 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
361 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
362 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
363 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
364 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
365 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
366 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
367 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
368 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
369 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
370 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
372 // Expand all other v4f16 operations.
373 // FIXME: We could generate better code by promoting some operations to
375 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
376 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
377 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
378 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
379 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
380 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
381 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
382 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
383 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
384 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
385 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
386 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
387 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
388 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
389 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
390 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
391 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
392 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
393 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
394 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
395 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
396 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
397 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
398 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
399 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
402 // v8f16 is also a storage-only type, so expand it.
403 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
404 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
405 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
406 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
407 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
408 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
409 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
410 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
411 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
412 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
413 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
414 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
415 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
416 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
417 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
418 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
419 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
420 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
421 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
422 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
423 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
424 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
425 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
426 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
427 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
428 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
429 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
430 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
431 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
432 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
434 // AArch64 has implementations of a lot of rounding-like FP operations.
435 for (MVT Ty : {MVT::f32, MVT::f64}) {
436 setOperationAction(ISD::FFLOOR, Ty, Legal);
437 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
438 setOperationAction(ISD::FCEIL, Ty, Legal);
439 setOperationAction(ISD::FRINT, Ty, Legal);
440 setOperationAction(ISD::FTRUNC, Ty, Legal);
441 setOperationAction(ISD::FROUND, Ty, Legal);
442 setOperationAction(ISD::FMINNUM, Ty, Legal);
443 setOperationAction(ISD::FMAXNUM, Ty, Legal);
444 setOperationAction(ISD::FMINNAN, Ty, Legal);
445 setOperationAction(ISD::FMAXNAN, Ty, Legal);
448 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
450 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
452 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
453 // This requires the Performance Monitors extension.
454 if (Subtarget->hasPerfMon())
455 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
457 if (Subtarget->isTargetMachO()) {
458 // For iOS, we don't want to the normal expansion of a libcall to
459 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
461 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
462 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
464 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
465 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
468 // Make floating-point constants legal for the large code model, so they don't
469 // become loads from the constant pool.
470 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
471 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
472 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
475 // AArch64 does not have floating-point extending loads, i1 sign-extending
476 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
477 for (MVT VT : MVT::fp_valuetypes()) {
478 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
479 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
480 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
481 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
483 for (MVT VT : MVT::integer_valuetypes())
484 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
486 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
487 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
488 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
489 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
490 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
491 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
492 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
494 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
495 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
497 // Indexed loads and stores are supported.
498 for (unsigned im = (unsigned)ISD::PRE_INC;
499 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
500 setIndexedLoadAction(im, MVT::i8, Legal);
501 setIndexedLoadAction(im, MVT::i16, Legal);
502 setIndexedLoadAction(im, MVT::i32, Legal);
503 setIndexedLoadAction(im, MVT::i64, Legal);
504 setIndexedLoadAction(im, MVT::f64, Legal);
505 setIndexedLoadAction(im, MVT::f32, Legal);
506 setIndexedLoadAction(im, MVT::f16, Legal);
507 setIndexedStoreAction(im, MVT::i8, Legal);
508 setIndexedStoreAction(im, MVT::i16, Legal);
509 setIndexedStoreAction(im, MVT::i32, Legal);
510 setIndexedStoreAction(im, MVT::i64, Legal);
511 setIndexedStoreAction(im, MVT::f64, Legal);
512 setIndexedStoreAction(im, MVT::f32, Legal);
513 setIndexedStoreAction(im, MVT::f16, Legal);
517 setOperationAction(ISD::TRAP, MVT::Other, Legal);
519 // We combine OR nodes for bitfield operations.
520 setTargetDAGCombine(ISD::OR);
522 // Vector add and sub nodes may conceal a high-half opportunity.
523 // Also, try to fold ADD into CSINC/CSINV..
524 setTargetDAGCombine(ISD::ADD);
525 setTargetDAGCombine(ISD::SUB);
526 setTargetDAGCombine(ISD::SRL);
527 setTargetDAGCombine(ISD::XOR);
528 setTargetDAGCombine(ISD::SINT_TO_FP);
529 setTargetDAGCombine(ISD::UINT_TO_FP);
531 setTargetDAGCombine(ISD::FP_TO_SINT);
532 setTargetDAGCombine(ISD::FP_TO_UINT);
533 setTargetDAGCombine(ISD::FDIV);
535 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
537 setTargetDAGCombine(ISD::ANY_EXTEND);
538 setTargetDAGCombine(ISD::ZERO_EXTEND);
539 setTargetDAGCombine(ISD::SIGN_EXTEND);
540 setTargetDAGCombine(ISD::BITCAST);
541 setTargetDAGCombine(ISD::CONCAT_VECTORS);
542 setTargetDAGCombine(ISD::STORE);
543 if (Subtarget->supportsAddressTopByteIgnored())
544 setTargetDAGCombine(ISD::LOAD);
546 setTargetDAGCombine(ISD::MUL);
548 setTargetDAGCombine(ISD::SELECT);
549 setTargetDAGCombine(ISD::VSELECT);
551 setTargetDAGCombine(ISD::INTRINSIC_VOID);
552 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
555 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
556 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
557 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
559 setStackPointerRegisterToSaveRestore(AArch64::SP);
561 setSchedulingPreference(Sched::Hybrid);
563 EnableExtLdPromotion = true;
565 // Set required alignment.
566 setMinFunctionAlignment(2);
567 // Set preferred alignments.
568 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
569 setPrefLoopAlignment(STI.getPrefLoopAlignment());
571 // Only change the limit for entries in a jump table if specified by
572 // the subtarget, but not at the command line.
573 unsigned MaxJT = STI.getMaximumJumpTableSize();
574 if (MaxJT && getMaximumJumpTableSize() == 0)
575 setMaximumJumpTableSize(MaxJT);
577 setHasExtractBitsInsn(true);
579 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
581 if (Subtarget->hasNEON()) {
582 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
583 // silliness like this:
584 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
585 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
586 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
587 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
588 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
589 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
590 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
591 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
592 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
593 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
594 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
595 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
596 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
597 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
598 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
599 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
600 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
601 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
602 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
603 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
604 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
605 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
606 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
607 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
608 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
610 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
611 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
612 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
613 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
614 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
616 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
618 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
619 // elements smaller than i32, so promote the input to i32 first.
620 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
621 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
622 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
623 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
624 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
625 // -> v8f16 conversions.
626 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
627 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
628 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
629 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
630 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
631 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
632 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
633 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
634 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
635 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
636 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
637 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
638 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
640 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
641 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
643 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
644 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
645 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
646 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
647 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
648 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
649 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
650 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
652 // AArch64 doesn't have MUL.2d:
653 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
654 // Custom handling for some quad-vector types to detect MULL.
655 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
656 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
657 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
660 for (MVT VT : MVT::integer_valuetypes()) {
661 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
662 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
663 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
664 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
665 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
667 for (MVT VT : MVT::fp_valuetypes()) {
668 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
669 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
672 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
673 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
674 // Likewise, narrowing and extending vector loads/stores aren't handled
676 for (MVT VT : MVT::vector_valuetypes()) {
677 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
679 setOperationAction(ISD::MULHS, VT, Expand);
680 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
681 setOperationAction(ISD::MULHU, VT, Expand);
682 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
684 setOperationAction(ISD::BSWAP, VT, Expand);
686 for (MVT InnerVT : MVT::vector_valuetypes()) {
687 setTruncStoreAction(VT, InnerVT, Expand);
688 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
689 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
690 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
694 // AArch64 has implementations of a lot of rounding-like FP operations.
695 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
696 setOperationAction(ISD::FFLOOR, Ty, Legal);
697 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
698 setOperationAction(ISD::FCEIL, Ty, Legal);
699 setOperationAction(ISD::FRINT, Ty, Legal);
700 setOperationAction(ISD::FTRUNC, Ty, Legal);
701 setOperationAction(ISD::FROUND, Ty, Legal);
705 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
708 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
709 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
710 setOperationAction(ISD::LOAD, VT, Promote);
711 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
713 setOperationAction(ISD::STORE, VT, Promote);
714 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
715 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
716 setOperationAction(ISD::LOAD, VT, Promote);
717 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
719 setOperationAction(ISD::STORE, VT, Promote);
720 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
723 // Mark vector float intrinsics as expand.
724 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
725 setOperationAction(ISD::FSIN, VT, Expand);
726 setOperationAction(ISD::FCOS, VT, Expand);
727 setOperationAction(ISD::FPOW, VT, Expand);
728 setOperationAction(ISD::FLOG, VT, Expand);
729 setOperationAction(ISD::FLOG2, VT, Expand);
730 setOperationAction(ISD::FLOG10, VT, Expand);
731 setOperationAction(ISD::FEXP, VT, Expand);
732 setOperationAction(ISD::FEXP2, VT, Expand);
734 // But we do support custom-lowering for FCOPYSIGN.
735 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
740 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
741 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
742 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
743 setOperationAction(ISD::SRA, VT, Custom);
744 setOperationAction(ISD::SRL, VT, Custom);
745 setOperationAction(ISD::SHL, VT, Custom);
746 setOperationAction(ISD::AND, VT, Custom);
747 setOperationAction(ISD::OR, VT, Custom);
748 setOperationAction(ISD::SETCC, VT, Custom);
749 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
751 setOperationAction(ISD::SELECT, VT, Expand);
752 setOperationAction(ISD::SELECT_CC, VT, Expand);
753 setOperationAction(ISD::VSELECT, VT, Expand);
754 for (MVT InnerVT : MVT::all_valuetypes())
755 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
757 // CNT supports only B element sizes.
758 if (VT != MVT::v8i8 && VT != MVT::v16i8)
759 setOperationAction(ISD::CTPOP, VT, Expand);
761 setOperationAction(ISD::UDIV, VT, Expand);
762 setOperationAction(ISD::SDIV, VT, Expand);
763 setOperationAction(ISD::UREM, VT, Expand);
764 setOperationAction(ISD::SREM, VT, Expand);
765 setOperationAction(ISD::FREM, VT, Expand);
767 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
768 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
770 if (!VT.isFloatingPoint())
771 setOperationAction(ISD::ABS, VT, Legal);
773 // [SU][MIN|MAX] are available for all NEON types apart from i64.
774 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
775 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
776 setOperationAction(Opcode, VT, Legal);
778 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
779 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
780 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
781 ISD::FMINNUM, ISD::FMAXNUM})
782 setOperationAction(Opcode, VT, Legal);
784 if (Subtarget->isLittleEndian()) {
785 for (unsigned im = (unsigned)ISD::PRE_INC;
786 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
787 setIndexedLoadAction(im, VT, Legal);
788 setIndexedStoreAction(im, VT, Legal);
793 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
794 addRegisterClass(VT, &AArch64::FPR64RegClass);
795 addTypeForNEON(VT, MVT::v2i32);
798 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
799 addRegisterClass(VT, &AArch64::FPR128RegClass);
800 addTypeForNEON(VT, MVT::v4i32);
803 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
807 return VT.changeVectorElementTypeToInteger();
810 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
811 const APInt &Demanded,
812 TargetLowering::TargetLoweringOpt &TLO,
814 uint64_t OldImm = Imm, NewImm, Enc;
815 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
817 // Return if the immediate is already all zeros, all ones, a bimm32 or a
819 if (Imm == 0 || Imm == Mask ||
820 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
823 unsigned EltSize = Size;
824 uint64_t DemandedBits = Demanded.getZExtValue();
826 // Clear bits that are not demanded.
830 // The goal here is to set the non-demanded bits in a way that minimizes
831 // the number of switching between 0 and 1. In order to achieve this goal,
832 // we set the non-demanded bits to the value of the preceding demanded bits.
833 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
834 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
835 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
836 // The final result is 0b11000011.
837 uint64_t NonDemandedBits = ~DemandedBits;
838 uint64_t InvertedImm = ~Imm & DemandedBits;
839 uint64_t RotatedImm =
840 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
842 uint64_t Sum = RotatedImm + NonDemandedBits;
843 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
844 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
845 NewImm = (Imm | Ones) & Mask;
847 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
848 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
849 // we halve the element size and continue the search.
850 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
853 // We cannot shrink the element size any further if it is 2-bits.
859 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
861 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
862 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
865 // Merge the upper and lower halves of Imm and DemandedBits.
867 DemandedBits |= DemandedBitsHi;
872 // Replicate the element across the register width.
873 while (EltSize < Size) {
874 NewImm |= NewImm << EltSize;
879 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
880 "demanded bits should never be altered");
881 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
883 // Create the new constant immediate node.
884 EVT VT = Op.getValueType();
888 // If the new constant immediate is all-zeros or all-ones, let the target
889 // independent DAG combine optimize this node.
890 if (NewImm == 0 || NewImm == OrigMask) {
891 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
892 TLO.DAG.getConstant(NewImm, DL, VT));
893 // Otherwise, create a machine node so that target independent DAG combine
894 // doesn't undo this optimization.
896 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
897 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
899 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
902 return TLO.CombineTo(Op, New);
905 bool AArch64TargetLowering::targetShrinkDemandedConstant(
906 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
907 // Delay this optimization to as late as possible.
911 if (!EnableOptimizeLogicalImm)
914 EVT VT = Op.getValueType();
918 unsigned Size = VT.getSizeInBits();
919 assert((Size == 32 || Size == 64) &&
920 "i32 or i64 is expected after legalization.");
922 // Exit early if we demand all bits.
923 if (Demanded.countPopulation() == Size)
927 switch (Op.getOpcode()) {
931 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
934 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
937 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
940 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
943 uint64_t Imm = C->getZExtValue();
944 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
947 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
948 /// Mask are known to be either zero or one and return them Known.
949 void AArch64TargetLowering::computeKnownBitsForTargetNode(
950 const SDValue Op, KnownBits &Known,
951 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
952 switch (Op.getOpcode()) {
955 case AArch64ISD::CSEL: {
957 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
958 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
959 Known.Zero &= Known2.Zero;
960 Known.One &= Known2.One;
963 case ISD::INTRINSIC_W_CHAIN: {
964 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
965 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
968 case Intrinsic::aarch64_ldaxr:
969 case Intrinsic::aarch64_ldxr: {
970 unsigned BitWidth = Known.getBitWidth();
971 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
972 unsigned MemBits = VT.getScalarSizeInBits();
973 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
979 case ISD::INTRINSIC_WO_CHAIN:
980 case ISD::INTRINSIC_VOID: {
981 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
985 case Intrinsic::aarch64_neon_umaxv:
986 case Intrinsic::aarch64_neon_uminv: {
987 // Figure out the datatype of the vector operand. The UMINV instruction
988 // will zero extend the result, so we can mark as known zero all the
989 // bits larger than the element datatype. 32-bit or larget doesn't need
990 // this as those are legal types and will be handled by isel directly.
991 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
992 unsigned BitWidth = Known.getBitWidth();
993 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
994 assert(BitWidth >= 8 && "Unexpected width!");
995 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
997 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
998 assert(BitWidth >= 16 && "Unexpected width!");
999 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1009 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1014 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1018 if (Subtarget->requiresStrictAlign())
1022 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1023 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1024 // See comments in performSTORECombine() for more details about
1025 // these conditions.
1027 // Code that uses clang vector extensions can mark that it
1028 // wants unaligned accesses to be treated as fast by
1029 // underspecifying alignment to be 1 or 2.
1032 // Disregard v2i64. Memcpy lowering produces those and splitting
1033 // them regresses performance on micro-benchmarks and olden/bh.
1040 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1041 const TargetLibraryInfo *libInfo) const {
1042 return AArch64::createFastISel(funcInfo, libInfo);
1045 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1046 switch ((AArch64ISD::NodeType)Opcode) {
1047 case AArch64ISD::FIRST_NUMBER: break;
1048 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1049 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1050 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1051 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1052 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1053 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1054 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1055 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1056 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1057 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1058 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1059 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1060 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1061 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1062 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1063 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1064 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1065 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1066 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1067 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1068 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1069 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1070 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1071 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1072 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1073 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1074 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1075 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1076 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1077 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1078 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1079 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1080 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1081 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1082 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1083 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1084 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1085 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1086 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1087 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1088 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1089 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1090 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1091 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1092 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1093 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1094 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1095 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1096 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1097 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1098 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1099 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1100 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1101 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1102 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1103 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1104 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1105 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1106 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1107 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1108 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1109 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1110 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1111 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1112 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1113 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1114 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1115 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1116 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1117 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1118 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1119 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1120 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1121 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1122 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1123 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1124 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1125 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1126 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1127 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1128 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1129 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1130 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1131 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1132 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1133 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1134 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1135 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1136 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1137 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1138 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1139 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1140 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1141 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1142 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1143 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1144 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1145 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1146 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1147 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1148 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1149 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1150 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1151 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1152 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1153 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1154 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1155 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1156 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1157 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1158 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1159 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1160 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1161 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1162 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1163 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1164 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1165 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1166 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1167 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1168 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1169 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1170 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1171 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1177 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1178 MachineBasicBlock *MBB) const {
1179 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1183 // [... previous instrs leading to comparison ...]
1189 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1191 MachineFunction *MF = MBB->getParent();
1192 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1193 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1194 DebugLoc DL = MI.getDebugLoc();
1195 MachineFunction::iterator It = ++MBB->getIterator();
1197 unsigned DestReg = MI.getOperand(0).getReg();
1198 unsigned IfTrueReg = MI.getOperand(1).getReg();
1199 unsigned IfFalseReg = MI.getOperand(2).getReg();
1200 unsigned CondCode = MI.getOperand(3).getImm();
1201 bool NZCVKilled = MI.getOperand(4).isKill();
1203 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1204 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1205 MF->insert(It, TrueBB);
1206 MF->insert(It, EndBB);
1208 // Transfer rest of current basic-block to EndBB
1209 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1211 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1213 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1214 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1215 MBB->addSuccessor(TrueBB);
1216 MBB->addSuccessor(EndBB);
1218 // TrueBB falls through to the end.
1219 TrueBB->addSuccessor(EndBB);
1222 TrueBB->addLiveIn(AArch64::NZCV);
1223 EndBB->addLiveIn(AArch64::NZCV);
1226 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1232 MI.eraseFromParent();
1236 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1237 MachineInstr &MI, MachineBasicBlock *BB) const {
1238 switch (MI.getOpcode()) {
1243 llvm_unreachable("Unexpected instruction for custom inserter!");
1245 case AArch64::F128CSEL:
1246 return EmitF128CSEL(MI, BB);
1248 case TargetOpcode::STACKMAP:
1249 case TargetOpcode::PATCHPOINT:
1250 return emitPatchPoint(MI, BB);
1254 //===----------------------------------------------------------------------===//
1255 // AArch64 Lowering private implementation.
1256 //===----------------------------------------------------------------------===//
1258 //===----------------------------------------------------------------------===//
1260 //===----------------------------------------------------------------------===//
1262 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1264 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1267 llvm_unreachable("Unknown condition code!");
1269 return AArch64CC::NE;
1271 return AArch64CC::EQ;
1273 return AArch64CC::GT;
1275 return AArch64CC::GE;
1277 return AArch64CC::LT;
1279 return AArch64CC::LE;
1281 return AArch64CC::HI;
1283 return AArch64CC::HS;
1285 return AArch64CC::LO;
1287 return AArch64CC::LS;
1291 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1292 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1293 AArch64CC::CondCode &CondCode,
1294 AArch64CC::CondCode &CondCode2) {
1295 CondCode2 = AArch64CC::AL;
1298 llvm_unreachable("Unknown FP condition!");
1301 CondCode = AArch64CC::EQ;
1305 CondCode = AArch64CC::GT;
1309 CondCode = AArch64CC::GE;
1312 CondCode = AArch64CC::MI;
1315 CondCode = AArch64CC::LS;
1318 CondCode = AArch64CC::MI;
1319 CondCode2 = AArch64CC::GT;
1322 CondCode = AArch64CC::VC;
1325 CondCode = AArch64CC::VS;
1328 CondCode = AArch64CC::EQ;
1329 CondCode2 = AArch64CC::VS;
1332 CondCode = AArch64CC::HI;
1335 CondCode = AArch64CC::PL;
1339 CondCode = AArch64CC::LT;
1343 CondCode = AArch64CC::LE;
1347 CondCode = AArch64CC::NE;
1352 /// Convert a DAG fp condition code to an AArch64 CC.
1353 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1354 /// should be AND'ed instead of OR'ed.
1355 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1356 AArch64CC::CondCode &CondCode,
1357 AArch64CC::CondCode &CondCode2) {
1358 CondCode2 = AArch64CC::AL;
1361 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1362 assert(CondCode2 == AArch64CC::AL);
1366 // == ((a olt b) || (a ogt b))
1367 // == ((a ord b) && (a une b))
1368 CondCode = AArch64CC::VC;
1369 CondCode2 = AArch64CC::NE;
1373 // == ((a uno b) || (a oeq b))
1374 // == ((a ule b) && (a uge b))
1375 CondCode = AArch64CC::PL;
1376 CondCode2 = AArch64CC::LE;
1381 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1382 /// CC usable with the vector instructions. Fewer operations are available
1383 /// without a real NZCV register, so we have to use less efficient combinations
1384 /// to get the same effect.
1385 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1386 AArch64CC::CondCode &CondCode,
1387 AArch64CC::CondCode &CondCode2,
1392 // Mostly the scalar mappings work fine.
1393 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1399 CondCode = AArch64CC::MI;
1400 CondCode2 = AArch64CC::GE;
1407 // All of the compare-mask comparisons are ordered, but we can switch
1408 // between the two by a double inversion. E.g. ULE == !OGT.
1410 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1415 static bool isLegalArithImmed(uint64_t C) {
1416 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1417 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1420 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1421 const SDLoc &dl, SelectionDAG &DAG) {
1422 EVT VT = LHS.getValueType();
1424 if (VT.isFloatingPoint()) {
1425 assert(VT != MVT::f128);
1426 if (VT == MVT::f16) {
1427 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1428 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1431 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1434 // The CMP instruction is just an alias for SUBS, and representing it as
1435 // SUBS means that it's possible to get CSE with subtract operations.
1436 // A later phase can perform the optimization of setting the destination
1437 // register to WZR/XZR if it ends up being unused.
1438 unsigned Opcode = AArch64ISD::SUBS;
1440 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1441 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1442 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1443 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1444 // can be set differently by this operation. It comes down to whether
1445 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1446 // everything is fine. If not then the optimization is wrong. Thus general
1447 // comparisons are only valid if op2 != 0.
1449 // So, finally, the only LLVM-native comparisons that don't mention C and V
1450 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1451 // the absence of information about op2.
1452 Opcode = AArch64ISD::ADDS;
1453 RHS = RHS.getOperand(1);
1454 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1455 !isUnsignedIntSetCC(CC)) {
1456 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1457 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1458 // of the signed comparisons.
1459 Opcode = AArch64ISD::ANDS;
1460 RHS = LHS.getOperand(1);
1461 LHS = LHS.getOperand(0);
1464 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1468 /// \defgroup AArch64CCMP CMP;CCMP matching
1470 /// These functions deal with the formation of CMP;CCMP;... sequences.
1471 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1472 /// a comparison. They set the NZCV flags to a predefined value if their
1473 /// predicate is false. This allows to express arbitrary conjunctions, for
1474 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1477 /// ccmp B, inv(CB), CA
1478 /// check for CB flags
1480 /// In general we can create code for arbitrary "... (and (and A B) C)"
1481 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1482 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1483 /// negation operations:
1484 /// We can negate the results of a single comparison by inverting the flags
1485 /// used when the predicate fails and inverting the flags tested in the next
1486 /// instruction; We can also negate the results of the whole previous
1487 /// conditional compare sequence by inverting the flags tested in the next
1488 /// instruction. However there is no way to negate the result of a partial
1491 /// Therefore on encountering an "or" expression we can negate the subtree on
1492 /// one side and have to be able to push the negate to the leafs of the subtree
1493 /// on the other side (see also the comments in code). As complete example:
1494 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1495 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1496 /// is transformed to
1497 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1498 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1499 /// and implemented as:
1501 /// ccmp D, inv(CD), CC
1502 /// ccmp A, CA, inv(CD)
1503 /// ccmp B, CB, inv(CA)
1504 /// check for CB flags
1505 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1506 /// by conditional compare sequences.
1509 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1510 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1511 ISD::CondCode CC, SDValue CCOp,
1512 AArch64CC::CondCode Predicate,
1513 AArch64CC::CondCode OutCC,
1514 const SDLoc &DL, SelectionDAG &DAG) {
1515 unsigned Opcode = 0;
1516 if (LHS.getValueType().isFloatingPoint()) {
1517 assert(LHS.getValueType() != MVT::f128);
1518 if (LHS.getValueType() == MVT::f16) {
1519 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1520 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1522 Opcode = AArch64ISD::FCCMP;
1523 } else if (RHS.getOpcode() == ISD::SUB) {
1524 SDValue SubOp0 = RHS.getOperand(0);
1525 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1526 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1527 Opcode = AArch64ISD::CCMN;
1528 RHS = RHS.getOperand(1);
1532 Opcode = AArch64ISD::CCMP;
1534 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1535 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1536 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1537 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1538 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1541 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1542 /// CanPushNegate is set to true if we can push a negate operation through
1543 /// the tree in a was that we are left with AND operations and negate operations
1544 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1545 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1546 /// brought into such a form.
1547 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1548 unsigned Depth = 0) {
1549 if (!Val.hasOneUse())
1551 unsigned Opcode = Val->getOpcode();
1552 if (Opcode == ISD::SETCC) {
1553 if (Val->getOperand(0).getValueType() == MVT::f128)
1558 // Protect against exponential runtime and stack overflow.
1561 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1562 SDValue O0 = Val->getOperand(0);
1563 SDValue O1 = Val->getOperand(1);
1565 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1568 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1571 if (Opcode == ISD::OR) {
1572 // For an OR expression we need to be able to negate at least one side or
1573 // we cannot do the transformation at all.
1574 if (!CanNegateL && !CanNegateR)
1576 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1577 // can negate the x and y subtrees.
1578 CanNegate = CanNegateL && CanNegateR;
1580 // If the operands are OR expressions then we finally need to negate their
1581 // outputs, we can only do that for the operand with emitted last by
1582 // negating OutCC, not for both operands.
1583 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1584 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1585 if (NeedsNegOutL && NeedsNegOutR)
1587 // We cannot negate an AND operation (it would become an OR),
1595 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1596 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1597 /// Tries to transform the given i1 producing node @p Val to a series compare
1598 /// and conditional compare operations. @returns an NZCV flags producing node
1599 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1600 /// transformation was not possible.
1601 /// On recursive invocations @p PushNegate may be set to true to have negation
1602 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1603 /// for the comparisons in the current subtree; @p Depth limits the search
1604 /// depth to avoid stack overflow.
1605 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1606 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1607 AArch64CC::CondCode Predicate) {
1608 // We're at a tree leaf, produce a conditional comparison operation.
1609 unsigned Opcode = Val->getOpcode();
1610 if (Opcode == ISD::SETCC) {
1611 SDValue LHS = Val->getOperand(0);
1612 SDValue RHS = Val->getOperand(1);
1613 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1614 bool isInteger = LHS.getValueType().isInteger();
1616 CC = getSetCCInverse(CC, isInteger);
1618 // Determine OutCC and handle FP special case.
1620 OutCC = changeIntCCToAArch64CC(CC);
1622 assert(LHS.getValueType().isFloatingPoint());
1623 AArch64CC::CondCode ExtraCC;
1624 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1625 // Some floating point conditions can't be tested with a single condition
1626 // code. Construct an additional comparison in this case.
1627 if (ExtraCC != AArch64CC::AL) {
1629 if (!CCOp.getNode())
1630 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1632 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1635 Predicate = ExtraCC;
1639 // Produce a normal comparison if we are first in the chain
1641 return emitComparison(LHS, RHS, CC, DL, DAG);
1642 // Otherwise produce a ccmp.
1643 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1646 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1647 "Valid conjunction/disjunction tree");
1649 // Check if both sides can be transformed.
1650 SDValue LHS = Val->getOperand(0);
1651 SDValue RHS = Val->getOperand(1);
1653 // In case of an OR we need to negate our operands and the result.
1654 // (A v B) <=> not(not(A) ^ not(B))
1655 bool NegateOpsAndResult = Opcode == ISD::OR;
1656 // We can negate the results of all previous operations by inverting the
1657 // predicate flags giving us a free negation for one side. The other side
1658 // must be negatable by itself.
1659 if (NegateOpsAndResult) {
1660 // See which side we can negate.
1662 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1663 assert(isValidL && "Valid conjunction/disjunction tree");
1668 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1669 assert(isValidR && "Valid conjunction/disjunction tree");
1670 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1673 // Order the side which we cannot negate to RHS so we can emit it first.
1675 std::swap(LHS, RHS);
1677 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1678 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1679 "Valid conjunction/disjunction tree");
1680 // Order the side where we need to negate the output flags to RHS so it
1681 // gets emitted first.
1683 std::swap(LHS, RHS);
1686 // Emit RHS. If we want to negate the tree we only need to push a negate
1687 // through if we are already in a PushNegate case, otherwise we can negate
1688 // the "flags to test" afterwards.
1689 AArch64CC::CondCode RHSCC;
1690 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1692 if (NegateOpsAndResult && !Negate)
1693 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1694 // Emit LHS. We may need to negate it.
1695 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1696 NegateOpsAndResult, CmpR,
1698 // If we transformed an OR to and AND then we have to negate the result
1699 // (or absorb the Negate parameter).
1700 if (NegateOpsAndResult && !Negate)
1701 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1705 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1706 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1707 /// \see emitConjunctionDisjunctionTreeRec().
1708 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1709 AArch64CC::CondCode &OutCC) {
1711 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1714 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1720 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1721 SDValue &AArch64cc, SelectionDAG &DAG,
1723 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1724 EVT VT = RHS.getValueType();
1725 uint64_t C = RHSC->getZExtValue();
1726 if (!isLegalArithImmed(C)) {
1727 // Constant does not fit, try adjusting it by one?
1733 if ((VT == MVT::i32 && C != 0x80000000 &&
1734 isLegalArithImmed((uint32_t)(C - 1))) ||
1735 (VT == MVT::i64 && C != 0x80000000ULL &&
1736 isLegalArithImmed(C - 1ULL))) {
1737 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1738 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1739 RHS = DAG.getConstant(C, dl, VT);
1744 if ((VT == MVT::i32 && C != 0 &&
1745 isLegalArithImmed((uint32_t)(C - 1))) ||
1746 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1747 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1748 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1749 RHS = DAG.getConstant(C, dl, VT);
1754 if ((VT == MVT::i32 && C != INT32_MAX &&
1755 isLegalArithImmed((uint32_t)(C + 1))) ||
1756 (VT == MVT::i64 && C != INT64_MAX &&
1757 isLegalArithImmed(C + 1ULL))) {
1758 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1759 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1760 RHS = DAG.getConstant(C, dl, VT);
1765 if ((VT == MVT::i32 && C != UINT32_MAX &&
1766 isLegalArithImmed((uint32_t)(C + 1))) ||
1767 (VT == MVT::i64 && C != UINT64_MAX &&
1768 isLegalArithImmed(C + 1ULL))) {
1769 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1770 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1771 RHS = DAG.getConstant(C, dl, VT);
1778 AArch64CC::CondCode AArch64CC;
1779 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1780 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1782 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1783 // For the i8 operand, the largest immediate is 255, so this can be easily
1784 // encoded in the compare instruction. For the i16 operand, however, the
1785 // largest immediate cannot be encoded in the compare.
1786 // Therefore, use a sign extending load and cmn to avoid materializing the
1787 // -1 constant. For example,
1789 // ldrh w0, [x0, #0]
1792 // ldrsh w0, [x0, #0]
1794 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1795 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1796 // ensure both the LHS and RHS are truly zero extended and to make sure the
1797 // transformation is profitable.
1798 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1799 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1800 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1801 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1802 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1803 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1805 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1806 DAG.getValueType(MVT::i16));
1807 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1808 RHS.getValueType()),
1810 AArch64CC = changeIntCCToAArch64CC(CC);
1814 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1815 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1816 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1817 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1823 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1824 AArch64CC = changeIntCCToAArch64CC(CC);
1826 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1830 static std::pair<SDValue, SDValue>
1831 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1832 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1833 "Unsupported value type");
1834 SDValue Value, Overflow;
1836 SDValue LHS = Op.getOperand(0);
1837 SDValue RHS = Op.getOperand(1);
1839 switch (Op.getOpcode()) {
1841 llvm_unreachable("Unknown overflow instruction!");
1843 Opc = AArch64ISD::ADDS;
1847 Opc = AArch64ISD::ADDS;
1851 Opc = AArch64ISD::SUBS;
1855 Opc = AArch64ISD::SUBS;
1858 // Multiply needs a little bit extra work.
1862 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1863 if (Op.getValueType() == MVT::i32) {
1864 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1865 // For a 32 bit multiply with overflow check we want the instruction
1866 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1867 // need to generate the following pattern:
1868 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1869 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1870 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1871 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1872 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1873 DAG.getConstant(0, DL, MVT::i64));
1874 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1875 // operation. We need to clear out the upper 32 bits, because we used a
1876 // widening multiply that wrote all 64 bits. In the end this should be a
1878 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1880 // The signed overflow check requires more than just a simple check for
1881 // any bit set in the upper 32 bits of the result. These bits could be
1882 // just the sign bits of a negative number. To perform the overflow
1883 // check we have to arithmetic shift right the 32nd bit of the result by
1884 // 31 bits. Then we compare the result to the upper 32 bits.
1885 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1886 DAG.getConstant(32, DL, MVT::i64));
1887 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1888 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1889 DAG.getConstant(31, DL, MVT::i64));
1890 // It is important that LowerBits is last, otherwise the arithmetic
1891 // shift will not be folded into the compare (SUBS).
1892 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1893 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1896 // The overflow check for unsigned multiply is easy. We only need to
1897 // check if any of the upper 32 bits are set. This can be done with a
1898 // CMP (shifted register). For that we need to generate the following
1900 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1901 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1902 DAG.getConstant(32, DL, MVT::i64));
1903 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1905 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1906 DAG.getConstant(0, DL, MVT::i64),
1907 UpperBits).getValue(1);
1911 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1912 // For the 64 bit multiply
1913 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1915 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1916 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1917 DAG.getConstant(63, DL, MVT::i64));
1918 // It is important that LowerBits is last, otherwise the arithmetic
1919 // shift will not be folded into the compare (SUBS).
1920 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1921 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1924 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1925 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1927 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1928 DAG.getConstant(0, DL, MVT::i64),
1929 UpperBits).getValue(1);
1936 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1938 // Emit the AArch64 operation with overflow check.
1939 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1940 Overflow = Value.getValue(1);
1942 return std::make_pair(Value, Overflow);
1945 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1946 RTLIB::Libcall Call) const {
1947 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1948 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1951 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1952 SDValue Sel = Op.getOperand(0);
1953 SDValue Other = Op.getOperand(1);
1955 // If neither operand is a SELECT_CC, give up.
1956 if (Sel.getOpcode() != ISD::SELECT_CC)
1957 std::swap(Sel, Other);
1958 if (Sel.getOpcode() != ISD::SELECT_CC)
1961 // The folding we want to perform is:
1962 // (xor x, (select_cc a, b, cc, 0, -1) )
1964 // (csel x, (xor x, -1), cc ...)
1966 // The latter will get matched to a CSINV instruction.
1968 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1969 SDValue LHS = Sel.getOperand(0);
1970 SDValue RHS = Sel.getOperand(1);
1971 SDValue TVal = Sel.getOperand(2);
1972 SDValue FVal = Sel.getOperand(3);
1975 // FIXME: This could be generalized to non-integer comparisons.
1976 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1979 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1980 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1982 // The values aren't constants, this isn't the pattern we're looking for.
1983 if (!CFVal || !CTVal)
1986 // We can commute the SELECT_CC by inverting the condition. This
1987 // might be needed to make this fit into a CSINV pattern.
1988 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1989 std::swap(TVal, FVal);
1990 std::swap(CTVal, CFVal);
1991 CC = ISD::getSetCCInverse(CC, true);
1994 // If the constants line up, perform the transform!
1995 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1997 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2000 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2001 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2003 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2010 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2011 EVT VT = Op.getValueType();
2013 // Let legalize expand this if it isn't a legal type yet.
2014 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2017 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2020 bool ExtraOp = false;
2021 switch (Op.getOpcode()) {
2023 llvm_unreachable("Invalid code");
2025 Opc = AArch64ISD::ADDS;
2028 Opc = AArch64ISD::SUBS;
2031 Opc = AArch64ISD::ADCS;
2035 Opc = AArch64ISD::SBCS;
2041 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2042 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2046 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2047 // Let legalize expand this if it isn't a legal type yet.
2048 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2052 AArch64CC::CondCode CC;
2053 // The actual operation that sets the overflow or carry flag.
2054 SDValue Value, Overflow;
2055 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2057 // We use 0 and 1 as false and true values.
2058 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2059 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2061 // We use an inverted condition, because the conditional select is inverted
2062 // too. This will allow it to be selected to a single instruction:
2063 // CSINC Wd, WZR, WZR, invert(cond).
2064 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2065 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2068 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2069 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2072 // Prefetch operands are:
2073 // 1: Address to prefetch
2075 // 3: int locality (0 = no locality ... 3 = extreme locality)
2076 // 4: bool isDataCache
2077 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2079 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2080 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2081 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2083 bool IsStream = !Locality;
2084 // When the locality number is set
2086 // The front-end should have filtered out the out-of-range values
2087 assert(Locality <= 3 && "Prefetch locality out-of-range");
2088 // The locality degree is the opposite of the cache speed.
2089 // Put the number the other way around.
2090 // The encoding starts at 0 for level 1
2091 Locality = 3 - Locality;
2094 // built the mask value encoding the expected behavior.
2095 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2096 (!IsData << 3) | // IsDataCache bit
2097 (Locality << 1) | // Cache level bits
2098 (unsigned)IsStream; // Stream bit
2099 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2100 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2103 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2104 SelectionDAG &DAG) const {
2105 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2108 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2110 return LowerF128Call(Op, DAG, LC);
2113 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2114 SelectionDAG &DAG) const {
2115 if (Op.getOperand(0).getValueType() != MVT::f128) {
2116 // It's legal except when f128 is involved
2121 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2123 // FP_ROUND node has a second operand indicating whether it is known to be
2124 // precise. That doesn't take part in the LibCall so we can't directly use
2126 SDValue SrcVal = Op.getOperand(0);
2127 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2131 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2132 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2133 // Any additional optimization in this function should be recorded
2134 // in the cost tables.
2135 EVT InVT = Op.getOperand(0).getValueType();
2136 EVT VT = Op.getValueType();
2137 unsigned NumElts = InVT.getVectorNumElements();
2139 // f16 vectors are promoted to f32 before a conversion.
2140 if (InVT.getVectorElementType() == MVT::f16) {
2141 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2144 Op.getOpcode(), dl, Op.getValueType(),
2145 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2148 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2151 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2153 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2156 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2159 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2160 VT.getVectorNumElements());
2161 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2162 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2165 // Type changing conversions are illegal.
2169 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2170 SelectionDAG &DAG) const {
2171 if (Op.getOperand(0).getValueType().isVector())
2172 return LowerVectorFP_TO_INT(Op, DAG);
2174 // f16 conversions are promoted to f32.
2175 if (Op.getOperand(0).getValueType() == MVT::f16) {
2178 Op.getOpcode(), dl, Op.getValueType(),
2179 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2182 if (Op.getOperand(0).getValueType() != MVT::f128) {
2183 // It's legal except when f128 is involved
2188 if (Op.getOpcode() == ISD::FP_TO_SINT)
2189 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2191 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2193 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2194 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2197 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2198 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2199 // Any additional optimization in this function should be recorded
2200 // in the cost tables.
2201 EVT VT = Op.getValueType();
2203 SDValue In = Op.getOperand(0);
2204 EVT InVT = In.getValueType();
2206 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2208 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2209 InVT.getVectorNumElements());
2210 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2211 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2214 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2216 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2217 EVT CastVT = VT.changeVectorElementTypeToInteger();
2218 In = DAG.getNode(CastOpc, dl, CastVT, In);
2219 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2225 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2226 SelectionDAG &DAG) const {
2227 if (Op.getValueType().isVector())
2228 return LowerVectorINT_TO_FP(Op, DAG);
2230 // f16 conversions are promoted to f32.
2231 if (Op.getValueType() == MVT::f16) {
2234 ISD::FP_ROUND, dl, MVT::f16,
2235 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2236 DAG.getIntPtrConstant(0, dl));
2239 // i128 conversions are libcalls.
2240 if (Op.getOperand(0).getValueType() == MVT::i128)
2243 // Other conversions are legal, unless it's to the completely software-based
2245 if (Op.getValueType() != MVT::f128)
2249 if (Op.getOpcode() == ISD::SINT_TO_FP)
2250 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2252 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2254 return LowerF128Call(Op, DAG, LC);
2257 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2258 SelectionDAG &DAG) const {
2259 // For iOS, we want to call an alternative entry point: __sincos_stret,
2260 // which returns the values in two S / D registers.
2262 SDValue Arg = Op.getOperand(0);
2263 EVT ArgVT = Arg.getValueType();
2264 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2271 Entry.IsSExt = false;
2272 Entry.IsZExt = false;
2273 Args.push_back(Entry);
2275 const char *LibcallName =
2276 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2278 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2280 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2281 TargetLowering::CallLoweringInfo CLI(DAG);
2283 .setChain(DAG.getEntryNode())
2284 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2286 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2287 return CallResult.first;
2290 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2291 if (Op.getValueType() != MVT::f16)
2294 assert(Op.getOperand(0).getValueType() == MVT::i16);
2297 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2298 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2300 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2301 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2305 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2306 if (OrigVT.getSizeInBits() >= 64)
2309 assert(OrigVT.isSimple() && "Expecting a simple value type");
2311 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2312 switch (OrigSimpleTy) {
2313 default: llvm_unreachable("Unexpected Vector Type");
2322 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2325 unsigned ExtOpcode) {
2326 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2327 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2328 // 64-bits we need to insert a new extension so that it will be 64-bits.
2329 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2330 if (OrigTy.getSizeInBits() >= 64)
2333 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2334 EVT NewVT = getExtensionTo64Bits(OrigTy);
2336 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2339 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2341 EVT VT = N->getValueType(0);
2343 if (N->getOpcode() != ISD::BUILD_VECTOR)
2346 for (const SDValue &Elt : N->op_values()) {
2347 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2348 unsigned EltSize = VT.getScalarSizeInBits();
2349 unsigned HalfSize = EltSize / 2;
2351 if (!isIntN(HalfSize, C->getSExtValue()))
2354 if (!isUIntN(HalfSize, C->getZExtValue()))
2365 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2366 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2367 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2368 N->getOperand(0)->getValueType(0),
2372 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2373 EVT VT = N->getValueType(0);
2375 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2376 unsigned NumElts = VT.getVectorNumElements();
2377 MVT TruncVT = MVT::getIntegerVT(EltSize);
2378 SmallVector<SDValue, 8> Ops;
2379 for (unsigned i = 0; i != NumElts; ++i) {
2380 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2381 const APInt &CInt = C->getAPIntValue();
2382 // Element types smaller than 32 bits are not legal, so use i32 elements.
2383 // The values are implicitly truncated so sext vs. zext doesn't matter.
2384 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2386 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2389 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2390 return N->getOpcode() == ISD::SIGN_EXTEND ||
2391 isExtendedBUILD_VECTOR(N, DAG, true);
2394 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2395 return N->getOpcode() == ISD::ZERO_EXTEND ||
2396 isExtendedBUILD_VECTOR(N, DAG, false);
2399 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2400 unsigned Opcode = N->getOpcode();
2401 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2402 SDNode *N0 = N->getOperand(0).getNode();
2403 SDNode *N1 = N->getOperand(1).getNode();
2404 return N0->hasOneUse() && N1->hasOneUse() &&
2405 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2410 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2411 unsigned Opcode = N->getOpcode();
2412 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2413 SDNode *N0 = N->getOperand(0).getNode();
2414 SDNode *N1 = N->getOperand(1).getNode();
2415 return N0->hasOneUse() && N1->hasOneUse() &&
2416 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2421 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2422 // Multiplications are only custom-lowered for 128-bit vectors so that
2423 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2424 EVT VT = Op.getValueType();
2425 assert(VT.is128BitVector() && VT.isInteger() &&
2426 "unexpected type for custom-lowering ISD::MUL");
2427 SDNode *N0 = Op.getOperand(0).getNode();
2428 SDNode *N1 = Op.getOperand(1).getNode();
2429 unsigned NewOpc = 0;
2431 bool isN0SExt = isSignExtended(N0, DAG);
2432 bool isN1SExt = isSignExtended(N1, DAG);
2433 if (isN0SExt && isN1SExt)
2434 NewOpc = AArch64ISD::SMULL;
2436 bool isN0ZExt = isZeroExtended(N0, DAG);
2437 bool isN1ZExt = isZeroExtended(N1, DAG);
2438 if (isN0ZExt && isN1ZExt)
2439 NewOpc = AArch64ISD::UMULL;
2440 else if (isN1SExt || isN1ZExt) {
2441 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2442 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2443 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2444 NewOpc = AArch64ISD::SMULL;
2446 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2447 NewOpc = AArch64ISD::UMULL;
2449 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2451 NewOpc = AArch64ISD::UMULL;
2457 if (VT == MVT::v2i64)
2458 // Fall through to expand this. It is not legal.
2461 // Other vector multiplications are legal.
2466 // Legalize to a S/UMULL instruction
2469 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2471 Op0 = skipExtensionForVectorMULL(N0, DAG);
2472 assert(Op0.getValueType().is64BitVector() &&
2473 Op1.getValueType().is64BitVector() &&
2474 "unexpected types for extended operands to VMULL");
2475 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2477 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2478 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2479 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2480 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2481 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2482 EVT Op1VT = Op1.getValueType();
2483 return DAG.getNode(N0->getOpcode(), DL, VT,
2484 DAG.getNode(NewOpc, DL, VT,
2485 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2486 DAG.getNode(NewOpc, DL, VT,
2487 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2490 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2491 SelectionDAG &DAG) const {
2492 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2495 default: return SDValue(); // Don't custom lower most intrinsics.
2496 case Intrinsic::thread_pointer: {
2497 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2498 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2500 case Intrinsic::aarch64_neon_abs:
2501 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2503 case Intrinsic::aarch64_neon_smax:
2504 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2505 Op.getOperand(1), Op.getOperand(2));
2506 case Intrinsic::aarch64_neon_umax:
2507 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2508 Op.getOperand(1), Op.getOperand(2));
2509 case Intrinsic::aarch64_neon_smin:
2510 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2511 Op.getOperand(1), Op.getOperand(2));
2512 case Intrinsic::aarch64_neon_umin:
2513 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2514 Op.getOperand(1), Op.getOperand(2));
2518 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2519 SelectionDAG &DAG) const {
2520 switch (Op.getOpcode()) {
2522 llvm_unreachable("unimplemented operand");
2525 return LowerBITCAST(Op, DAG);
2526 case ISD::GlobalAddress:
2527 return LowerGlobalAddress(Op, DAG);
2528 case ISD::GlobalTLSAddress:
2529 return LowerGlobalTLSAddress(Op, DAG);
2531 return LowerSETCC(Op, DAG);
2533 return LowerBR_CC(Op, DAG);
2535 return LowerSELECT(Op, DAG);
2536 case ISD::SELECT_CC:
2537 return LowerSELECT_CC(Op, DAG);
2538 case ISD::JumpTable:
2539 return LowerJumpTable(Op, DAG);
2540 case ISD::ConstantPool:
2541 return LowerConstantPool(Op, DAG);
2542 case ISD::BlockAddress:
2543 return LowerBlockAddress(Op, DAG);
2545 return LowerVASTART(Op, DAG);
2547 return LowerVACOPY(Op, DAG);
2549 return LowerVAARG(Op, DAG);
2554 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2561 return LowerXALUO(Op, DAG);
2563 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2565 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2567 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2569 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2571 return LowerFP_ROUND(Op, DAG);
2572 case ISD::FP_EXTEND:
2573 return LowerFP_EXTEND(Op, DAG);
2574 case ISD::FRAMEADDR:
2575 return LowerFRAMEADDR(Op, DAG);
2576 case ISD::RETURNADDR:
2577 return LowerRETURNADDR(Op, DAG);
2578 case ISD::INSERT_VECTOR_ELT:
2579 return LowerINSERT_VECTOR_ELT(Op, DAG);
2580 case ISD::EXTRACT_VECTOR_ELT:
2581 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2582 case ISD::BUILD_VECTOR:
2583 return LowerBUILD_VECTOR(Op, DAG);
2584 case ISD::VECTOR_SHUFFLE:
2585 return LowerVECTOR_SHUFFLE(Op, DAG);
2586 case ISD::EXTRACT_SUBVECTOR:
2587 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2591 return LowerVectorSRA_SRL_SHL(Op, DAG);
2592 case ISD::SHL_PARTS:
2593 return LowerShiftLeftParts(Op, DAG);
2594 case ISD::SRL_PARTS:
2595 case ISD::SRA_PARTS:
2596 return LowerShiftRightParts(Op, DAG);
2598 return LowerCTPOP(Op, DAG);
2599 case ISD::FCOPYSIGN:
2600 return LowerFCOPYSIGN(Op, DAG);
2602 return LowerVectorAND(Op, DAG);
2604 return LowerVectorOR(Op, DAG);
2606 return LowerXOR(Op, DAG);
2608 return LowerPREFETCH(Op, DAG);
2609 case ISD::SINT_TO_FP:
2610 case ISD::UINT_TO_FP:
2611 return LowerINT_TO_FP(Op, DAG);
2612 case ISD::FP_TO_SINT:
2613 case ISD::FP_TO_UINT:
2614 return LowerFP_TO_INT(Op, DAG);
2616 return LowerFSINCOS(Op, DAG);
2618 return LowerMUL(Op, DAG);
2619 case ISD::INTRINSIC_WO_CHAIN:
2620 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2621 case ISD::VECREDUCE_ADD:
2622 case ISD::VECREDUCE_SMAX:
2623 case ISD::VECREDUCE_SMIN:
2624 case ISD::VECREDUCE_UMAX:
2625 case ISD::VECREDUCE_UMIN:
2626 case ISD::VECREDUCE_FMAX:
2627 case ISD::VECREDUCE_FMIN:
2628 return LowerVECREDUCE(Op, DAG);
2632 //===----------------------------------------------------------------------===//
2633 // Calling Convention Implementation
2634 //===----------------------------------------------------------------------===//
2636 #include "AArch64GenCallingConv.inc"
2638 /// Selects the correct CCAssignFn for a given CallingConvention value.
2639 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2640 bool IsVarArg) const {
2643 llvm_unreachable("Unsupported calling convention.");
2644 case CallingConv::WebKit_JS:
2645 return CC_AArch64_WebKit_JS;
2646 case CallingConv::GHC:
2647 return CC_AArch64_GHC;
2648 case CallingConv::C:
2649 case CallingConv::Fast:
2650 case CallingConv::PreserveMost:
2651 case CallingConv::CXX_FAST_TLS:
2652 case CallingConv::Swift:
2653 if (Subtarget->isTargetWindows() && IsVarArg)
2654 return CC_AArch64_Win64_VarArg;
2655 if (!Subtarget->isTargetDarwin())
2656 return CC_AArch64_AAPCS;
2657 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2658 case CallingConv::Win64:
2659 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2664 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2665 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2666 : RetCC_AArch64_AAPCS;
2669 SDValue AArch64TargetLowering::LowerFormalArguments(
2670 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2671 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2672 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2673 MachineFunction &MF = DAG.getMachineFunction();
2674 MachineFrameInfo &MFI = MF.getFrameInfo();
2675 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
2677 // Assign locations to all of the incoming arguments.
2678 SmallVector<CCValAssign, 16> ArgLocs;
2679 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2682 // At this point, Ins[].VT may already be promoted to i32. To correctly
2683 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2684 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2685 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2686 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2688 unsigned NumArgs = Ins.size();
2689 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2690 unsigned CurArgIdx = 0;
2691 for (unsigned i = 0; i != NumArgs; ++i) {
2692 MVT ValVT = Ins[i].VT;
2693 if (Ins[i].isOrigArg()) {
2694 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2695 CurArgIdx = Ins[i].getOrigArgIndex();
2697 // Get type of the original argument.
2698 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2699 /*AllowUnknown*/ true);
2700 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2701 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2702 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2704 else if (ActualMVT == MVT::i16)
2707 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2709 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2710 assert(!Res && "Call operand has unhandled type");
2713 assert(ArgLocs.size() == Ins.size());
2714 SmallVector<SDValue, 16> ArgValues;
2715 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2716 CCValAssign &VA = ArgLocs[i];
2718 if (Ins[i].Flags.isByVal()) {
2719 // Byval is used for HFAs in the PCS, but the system should work in a
2720 // non-compliant manner for larger structs.
2721 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2722 int Size = Ins[i].Flags.getByValSize();
2723 unsigned NumRegs = (Size + 7) / 8;
2725 // FIXME: This works on big-endian for composite byvals, which are the common
2726 // case. It should also work for fundamental types too.
2728 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2729 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2730 InVals.push_back(FrameIdxN);
2735 if (VA.isRegLoc()) {
2736 // Arguments stored in registers.
2737 EVT RegVT = VA.getLocVT();
2740 const TargetRegisterClass *RC;
2742 if (RegVT == MVT::i32)
2743 RC = &AArch64::GPR32RegClass;
2744 else if (RegVT == MVT::i64)
2745 RC = &AArch64::GPR64RegClass;
2746 else if (RegVT == MVT::f16)
2747 RC = &AArch64::FPR16RegClass;
2748 else if (RegVT == MVT::f32)
2749 RC = &AArch64::FPR32RegClass;
2750 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2751 RC = &AArch64::FPR64RegClass;
2752 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2753 RC = &AArch64::FPR128RegClass;
2755 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2757 // Transform the arguments in physical registers into virtual ones.
2758 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2759 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2761 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2762 // to 64 bits. Insert an assert[sz]ext to capture this, then
2763 // truncate to the right size.
2764 switch (VA.getLocInfo()) {
2766 llvm_unreachable("Unknown loc info!");
2767 case CCValAssign::Full:
2769 case CCValAssign::BCvt:
2770 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2772 case CCValAssign::AExt:
2773 case CCValAssign::SExt:
2774 case CCValAssign::ZExt:
2775 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2776 // nodes after our lowering.
2777 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2781 InVals.push_back(ArgValue);
2783 } else { // VA.isRegLoc()
2784 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2785 unsigned ArgOffset = VA.getLocMemOffset();
2786 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2788 uint32_t BEAlign = 0;
2789 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2790 !Ins[i].Flags.isInConsecutiveRegs())
2791 BEAlign = 8 - ArgSize;
2793 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2795 // Create load nodes to retrieve arguments from the stack.
2796 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2799 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2800 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2801 MVT MemVT = VA.getValVT();
2803 switch (VA.getLocInfo()) {
2806 case CCValAssign::BCvt:
2807 MemVT = VA.getLocVT();
2809 case CCValAssign::SExt:
2810 ExtType = ISD::SEXTLOAD;
2812 case CCValAssign::ZExt:
2813 ExtType = ISD::ZEXTLOAD;
2815 case CCValAssign::AExt:
2816 ExtType = ISD::EXTLOAD;
2820 ArgValue = DAG.getExtLoad(
2821 ExtType, DL, VA.getLocVT(), Chain, FIN,
2822 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2825 InVals.push_back(ArgValue);
2830 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2832 if (!Subtarget->isTargetDarwin() || IsWin64) {
2833 // The AAPCS variadic function ABI is identical to the non-variadic
2834 // one. As a result there may be more arguments in registers and we should
2835 // save them for future reference.
2836 // Win64 variadic functions also pass arguments in registers, but all float
2837 // arguments are passed in integer registers.
2838 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2841 // This will point to the next argument passed via stack.
2842 unsigned StackOffset = CCInfo.getNextStackOffset();
2843 // We currently pass all varargs at 8-byte alignment.
2844 StackOffset = ((StackOffset + 7) & ~7);
2845 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2848 unsigned StackArgSize = CCInfo.getNextStackOffset();
2849 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2850 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2851 // This is a non-standard ABI so by fiat I say we're allowed to make full
2852 // use of the stack area to be popped, which must be aligned to 16 bytes in
2854 StackArgSize = alignTo(StackArgSize, 16);
2856 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2857 // a multiple of 16.
2858 FuncInfo->setArgumentStackToRestore(StackArgSize);
2860 // This realignment carries over to the available bytes below. Our own
2861 // callers will guarantee the space is free by giving an aligned value to
2864 // Even if we're not expected to free up the space, it's useful to know how
2865 // much is there while considering tail calls (because we can reuse it).
2866 FuncInfo->setBytesInStackArgArea(StackArgSize);
2871 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2874 SDValue &Chain) const {
2875 MachineFunction &MF = DAG.getMachineFunction();
2876 MachineFrameInfo &MFI = MF.getFrameInfo();
2877 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2878 auto PtrVT = getPointerTy(DAG.getDataLayout());
2879 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
2881 SmallVector<SDValue, 8> MemOps;
2883 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2884 AArch64::X3, AArch64::X4, AArch64::X5,
2885 AArch64::X6, AArch64::X7 };
2886 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2887 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2889 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2891 if (GPRSaveSize != 0) {
2893 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
2895 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2897 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2899 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2900 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2901 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2902 SDValue Store = DAG.getStore(
2903 Val.getValue(1), DL, Val, FIN,
2905 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2907 (i - FirstVariadicGPR) * 8)
2908 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2909 MemOps.push_back(Store);
2911 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2914 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2915 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2917 if (Subtarget->hasFPARMv8() && !IsWin64) {
2918 static const MCPhysReg FPRArgRegs[] = {
2919 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2920 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2921 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2922 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2924 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2926 if (FPRSaveSize != 0) {
2927 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2929 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2931 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2932 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2933 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2935 SDValue Store = DAG.getStore(
2936 Val.getValue(1), DL, Val, FIN,
2937 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2938 MemOps.push_back(Store);
2939 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2940 DAG.getConstant(16, DL, PtrVT));
2943 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2944 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2947 if (!MemOps.empty()) {
2948 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2952 /// LowerCallResult - Lower the result values of a call into the
2953 /// appropriate copies out of appropriate physical registers.
2954 SDValue AArch64TargetLowering::LowerCallResult(
2955 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2956 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2957 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2958 SDValue ThisVal) const {
2959 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2960 ? RetCC_AArch64_WebKit_JS
2961 : RetCC_AArch64_AAPCS;
2962 // Assign locations to each value returned by this call.
2963 SmallVector<CCValAssign, 16> RVLocs;
2964 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2966 CCInfo.AnalyzeCallResult(Ins, RetCC);
2968 // Copy all of the result registers out of their specified physreg.
2969 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2970 CCValAssign VA = RVLocs[i];
2972 // Pass 'this' value directly from the argument to return value, to avoid
2973 // reg unit interference
2974 if (i == 0 && isThisReturn) {
2975 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2976 "unexpected return calling convention register assignment");
2977 InVals.push_back(ThisVal);
2982 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2983 Chain = Val.getValue(1);
2984 InFlag = Val.getValue(2);
2986 switch (VA.getLocInfo()) {
2988 llvm_unreachable("Unknown loc info!");
2989 case CCValAssign::Full:
2991 case CCValAssign::BCvt:
2992 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2996 InVals.push_back(Val);
3002 /// Return true if the calling convention is one that we can guarantee TCO for.
3003 static bool canGuaranteeTCO(CallingConv::ID CC) {
3004 return CC == CallingConv::Fast;
3007 /// Return true if we might ever do TCO for calls with this calling convention.
3008 static bool mayTailCallThisCC(CallingConv::ID CC) {
3010 case CallingConv::C:
3011 case CallingConv::PreserveMost:
3012 case CallingConv::Swift:
3015 return canGuaranteeTCO(CC);
3019 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3020 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3021 const SmallVectorImpl<ISD::OutputArg> &Outs,
3022 const SmallVectorImpl<SDValue> &OutVals,
3023 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3024 if (!mayTailCallThisCC(CalleeCC))
3027 MachineFunction &MF = DAG.getMachineFunction();
3028 const Function *CallerF = MF.getFunction();
3029 CallingConv::ID CallerCC = CallerF->getCallingConv();
3030 bool CCMatch = CallerCC == CalleeCC;
3032 // Byval parameters hand the function a pointer directly into the stack area
3033 // we want to reuse during a tail call. Working around this *is* possible (see
3034 // X86) but less efficient and uglier in LowerCall.
3035 for (Function::const_arg_iterator i = CallerF->arg_begin(),
3036 e = CallerF->arg_end();
3038 if (i->hasByValAttr())
3041 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3042 return canGuaranteeTCO(CalleeCC) && CCMatch;
3044 // Externally-defined functions with weak linkage should not be
3045 // tail-called on AArch64 when the OS does not support dynamic
3046 // pre-emption of symbols, as the AAELF spec requires normal calls
3047 // to undefined weak functions to be replaced with a NOP or jump to the
3048 // next instruction. The behaviour of branch instructions in this
3049 // situation (as used for tail calls) is implementation-defined, so we
3050 // cannot rely on the linker replacing the tail call with a return.
3051 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3052 const GlobalValue *GV = G->getGlobal();
3053 const Triple &TT = getTargetMachine().getTargetTriple();
3054 if (GV->hasExternalWeakLinkage() &&
3055 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3059 // Now we search for cases where we can use a tail call without changing the
3060 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3063 // I want anyone implementing a new calling convention to think long and hard
3064 // about this assert.
3065 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3066 "Unexpected variadic calling convention");
3068 LLVMContext &C = *DAG.getContext();
3069 if (isVarArg && !Outs.empty()) {
3070 // At least two cases here: if caller is fastcc then we can't have any
3071 // memory arguments (we'd be expected to clean up the stack afterwards). If
3072 // caller is C then we could potentially use its argument area.
3074 // FIXME: for now we take the most conservative of these in both cases:
3075 // disallow all variadic memory operands.
3076 SmallVector<CCValAssign, 16> ArgLocs;
3077 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3079 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3080 for (const CCValAssign &ArgLoc : ArgLocs)
3081 if (!ArgLoc.isRegLoc())
3085 // Check that the call results are passed in the same way.
3086 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3087 CCAssignFnForCall(CalleeCC, isVarArg),
3088 CCAssignFnForCall(CallerCC, isVarArg)))
3090 // The callee has to preserve all registers the caller needs to preserve.
3091 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3092 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3094 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3095 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3099 // Nothing more to check if the callee is taking no arguments
3103 SmallVector<CCValAssign, 16> ArgLocs;
3104 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3106 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3108 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3110 // If the stack arguments for this call do not fit into our own save area then
3111 // the call cannot be made tail.
3112 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3115 const MachineRegisterInfo &MRI = MF.getRegInfo();
3116 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3122 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3124 MachineFrameInfo &MFI,
3125 int ClobberedFI) const {
3126 SmallVector<SDValue, 8> ArgChains;
3127 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3128 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3130 // Include the original chain at the beginning of the list. When this is
3131 // used by target LowerCall hooks, this helps legalize find the
3132 // CALLSEQ_BEGIN node.
3133 ArgChains.push_back(Chain);
3135 // Add a chain value for each stack argument corresponding
3136 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3137 UE = DAG.getEntryNode().getNode()->use_end();
3139 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3140 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3141 if (FI->getIndex() < 0) {
3142 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3143 int64_t InLastByte = InFirstByte;
3144 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3146 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3147 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3148 ArgChains.push_back(SDValue(L, 1));
3151 // Build a tokenfactor for all the chains.
3152 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3155 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3156 bool TailCallOpt) const {
3157 return CallCC == CallingConv::Fast && TailCallOpt;
3160 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3161 /// and add input and output parameter nodes.
3163 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3164 SmallVectorImpl<SDValue> &InVals) const {
3165 SelectionDAG &DAG = CLI.DAG;
3167 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3168 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3169 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3170 SDValue Chain = CLI.Chain;
3171 SDValue Callee = CLI.Callee;
3172 bool &IsTailCall = CLI.IsTailCall;
3173 CallingConv::ID CallConv = CLI.CallConv;
3174 bool IsVarArg = CLI.IsVarArg;
3176 MachineFunction &MF = DAG.getMachineFunction();
3177 bool IsThisReturn = false;
3179 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3180 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3181 bool IsSibCall = false;
3184 // Check if it's really possible to do a tail call.
3185 IsTailCall = isEligibleForTailCallOptimization(
3186 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3187 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3188 report_fatal_error("failed to perform tail call elimination on a call "
3189 "site marked musttail");
3191 // A sibling call is one where we're under the usual C ABI and not planning
3192 // to change that but can still do a tail call:
3193 if (!TailCallOpt && IsTailCall)
3200 // Analyze operands of the call, assigning locations to each operand.
3201 SmallVector<CCValAssign, 16> ArgLocs;
3202 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3206 // Handle fixed and variable vector arguments differently.
3207 // Variable vector arguments always go into memory.
3208 unsigned NumArgs = Outs.size();
3210 for (unsigned i = 0; i != NumArgs; ++i) {
3211 MVT ArgVT = Outs[i].VT;
3212 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3213 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3214 /*IsVarArg=*/ !Outs[i].IsFixed);
3215 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3216 assert(!Res && "Call operand has unhandled type");
3220 // At this point, Outs[].VT may already be promoted to i32. To correctly
3221 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3222 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3223 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3224 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3226 unsigned NumArgs = Outs.size();
3227 for (unsigned i = 0; i != NumArgs; ++i) {
3228 MVT ValVT = Outs[i].VT;
3229 // Get type of the original argument.
3230 EVT ActualVT = getValueType(DAG.getDataLayout(),
3231 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3232 /*AllowUnknown*/ true);
3233 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3234 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3235 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3236 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3238 else if (ActualMVT == MVT::i16)
3241 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3242 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3243 assert(!Res && "Call operand has unhandled type");
3248 // Get a count of how many bytes are to be pushed on the stack.
3249 unsigned NumBytes = CCInfo.getNextStackOffset();
3252 // Since we're not changing the ABI to make this a tail call, the memory
3253 // operands are already available in the caller's incoming argument space.
3257 // FPDiff is the byte offset of the call's argument area from the callee's.
3258 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3259 // by this amount for a tail call. In a sibling call it must be 0 because the
3260 // caller will deallocate the entire stack and the callee still expects its
3261 // arguments to begin at SP+0. Completely unused for non-tail calls.
3264 if (IsTailCall && !IsSibCall) {
3265 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3267 // Since callee will pop argument stack as a tail call, we must keep the
3268 // popped size 16-byte aligned.
3269 NumBytes = alignTo(NumBytes, 16);
3271 // FPDiff will be negative if this tail call requires more space than we
3272 // would automatically have in our incoming argument space. Positive if we
3273 // can actually shrink the stack.
3274 FPDiff = NumReusableBytes - NumBytes;
3276 // The stack pointer must be 16-byte aligned at all times it's used for a
3277 // memory operation, which in practice means at *all* times and in
3278 // particular across call boundaries. Therefore our own arguments started at
3279 // a 16-byte aligned SP and the delta applied for the tail call should
3280 // satisfy the same constraint.
3281 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3284 // Adjust the stack pointer for the new arguments...
3285 // These operations are automatically eliminated by the prolog/epilog pass
3287 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3289 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3290 getPointerTy(DAG.getDataLayout()));
3292 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3293 SmallVector<SDValue, 8> MemOpChains;
3294 auto PtrVT = getPointerTy(DAG.getDataLayout());
3296 // Walk the register/memloc assignments, inserting copies/loads.
3297 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3298 ++i, ++realArgIdx) {
3299 CCValAssign &VA = ArgLocs[i];
3300 SDValue Arg = OutVals[realArgIdx];
3301 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3303 // Promote the value if needed.
3304 switch (VA.getLocInfo()) {
3306 llvm_unreachable("Unknown loc info!");
3307 case CCValAssign::Full:
3309 case CCValAssign::SExt:
3310 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3312 case CCValAssign::ZExt:
3313 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3315 case CCValAssign::AExt:
3316 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3317 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3318 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3319 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3321 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3323 case CCValAssign::BCvt:
3324 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3326 case CCValAssign::FPExt:
3327 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3331 if (VA.isRegLoc()) {
3332 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3333 Outs[0].VT == MVT::i64) {
3334 assert(VA.getLocVT() == MVT::i64 &&
3335 "unexpected calling convention register assignment");
3336 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3337 "unexpected use of 'returned'");
3338 IsThisReturn = true;
3340 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3342 assert(VA.isMemLoc());
3345 MachinePointerInfo DstInfo;
3347 // FIXME: This works on big-endian for composite byvals, which are the
3348 // common case. It should also work for fundamental types too.
3349 uint32_t BEAlign = 0;
3350 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3351 : VA.getValVT().getSizeInBits();
3352 OpSize = (OpSize + 7) / 8;
3353 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3354 !Flags.isInConsecutiveRegs()) {
3356 BEAlign = 8 - OpSize;
3358 unsigned LocMemOffset = VA.getLocMemOffset();
3359 int32_t Offset = LocMemOffset + BEAlign;
3360 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3361 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3364 Offset = Offset + FPDiff;
3365 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3367 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3369 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3371 // Make sure any stack arguments overlapping with where we're storing
3372 // are loaded before this eventual operation. Otherwise they'll be
3374 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3376 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3378 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3379 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3383 if (Outs[i].Flags.isByVal()) {
3385 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3386 SDValue Cpy = DAG.getMemcpy(
3387 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3388 /*isVol = */ false, /*AlwaysInline = */ false,
3389 /*isTailCall = */ false,
3390 DstInfo, MachinePointerInfo());
3392 MemOpChains.push_back(Cpy);
3394 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3395 // promoted to a legal register type i32, we should truncate Arg back to
3397 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3398 VA.getValVT() == MVT::i16)
3399 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3401 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3402 MemOpChains.push_back(Store);
3407 if (!MemOpChains.empty())
3408 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3410 // Build a sequence of copy-to-reg nodes chained together with token chain
3411 // and flag operands which copy the outgoing args into the appropriate regs.
3413 for (auto &RegToPass : RegsToPass) {
3414 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3415 RegToPass.second, InFlag);
3416 InFlag = Chain.getValue(1);
3419 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3420 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3421 // node so that legalize doesn't hack it.
3422 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3423 auto GV = G->getGlobal();
3424 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3425 AArch64II::MO_GOT) {
3426 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3427 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3429 const GlobalValue *GV = G->getGlobal();
3430 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3432 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3433 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3434 Subtarget->isTargetMachO()) {
3435 const char *Sym = S->getSymbol();
3436 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3437 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3439 const char *Sym = S->getSymbol();
3440 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3444 // We don't usually want to end the call-sequence here because we would tidy
3445 // the frame up *after* the call, however in the ABI-changing tail-call case
3446 // we've carefully laid out the parameters so that when sp is reset they'll be
3447 // in the correct location.
3448 if (IsTailCall && !IsSibCall) {
3449 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3450 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3451 InFlag = Chain.getValue(1);
3454 std::vector<SDValue> Ops;
3455 Ops.push_back(Chain);
3456 Ops.push_back(Callee);
3459 // Each tail call may have to adjust the stack by a different amount, so
3460 // this information must travel along with the operation for eventual
3461 // consumption by emitEpilogue.
3462 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3465 // Add argument registers to the end of the list so that they are known live
3467 for (auto &RegToPass : RegsToPass)
3468 Ops.push_back(DAG.getRegister(RegToPass.first,
3469 RegToPass.second.getValueType()));
3471 // Add a register mask operand representing the call-preserved registers.
3472 const uint32_t *Mask;
3473 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3475 // For 'this' returns, use the X0-preserving mask if applicable
3476 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3478 IsThisReturn = false;
3479 Mask = TRI->getCallPreservedMask(MF, CallConv);
3482 Mask = TRI->getCallPreservedMask(MF, CallConv);
3484 assert(Mask && "Missing call preserved mask for calling convention");
3485 Ops.push_back(DAG.getRegisterMask(Mask));
3487 if (InFlag.getNode())
3488 Ops.push_back(InFlag);
3490 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3492 // If we're doing a tall call, use a TC_RETURN here rather than an
3493 // actual call instruction.
3495 MF.getFrameInfo().setHasTailCall();
3496 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3499 // Returns a chain and a flag for retval copy to use.
3500 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3501 InFlag = Chain.getValue(1);
3503 uint64_t CalleePopBytes =
3504 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3506 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3507 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3510 InFlag = Chain.getValue(1);
3512 // Handle result values, copying them out of physregs into vregs that we
3514 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3515 InVals, IsThisReturn,
3516 IsThisReturn ? OutVals[0] : SDValue());
3519 bool AArch64TargetLowering::CanLowerReturn(
3520 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3521 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3522 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3523 ? RetCC_AArch64_WebKit_JS
3524 : RetCC_AArch64_AAPCS;
3525 SmallVector<CCValAssign, 16> RVLocs;
3526 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3527 return CCInfo.CheckReturn(Outs, RetCC);
3531 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3533 const SmallVectorImpl<ISD::OutputArg> &Outs,
3534 const SmallVectorImpl<SDValue> &OutVals,
3535 const SDLoc &DL, SelectionDAG &DAG) const {
3536 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3537 ? RetCC_AArch64_WebKit_JS
3538 : RetCC_AArch64_AAPCS;
3539 SmallVector<CCValAssign, 16> RVLocs;
3540 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3542 CCInfo.AnalyzeReturn(Outs, RetCC);
3544 // Copy the result values into the output registers.
3546 SmallVector<SDValue, 4> RetOps(1, Chain);
3547 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3548 ++i, ++realRVLocIdx) {
3549 CCValAssign &VA = RVLocs[i];
3550 assert(VA.isRegLoc() && "Can only return in registers!");
3551 SDValue Arg = OutVals[realRVLocIdx];
3553 switch (VA.getLocInfo()) {
3555 llvm_unreachable("Unknown loc info!");
3556 case CCValAssign::Full:
3557 if (Outs[i].ArgVT == MVT::i1) {
3558 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3559 // value. This is strictly redundant on Darwin (which uses "zeroext
3560 // i1"), but will be optimised out before ISel.
3561 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3562 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3565 case CCValAssign::BCvt:
3566 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3570 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3571 Flag = Chain.getValue(1);
3572 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3574 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3575 const MCPhysReg *I =
3576 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3579 if (AArch64::GPR64RegClass.contains(*I))
3580 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3581 else if (AArch64::FPR64RegClass.contains(*I))
3582 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3584 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3588 RetOps[0] = Chain; // Update chain.
3590 // Add the flag if we have it.
3592 RetOps.push_back(Flag);
3594 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3597 //===----------------------------------------------------------------------===//
3598 // Other Lowering Code
3599 //===----------------------------------------------------------------------===//
3601 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3603 unsigned Flag) const {
3604 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3607 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3609 unsigned Flag) const {
3610 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3613 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3615 unsigned Flag) const {
3616 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3617 N->getOffset(), Flag);
3620 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3622 unsigned Flag) const {
3623 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3627 template <class NodeTy>
3628 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const {
3629 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3631 EVT Ty = getPointerTy(DAG.getDataLayout());
3632 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT);
3633 // FIXME: Once remat is capable of dealing with instructions with register
3634 // operands, expand this into two nodes instead of using a wrapper node.
3635 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3638 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3639 template <class NodeTy>
3640 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG)
3642 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3644 EVT Ty = getPointerTy(DAG.getDataLayout());
3645 const unsigned char MO_NC = AArch64II::MO_NC;
3647 AArch64ISD::WrapperLarge, DL, Ty,
3648 getTargetNode(N, Ty, DAG, AArch64II::MO_G3),
3649 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC),
3650 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC),
3651 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC));
3654 // (addlow (adrp %hi(sym)) %lo(sym))
3655 template <class NodeTy>
3656 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
3657 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3659 EVT Ty = getPointerTy(DAG.getDataLayout());
3660 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE);
3661 SDValue Lo = getTargetNode(N, Ty, DAG,
3662 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3663 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3664 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3667 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3668 SelectionDAG &DAG) const {
3669 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3670 const GlobalValue *GV = GN->getGlobal();
3671 unsigned char OpFlags =
3672 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3674 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3675 "unexpected offset in global node");
3677 // This also catches the large code model case for Darwin.
3678 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3679 return getGOT(GN, DAG);
3682 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3683 return getAddrLarge(GN, DAG);
3685 return getAddr(GN, DAG);
3689 /// \brief Convert a TLS address reference into the correct sequence of loads
3690 /// and calls to compute the variable's address (for Darwin, currently) and
3691 /// return an SDValue containing the final node.
3693 /// Darwin only has one TLS scheme which must be capable of dealing with the
3694 /// fully general situation, in the worst case. This means:
3695 /// + "extern __thread" declaration.
3696 /// + Defined in a possibly unknown dynamic library.
3698 /// The general system is that each __thread variable has a [3 x i64] descriptor
3699 /// which contains information used by the runtime to calculate the address. The
3700 /// only part of this the compiler needs to know about is the first xword, which
3701 /// contains a function pointer that must be called with the address of the
3702 /// entire descriptor in "x0".
3704 /// Since this descriptor may be in a different unit, in general even the
3705 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3707 /// adrp x0, _var@TLVPPAGE
3708 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3709 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3710 /// ; the function pointer
3711 /// blr x1 ; Uses descriptor address in x0
3712 /// ; Address of _var is now in x0.
3714 /// If the address of _var's descriptor *is* known to the linker, then it can
3715 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3716 /// a slight efficiency gain.
3718 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3719 SelectionDAG &DAG) const {
3720 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3723 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3724 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3727 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3728 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3730 // The first entry in the descriptor is a function pointer that we must call
3731 // to obtain the address of the variable.
3732 SDValue Chain = DAG.getEntryNode();
3733 SDValue FuncTLVGet = DAG.getLoad(
3734 MVT::i64, DL, Chain, DescAddr,
3735 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3736 /* Alignment = */ 8,
3737 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3738 MachineMemOperand::MODereferenceable);
3739 Chain = FuncTLVGet.getValue(1);
3741 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3742 MFI.setAdjustsStack(true);
3744 // TLS calls preserve all registers except those that absolutely must be
3745 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3747 const uint32_t *Mask =
3748 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3750 // Finally, we can make the call. This is just a degenerate version of a
3751 // normal AArch64 call node: x0 takes the address of the descriptor, and
3752 // returns the address of the variable in this thread.
3753 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3755 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3756 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3757 DAG.getRegisterMask(Mask), Chain.getValue(1));
3758 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3761 /// When accessing thread-local variables under either the general-dynamic or
3762 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3763 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3764 /// is a function pointer to carry out the resolution.
3766 /// The sequence is:
3767 /// adrp x0, :tlsdesc:var
3768 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3769 /// add x0, x0, #:tlsdesc_lo12:var
3770 /// .tlsdesccall var
3772 /// (TPIDR_EL0 offset now in x0)
3774 /// The above sequence must be produced unscheduled, to enable the linker to
3775 /// optimize/relax this sequence.
3776 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3777 /// above sequence, and expanded really late in the compilation flow, to ensure
3778 /// the sequence is produced as per above.
3779 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3781 SelectionDAG &DAG) const {
3782 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3784 SDValue Chain = DAG.getEntryNode();
3785 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3788 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3789 SDValue Glue = Chain.getValue(1);
3791 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3795 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3796 SelectionDAG &DAG) const {
3797 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3798 assert(Subtarget->useSmallAddressing() &&
3799 "ELF TLS only supported in small memory model");
3800 // Different choices can be made for the maximum size of the TLS area for a
3801 // module. For the small address model, the default TLS size is 16MiB and the
3802 // maximum TLS size is 4GiB.
3803 // FIXME: add -mtls-size command line option and make it control the 16MiB
3804 // vs. 4GiB code sequence generation.
3805 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3807 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3809 if (DAG.getTarget().Options.EmulatedTLS)
3810 return LowerToTLSEmulatedModel(GA, DAG);
3812 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3813 if (Model == TLSModel::LocalDynamic)
3814 Model = TLSModel::GeneralDynamic;
3818 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3820 const GlobalValue *GV = GA->getGlobal();
3822 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3824 if (Model == TLSModel::LocalExec) {
3825 SDValue HiVar = DAG.getTargetGlobalAddress(
3826 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3827 SDValue LoVar = DAG.getTargetGlobalAddress(
3829 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3831 SDValue TPWithOff_lo =
3832 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3834 DAG.getTargetConstant(0, DL, MVT::i32)),
3837 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3839 DAG.getTargetConstant(0, DL, MVT::i32)),
3842 } else if (Model == TLSModel::InitialExec) {
3843 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3844 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3845 } else if (Model == TLSModel::LocalDynamic) {
3846 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3847 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3848 // the beginning of the module's TLS region, followed by a DTPREL offset
3851 // These accesses will need deduplicating if there's more than one.
3852 AArch64FunctionInfo *MFI =
3853 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3854 MFI->incNumLocalDynamicTLSAccesses();
3856 // The call needs a relocation too for linker relaxation. It doesn't make
3857 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3859 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3862 // Now we can calculate the offset from TPIDR_EL0 to this module's
3863 // thread-local area.
3864 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3866 // Now use :dtprel_whatever: operations to calculate this variable's offset
3867 // in its thread-storage area.
3868 SDValue HiVar = DAG.getTargetGlobalAddress(
3869 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3870 SDValue LoVar = DAG.getTargetGlobalAddress(
3871 GV, DL, MVT::i64, 0,
3872 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3874 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3875 DAG.getTargetConstant(0, DL, MVT::i32)),
3877 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3878 DAG.getTargetConstant(0, DL, MVT::i32)),
3880 } else if (Model == TLSModel::GeneralDynamic) {
3881 // The call needs a relocation too for linker relaxation. It doesn't make
3882 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3885 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3887 // Finally we can make a call to calculate the offset from tpidr_el0.
3888 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3890 llvm_unreachable("Unsupported ELF TLS access model");
3892 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3895 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3896 SelectionDAG &DAG) const {
3897 if (Subtarget->isTargetDarwin())
3898 return LowerDarwinGlobalTLSAddress(Op, DAG);
3899 if (Subtarget->isTargetELF())
3900 return LowerELFGlobalTLSAddress(Op, DAG);
3902 llvm_unreachable("Unexpected platform trying to use TLS");
3905 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3906 SDValue Chain = Op.getOperand(0);
3907 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3908 SDValue LHS = Op.getOperand(2);
3909 SDValue RHS = Op.getOperand(3);
3910 SDValue Dest = Op.getOperand(4);
3913 // Handle f128 first, since lowering it will result in comparing the return
3914 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3915 // is expecting to deal with.
3916 if (LHS.getValueType() == MVT::f128) {
3917 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3919 // If softenSetCCOperands returned a scalar, we need to compare the result
3920 // against zero to select between true and false values.
3921 if (!RHS.getNode()) {
3922 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3927 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3929 unsigned Opc = LHS.getOpcode();
3930 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3931 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3932 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3933 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3934 "Unexpected condition code.");
3935 // Only lower legal XALUO ops.
3936 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3939 // The actual operation with overflow check.
3940 AArch64CC::CondCode OFCC;
3941 SDValue Value, Overflow;
3942 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3944 if (CC == ISD::SETNE)
3945 OFCC = getInvertedCondCode(OFCC);
3946 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3948 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3952 if (LHS.getValueType().isInteger()) {
3953 assert((LHS.getValueType() == RHS.getValueType()) &&
3954 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3956 // If the RHS of the comparison is zero, we can potentially fold this
3957 // to a specialized branch.
3958 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3959 if (RHSC && RHSC->getZExtValue() == 0) {
3960 if (CC == ISD::SETEQ) {
3961 // See if we can use a TBZ to fold in an AND as well.
3962 // TBZ has a smaller branch displacement than CBZ. If the offset is
3963 // out of bounds, a late MI-layer pass rewrites branches.
3964 // 403.gcc is an example that hits this case.
3965 if (LHS.getOpcode() == ISD::AND &&
3966 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3967 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3968 SDValue Test = LHS.getOperand(0);
3969 uint64_t Mask = LHS.getConstantOperandVal(1);
3970 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3971 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3975 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3976 } else if (CC == ISD::SETNE) {
3977 // See if we can use a TBZ to fold in an AND as well.
3978 // TBZ has a smaller branch displacement than CBZ. If the offset is
3979 // out of bounds, a late MI-layer pass rewrites branches.
3980 // 403.gcc is an example that hits this case.
3981 if (LHS.getOpcode() == ISD::AND &&
3982 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3983 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3984 SDValue Test = LHS.getOperand(0);
3985 uint64_t Mask = LHS.getConstantOperandVal(1);
3986 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3987 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3991 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3992 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3993 // Don't combine AND since emitComparison converts the AND to an ANDS
3994 // (a.k.a. TST) and the test in the test bit and branch instruction
3995 // becomes redundant. This would also increase register pressure.
3996 uint64_t Mask = LHS.getValueSizeInBits() - 1;
3997 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3998 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4001 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4002 LHS.getOpcode() != ISD::AND) {
4003 // Don't combine AND since emitComparison converts the AND to an ANDS
4004 // (a.k.a. TST) and the test in the test bit and branch instruction
4005 // becomes redundant. This would also increase register pressure.
4006 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4007 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4008 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4012 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4013 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4017 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4019 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4020 // clean. Some of them require two branches to implement.
4021 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4022 AArch64CC::CondCode CC1, CC2;
4023 changeFPCCToAArch64CC(CC, CC1, CC2);
4024 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4026 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4027 if (CC2 != AArch64CC::AL) {
4028 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4029 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4036 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4037 SelectionDAG &DAG) const {
4038 EVT VT = Op.getValueType();
4041 SDValue In1 = Op.getOperand(0);
4042 SDValue In2 = Op.getOperand(1);
4043 EVT SrcVT = In2.getValueType();
4045 if (SrcVT.bitsLT(VT))
4046 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4047 else if (SrcVT.bitsGT(VT))
4048 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4053 SDValue VecVal1, VecVal2;
4054 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4056 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4057 EltMask = 0x80000000ULL;
4059 if (!VT.isVector()) {
4060 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4061 DAG.getUNDEF(VecVT), In1);
4062 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4063 DAG.getUNDEF(VecVT), In2);
4065 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4066 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4068 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4072 // We want to materialize a mask with the high bit set, but the AdvSIMD
4073 // immediate moves cannot materialize that in a single instruction for
4074 // 64-bit elements. Instead, materialize zero and then negate it.
4077 if (!VT.isVector()) {
4078 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4079 DAG.getUNDEF(VecVT), In1);
4080 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4081 DAG.getUNDEF(VecVT), In2);
4083 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4084 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4087 llvm_unreachable("Invalid type for copysign!");
4090 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4092 // If we couldn't materialize the mask above, then the mask vector will be
4093 // the zero vector, and we need to negate it here.
4094 if (VT == MVT::f64 || VT == MVT::v2f64) {
4095 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4096 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4097 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4101 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4104 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4105 else if (VT == MVT::f64)
4106 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4108 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4111 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4112 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
4113 Attribute::NoImplicitFloat))
4116 if (!Subtarget->hasNEON())
4119 // While there is no integer popcount instruction, it can
4120 // be more efficiently lowered to the following sequence that uses
4121 // AdvSIMD registers/instructions as long as the copies to/from
4122 // the AdvSIMD registers are cheap.
4123 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4124 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4125 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4126 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4127 SDValue Val = Op.getOperand(0);
4129 EVT VT = Op.getValueType();
4132 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4133 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4135 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4136 SDValue UaddLV = DAG.getNode(
4137 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4138 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4141 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4145 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4147 if (Op.getValueType().isVector())
4148 return LowerVSETCC(Op, DAG);
4150 SDValue LHS = Op.getOperand(0);
4151 SDValue RHS = Op.getOperand(1);
4152 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4155 // We chose ZeroOrOneBooleanContents, so use zero and one.
4156 EVT VT = Op.getValueType();
4157 SDValue TVal = DAG.getConstant(1, dl, VT);
4158 SDValue FVal = DAG.getConstant(0, dl, VT);
4160 // Handle f128 first, since one possible outcome is a normal integer
4161 // comparison which gets picked up by the next if statement.
4162 if (LHS.getValueType() == MVT::f128) {
4163 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4165 // If softenSetCCOperands returned a scalar, use it.
4166 if (!RHS.getNode()) {
4167 assert(LHS.getValueType() == Op.getValueType() &&
4168 "Unexpected setcc expansion!");
4173 if (LHS.getValueType().isInteger()) {
4176 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4178 // Note that we inverted the condition above, so we reverse the order of
4179 // the true and false operands here. This will allow the setcc to be
4180 // matched to a single CSINC instruction.
4181 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4184 // Now we know we're dealing with FP values.
4185 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4187 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4188 // and do the comparison.
4189 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4191 AArch64CC::CondCode CC1, CC2;
4192 changeFPCCToAArch64CC(CC, CC1, CC2);
4193 if (CC2 == AArch64CC::AL) {
4194 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4195 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4197 // Note that we inverted the condition above, so we reverse the order of
4198 // the true and false operands here. This will allow the setcc to be
4199 // matched to a single CSINC instruction.
4200 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4202 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4203 // totally clean. Some of them require two CSELs to implement. As is in
4204 // this case, we emit the first CSEL and then emit a second using the output
4205 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4207 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4208 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4210 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4212 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4213 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4217 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4218 SDValue RHS, SDValue TVal,
4219 SDValue FVal, const SDLoc &dl,
4220 SelectionDAG &DAG) const {
4221 // Handle f128 first, because it will result in a comparison of some RTLIB
4222 // call result against zero.
4223 if (LHS.getValueType() == MVT::f128) {
4224 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4226 // If softenSetCCOperands returned a scalar, we need to compare the result
4227 // against zero to select between true and false values.
4228 if (!RHS.getNode()) {
4229 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4234 // Also handle f16, for which we need to do a f32 comparison.
4235 if (LHS.getValueType() == MVT::f16) {
4236 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4237 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4240 // Next, handle integers.
4241 if (LHS.getValueType().isInteger()) {
4242 assert((LHS.getValueType() == RHS.getValueType()) &&
4243 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4245 unsigned Opcode = AArch64ISD::CSEL;
4247 // If both the TVal and the FVal are constants, see if we can swap them in
4248 // order to for a CSINV or CSINC out of them.
4249 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4250 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4252 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4253 std::swap(TVal, FVal);
4254 std::swap(CTVal, CFVal);
4255 CC = ISD::getSetCCInverse(CC, true);
4256 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4257 std::swap(TVal, FVal);
4258 std::swap(CTVal, CFVal);
4259 CC = ISD::getSetCCInverse(CC, true);
4260 } else if (TVal.getOpcode() == ISD::XOR) {
4261 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4262 // with a CSINV rather than a CSEL.
4263 if (isAllOnesConstant(TVal.getOperand(1))) {
4264 std::swap(TVal, FVal);
4265 std::swap(CTVal, CFVal);
4266 CC = ISD::getSetCCInverse(CC, true);
4268 } else if (TVal.getOpcode() == ISD::SUB) {
4269 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4270 // that we can match with a CSNEG rather than a CSEL.
4271 if (isNullConstant(TVal.getOperand(0))) {
4272 std::swap(TVal, FVal);
4273 std::swap(CTVal, CFVal);
4274 CC = ISD::getSetCCInverse(CC, true);
4276 } else if (CTVal && CFVal) {
4277 const int64_t TrueVal = CTVal->getSExtValue();
4278 const int64_t FalseVal = CFVal->getSExtValue();
4281 // If both TVal and FVal are constants, see if FVal is the
4282 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4283 // instead of a CSEL in that case.
4284 if (TrueVal == ~FalseVal) {
4285 Opcode = AArch64ISD::CSINV;
4286 } else if (TrueVal == -FalseVal) {
4287 Opcode = AArch64ISD::CSNEG;
4288 } else if (TVal.getValueType() == MVT::i32) {
4289 // If our operands are only 32-bit wide, make sure we use 32-bit
4290 // arithmetic for the check whether we can use CSINC. This ensures that
4291 // the addition in the check will wrap around properly in case there is
4292 // an overflow (which would not be the case if we do the check with
4293 // 64-bit arithmetic).
4294 const uint32_t TrueVal32 = CTVal->getZExtValue();
4295 const uint32_t FalseVal32 = CFVal->getZExtValue();
4297 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4298 Opcode = AArch64ISD::CSINC;
4300 if (TrueVal32 > FalseVal32) {
4304 // 64-bit check whether we can use CSINC.
4305 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4306 Opcode = AArch64ISD::CSINC;
4308 if (TrueVal > FalseVal) {
4313 // Swap TVal and FVal if necessary.
4315 std::swap(TVal, FVal);
4316 std::swap(CTVal, CFVal);
4317 CC = ISD::getSetCCInverse(CC, true);
4320 if (Opcode != AArch64ISD::CSEL) {
4321 // Drop FVal since we can get its value by simply inverting/negating
4327 // Avoid materializing a constant when possible by reusing a known value in
4328 // a register. However, don't perform this optimization if the known value
4329 // is one, zero or negative one in the case of a CSEL. We can always
4330 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4331 // FVal, respectively.
4332 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4333 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4334 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4335 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4336 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4337 // "a != C ? x : a" to avoid materializing C.
4338 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4340 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4342 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4343 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4344 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4345 // avoid materializing C.
4346 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4347 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4348 Opcode = AArch64ISD::CSINV;
4350 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4355 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4357 EVT VT = TVal.getValueType();
4358 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4361 // Now we know we're dealing with FP values.
4362 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4363 assert(LHS.getValueType() == RHS.getValueType());
4364 EVT VT = TVal.getValueType();
4365 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4367 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4368 // clean. Some of them require two CSELs to implement.
4369 AArch64CC::CondCode CC1, CC2;
4370 changeFPCCToAArch64CC(CC, CC1, CC2);
4372 if (DAG.getTarget().Options.UnsafeFPMath) {
4373 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4374 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4375 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4376 if (RHSVal && RHSVal->isZero()) {
4377 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4378 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4380 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4381 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4383 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4384 CFVal && CFVal->isZero() &&
4385 FVal.getValueType() == LHS.getValueType())
4390 // Emit first, and possibly only, CSEL.
4391 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4392 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4394 // If we need a second CSEL, emit it, using the output of the first as the
4395 // RHS. We're effectively OR'ing the two CC's together.
4396 if (CC2 != AArch64CC::AL) {
4397 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4398 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4401 // Otherwise, return the output of the first CSEL.
4405 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4406 SelectionDAG &DAG) const {
4407 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4408 SDValue LHS = Op.getOperand(0);
4409 SDValue RHS = Op.getOperand(1);
4410 SDValue TVal = Op.getOperand(2);
4411 SDValue FVal = Op.getOperand(3);
4413 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4416 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4417 SelectionDAG &DAG) const {
4418 SDValue CCVal = Op->getOperand(0);
4419 SDValue TVal = Op->getOperand(1);
4420 SDValue FVal = Op->getOperand(2);
4423 unsigned Opc = CCVal.getOpcode();
4424 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4426 if (CCVal.getResNo() == 1 &&
4427 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4428 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4429 // Only lower legal XALUO ops.
4430 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4433 AArch64CC::CondCode OFCC;
4434 SDValue Value, Overflow;
4435 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4436 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4438 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4442 // Lower it the same way as we would lower a SELECT_CC node.
4445 if (CCVal.getOpcode() == ISD::SETCC) {
4446 LHS = CCVal.getOperand(0);
4447 RHS = CCVal.getOperand(1);
4448 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4451 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4454 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4457 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4458 SelectionDAG &DAG) const {
4459 // Jump table entries as PC relative offsets. No additional tweaking
4460 // is necessary here. Just get the address of the jump table.
4461 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4463 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4464 !Subtarget->isTargetMachO()) {
4465 return getAddrLarge(JT, DAG);
4467 return getAddr(JT, DAG);
4470 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4471 SelectionDAG &DAG) const {
4472 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4474 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4475 // Use the GOT for the large code model on iOS.
4476 if (Subtarget->isTargetMachO()) {
4477 return getGOT(CP, DAG);
4479 return getAddrLarge(CP, DAG);
4481 return getAddr(CP, DAG);
4485 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4486 SelectionDAG &DAG) const {
4487 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4488 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4489 !Subtarget->isTargetMachO()) {
4490 return getAddrLarge(BA, DAG);
4492 return getAddr(BA, DAG);
4496 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4497 SelectionDAG &DAG) const {
4498 AArch64FunctionInfo *FuncInfo =
4499 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4502 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4503 getPointerTy(DAG.getDataLayout()));
4504 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4505 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4506 MachinePointerInfo(SV));
4509 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4510 SelectionDAG &DAG) const {
4511 AArch64FunctionInfo *FuncInfo =
4512 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4515 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4516 ? FuncInfo->getVarArgsGPRIndex()
4517 : FuncInfo->getVarArgsStackIndex(),
4518 getPointerTy(DAG.getDataLayout()));
4519 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4520 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4521 MachinePointerInfo(SV));
4524 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4525 SelectionDAG &DAG) const {
4526 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4527 // Standard, section B.3.
4528 MachineFunction &MF = DAG.getMachineFunction();
4529 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4530 auto PtrVT = getPointerTy(DAG.getDataLayout());
4533 SDValue Chain = Op.getOperand(0);
4534 SDValue VAList = Op.getOperand(1);
4535 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4536 SmallVector<SDValue, 4> MemOps;
4538 // void *__stack at offset 0
4539 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4540 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4541 MachinePointerInfo(SV), /* Alignment = */ 8));
4543 // void *__gr_top at offset 8
4544 int GPRSize = FuncInfo->getVarArgsGPRSize();
4546 SDValue GRTop, GRTopAddr;
4549 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4551 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4552 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4553 DAG.getConstant(GPRSize, DL, PtrVT));
4555 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4556 MachinePointerInfo(SV, 8),
4557 /* Alignment = */ 8));
4560 // void *__vr_top at offset 16
4561 int FPRSize = FuncInfo->getVarArgsFPRSize();
4563 SDValue VRTop, VRTopAddr;
4564 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4565 DAG.getConstant(16, DL, PtrVT));
4567 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4568 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4569 DAG.getConstant(FPRSize, DL, PtrVT));
4571 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4572 MachinePointerInfo(SV, 16),
4573 /* Alignment = */ 8));
4576 // int __gr_offs at offset 24
4577 SDValue GROffsAddr =
4578 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4579 MemOps.push_back(DAG.getStore(
4580 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4581 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4583 // int __vr_offs at offset 28
4584 SDValue VROffsAddr =
4585 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4586 MemOps.push_back(DAG.getStore(
4587 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4588 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4590 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4593 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4594 SelectionDAG &DAG) const {
4595 MachineFunction &MF = DAG.getMachineFunction();
4597 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
4598 return LowerWin64_VASTART(Op, DAG);
4599 else if (Subtarget->isTargetDarwin())
4600 return LowerDarwin_VASTART(Op, DAG);
4602 return LowerAAPCS_VASTART(Op, DAG);
4605 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4606 SelectionDAG &DAG) const {
4607 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4610 unsigned VaListSize =
4611 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
4612 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4613 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4615 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4617 DAG.getConstant(VaListSize, DL, MVT::i32),
4618 8, false, false, false, MachinePointerInfo(DestSV),
4619 MachinePointerInfo(SrcSV));
4622 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4623 assert(Subtarget->isTargetDarwin() &&
4624 "automatic va_arg instruction only works on Darwin");
4626 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4627 EVT VT = Op.getValueType();
4629 SDValue Chain = Op.getOperand(0);
4630 SDValue Addr = Op.getOperand(1);
4631 unsigned Align = Op.getConstantOperandVal(3);
4632 auto PtrVT = getPointerTy(DAG.getDataLayout());
4634 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4635 Chain = VAList.getValue(1);
4638 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4639 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4640 DAG.getConstant(Align - 1, DL, PtrVT));
4641 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4642 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4645 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4646 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4648 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4649 // up to 64 bits. At the very least, we have to increase the striding of the
4650 // vaargs list to match this, and for FP values we need to introduce
4651 // FP_ROUND nodes as well.
4652 if (VT.isInteger() && !VT.isVector())
4654 bool NeedFPTrunc = false;
4655 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4660 // Increment the pointer, VAList, to the next vaarg
4661 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4662 DAG.getConstant(ArgSize, DL, PtrVT));
4663 // Store the incremented VAList to the legalized pointer
4665 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4667 // Load the actual argument out of the pointer VAList
4669 // Load the value as an f64.
4671 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4672 // Round the value down to an f32.
4673 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4674 DAG.getIntPtrConstant(1, DL));
4675 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4676 // Merge the rounded value with the chain output of the load.
4677 return DAG.getMergeValues(Ops, DL);
4680 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4683 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4684 SelectionDAG &DAG) const {
4685 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4686 MFI.setFrameAddressIsTaken(true);
4688 EVT VT = Op.getValueType();
4690 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4692 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4694 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4695 MachinePointerInfo());
4699 // FIXME? Maybe this could be a TableGen attribute on some registers and
4700 // this table could be generated automatically from RegInfo.
4701 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4702 SelectionDAG &DAG) const {
4703 unsigned Reg = StringSwitch<unsigned>(RegName)
4704 .Case("sp", AArch64::SP)
4705 .Case("x18", AArch64::X18)
4706 .Case("w18", AArch64::W18)
4708 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4709 !Subtarget->isX18Reserved())
4713 report_fatal_error(Twine("Invalid register name \""
4714 + StringRef(RegName) + "\"."));
4717 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4718 SelectionDAG &DAG) const {
4719 MachineFunction &MF = DAG.getMachineFunction();
4720 MachineFrameInfo &MFI = MF.getFrameInfo();
4721 MFI.setReturnAddressIsTaken(true);
4723 EVT VT = Op.getValueType();
4725 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4727 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4728 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4729 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4730 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4731 MachinePointerInfo());
4734 // Return LR, which contains the return address. Mark it an implicit live-in.
4735 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4736 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4739 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4740 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4741 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4742 SelectionDAG &DAG) const {
4743 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4744 EVT VT = Op.getValueType();
4745 unsigned VTBits = VT.getSizeInBits();
4747 SDValue ShOpLo = Op.getOperand(0);
4748 SDValue ShOpHi = Op.getOperand(1);
4749 SDValue ShAmt = Op.getOperand(2);
4750 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4752 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4754 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4755 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4756 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4758 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4759 // is "undef". We wanted 0, so CSEL it directly.
4760 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4761 ISD::SETEQ, dl, DAG);
4762 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4764 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4765 HiBitsForLo, CCVal, Cmp);
4767 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4768 DAG.getConstant(VTBits, dl, MVT::i64));
4770 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4771 SDValue LoForNormalShift =
4772 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4774 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4776 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4777 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4778 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4779 LoForNormalShift, CCVal, Cmp);
4781 // AArch64 shifts larger than the register width are wrapped rather than
4782 // clamped, so we can't just emit "hi >> x".
4783 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4784 SDValue HiForBigShift =
4786 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4787 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4788 : DAG.getConstant(0, dl, VT);
4789 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4790 HiForNormalShift, CCVal, Cmp);
4792 SDValue Ops[2] = { Lo, Hi };
4793 return DAG.getMergeValues(Ops, dl);
4796 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4797 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4798 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4799 SelectionDAG &DAG) const {
4800 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4801 EVT VT = Op.getValueType();
4802 unsigned VTBits = VT.getSizeInBits();
4804 SDValue ShOpLo = Op.getOperand(0);
4805 SDValue ShOpHi = Op.getOperand(1);
4806 SDValue ShAmt = Op.getOperand(2);
4808 assert(Op.getOpcode() == ISD::SHL_PARTS);
4809 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4810 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4811 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4813 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4814 // is "undef". We wanted 0, so CSEL it directly.
4815 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4816 ISD::SETEQ, dl, DAG);
4817 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4819 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4820 LoBitsForHi, CCVal, Cmp);
4822 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4823 DAG.getConstant(VTBits, dl, MVT::i64));
4824 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4825 SDValue HiForNormalShift =
4826 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4828 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4830 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4832 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4833 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4834 HiForNormalShift, CCVal, Cmp);
4836 // AArch64 shifts of larger than register sizes are wrapped rather than
4837 // clamped, so we can't just emit "lo << a" if a is too big.
4838 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4839 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4840 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4841 LoForNormalShift, CCVal, Cmp);
4843 SDValue Ops[2] = { Lo, Hi };
4844 return DAG.getMergeValues(Ops, dl);
4847 bool AArch64TargetLowering::isOffsetFoldingLegal(
4848 const GlobalAddressSDNode *GA) const {
4849 // The AArch64 target doesn't support folding offsets into global addresses.
4853 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4854 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4855 // FIXME: We should be able to handle f128 as well with a clever lowering.
4856 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4860 return AArch64_AM::getFP64Imm(Imm) != -1;
4861 else if (VT == MVT::f32)
4862 return AArch64_AM::getFP32Imm(Imm) != -1;
4866 //===----------------------------------------------------------------------===//
4867 // AArch64 Optimization Hooks
4868 //===----------------------------------------------------------------------===//
4870 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4871 SDValue Operand, SelectionDAG &DAG,
4873 EVT VT = Operand.getValueType();
4874 if (ST->hasNEON() &&
4875 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4876 VT == MVT::f32 || VT == MVT::v1f32 ||
4877 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4878 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4879 // For the reciprocal estimates, convergence is quadratic, so the number
4880 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4881 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4882 // the result for float (23 mantissa bits) is 2 and for double (52
4883 // mantissa bits) is 3.
4884 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4886 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4892 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4893 SelectionDAG &DAG, int Enabled,
4896 bool Reciprocal) const {
4897 if (Enabled == ReciprocalEstimate::Enabled ||
4898 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4899 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4902 EVT VT = Operand.getValueType();
4905 Flags.setUnsafeAlgebra(true);
4907 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4908 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4909 for (int i = ExtraSteps; i > 0; --i) {
4910 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4912 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
4913 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4917 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4919 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4920 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4922 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
4923 // Correct the result if the operand is 0.0.
4924 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4925 VT, Eq, Operand, Estimate);
4935 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4936 SelectionDAG &DAG, int Enabled,
4937 int &ExtraSteps) const {
4938 if (Enabled == ReciprocalEstimate::Enabled)
4939 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4942 EVT VT = Operand.getValueType();
4945 Flags.setUnsafeAlgebra(true);
4947 // Newton reciprocal iteration: E * (2 - X * E)
4948 // AArch64 reciprocal iteration instruction: (2 - M * N)
4949 for (int i = ExtraSteps; i > 0; --i) {
4950 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4952 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4962 //===----------------------------------------------------------------------===//
4963 // AArch64 Inline Assembly Support
4964 //===----------------------------------------------------------------------===//
4966 // Table of Constraints
4967 // TODO: This is the current set of constraints supported by ARM for the
4968 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4970 // r - A general register
4971 // w - An FP/SIMD register of some size in the range v0-v31
4972 // x - An FP/SIMD register of some size in the range v0-v15
4973 // I - Constant that can be used with an ADD instruction
4974 // J - Constant that can be used with a SUB instruction
4975 // K - Constant that can be used with a 32-bit logical instruction
4976 // L - Constant that can be used with a 64-bit logical instruction
4977 // M - Constant that can be used as a 32-bit MOV immediate
4978 // N - Constant that can be used as a 64-bit MOV immediate
4979 // Q - A memory reference with base register and no offset
4980 // S - A symbolic address
4981 // Y - Floating point constant zero
4982 // Z - Integer constant zero
4984 // Note that general register operands will be output using their 64-bit x
4985 // register name, whatever the size of the variable, unless the asm operand
4986 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4987 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4989 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4990 // At this point, we have to lower this constraint to something else, so we
4991 // lower it to an "r" or "w". However, by doing this we will force the result
4992 // to be in register, while the X constraint is much more permissive.
4994 // Although we are correct (we are free to emit anything, without
4995 // constraints), we might break use cases that would expect us to be more
4996 // efficient and emit something else.
4997 if (!Subtarget->hasFPARMv8())
5000 if (ConstraintVT.isFloatingPoint())
5003 if (ConstraintVT.isVector() &&
5004 (ConstraintVT.getSizeInBits() == 64 ||
5005 ConstraintVT.getSizeInBits() == 128))
5011 /// getConstraintType - Given a constraint letter, return the type of
5012 /// constraint it is for this target.
5013 AArch64TargetLowering::ConstraintType
5014 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5015 if (Constraint.size() == 1) {
5016 switch (Constraint[0]) {
5023 return C_RegisterClass;
5024 // An address with a single base register. Due to the way we
5025 // currently handle addresses it is the same as 'r'.
5030 return TargetLowering::getConstraintType(Constraint);
5033 /// Examine constraint type and operand type and determine a weight value.
5034 /// This object must already have been set up with the operand type
5035 /// and the current alternative constraint selected.
5036 TargetLowering::ConstraintWeight
5037 AArch64TargetLowering::getSingleConstraintMatchWeight(
5038 AsmOperandInfo &info, const char *constraint) const {
5039 ConstraintWeight weight = CW_Invalid;
5040 Value *CallOperandVal = info.CallOperandVal;
5041 // If we don't have a value, we can't do a match,
5042 // but allow it at the lowest weight.
5043 if (!CallOperandVal)
5045 Type *type = CallOperandVal->getType();
5046 // Look at the constraint type.
5047 switch (*constraint) {
5049 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5053 if (type->isFloatingPointTy() || type->isVectorTy())
5054 weight = CW_Register;
5057 weight = CW_Constant;
5063 std::pair<unsigned, const TargetRegisterClass *>
5064 AArch64TargetLowering::getRegForInlineAsmConstraint(
5065 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5066 if (Constraint.size() == 1) {
5067 switch (Constraint[0]) {
5069 if (VT.getSizeInBits() == 64)
5070 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5071 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5073 if (VT.getSizeInBits() == 16)
5074 return std::make_pair(0U, &AArch64::FPR16RegClass);
5075 if (VT.getSizeInBits() == 32)
5076 return std::make_pair(0U, &AArch64::FPR32RegClass);
5077 if (VT.getSizeInBits() == 64)
5078 return std::make_pair(0U, &AArch64::FPR64RegClass);
5079 if (VT.getSizeInBits() == 128)
5080 return std::make_pair(0U, &AArch64::FPR128RegClass);
5082 // The instructions that this constraint is designed for can
5083 // only take 128-bit registers so just use that regclass.
5085 if (VT.getSizeInBits() == 128)
5086 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5090 if (StringRef("{cc}").equals_lower(Constraint))
5091 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5093 // Use the default implementation in TargetLowering to convert the register
5094 // constraint into a member of a register class.
5095 std::pair<unsigned, const TargetRegisterClass *> Res;
5096 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5098 // Not found as a standard register?
5100 unsigned Size = Constraint.size();
5101 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5102 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5104 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5105 if (!Failed && RegNo >= 0 && RegNo <= 31) {
5106 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5107 // By default we'll emit v0-v31 for this unless there's a modifier where
5108 // we'll emit the correct register as well.
5109 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5110 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5111 Res.second = &AArch64::FPR64RegClass;
5113 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5114 Res.second = &AArch64::FPR128RegClass;
5123 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5124 /// vector. If it is invalid, don't add anything to Ops.
5125 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5126 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5127 SelectionDAG &DAG) const {
5130 // Currently only support length 1 constraints.
5131 if (Constraint.length() != 1)
5134 char ConstraintLetter = Constraint[0];
5135 switch (ConstraintLetter) {
5139 // This set of constraints deal with valid constants for various instructions.
5140 // Validate and return a target constant for them if we can.
5142 // 'z' maps to xzr or wzr so it needs an input of 0.
5143 if (!isNullConstant(Op))
5146 if (Op.getValueType() == MVT::i64)
5147 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5149 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5159 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5163 // Grab the value and do some validation.
5164 uint64_t CVal = C->getZExtValue();
5165 switch (ConstraintLetter) {
5166 // The I constraint applies only to simple ADD or SUB immediate operands:
5167 // i.e. 0 to 4095 with optional shift by 12
5168 // The J constraint applies only to ADD or SUB immediates that would be
5169 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5170 // instruction [or vice versa], in other words -1 to -4095 with optional
5171 // left shift by 12.
5173 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5177 uint64_t NVal = -C->getSExtValue();
5178 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5179 CVal = C->getSExtValue();
5184 // The K and L constraints apply *only* to logical immediates, including
5185 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5186 // been removed and MOV should be used). So these constraints have to
5187 // distinguish between bit patterns that are valid 32-bit or 64-bit
5188 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5189 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5192 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5196 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5199 // The M and N constraints are a superset of K and L respectively, for use
5200 // with the MOV (immediate) alias. As well as the logical immediates they
5201 // also match 32 or 64-bit immediates that can be loaded either using a
5202 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5203 // (M) or 64-bit 0x1234000000000000 (N) etc.
5204 // As a note some of this code is liberally stolen from the asm parser.
5206 if (!isUInt<32>(CVal))
5208 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5210 if ((CVal & 0xFFFF) == CVal)
5212 if ((CVal & 0xFFFF0000ULL) == CVal)
5214 uint64_t NCVal = ~(uint32_t)CVal;
5215 if ((NCVal & 0xFFFFULL) == NCVal)
5217 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5222 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5224 if ((CVal & 0xFFFFULL) == CVal)
5226 if ((CVal & 0xFFFF0000ULL) == CVal)
5228 if ((CVal & 0xFFFF00000000ULL) == CVal)
5230 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5232 uint64_t NCVal = ~CVal;
5233 if ((NCVal & 0xFFFFULL) == NCVal)
5235 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5237 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5239 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5247 // All assembler immediates are 64-bit integers.
5248 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5252 if (Result.getNode()) {
5253 Ops.push_back(Result);
5257 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5260 //===----------------------------------------------------------------------===//
5261 // AArch64 Advanced SIMD Support
5262 //===----------------------------------------------------------------------===//
5264 /// WidenVector - Given a value in the V64 register class, produce the
5265 /// equivalent value in the V128 register class.
5266 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5267 EVT VT = V64Reg.getValueType();
5268 unsigned NarrowSize = VT.getVectorNumElements();
5269 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5270 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5273 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5274 V64Reg, DAG.getConstant(0, DL, MVT::i32));
5277 /// getExtFactor - Determine the adjustment factor for the position when
5278 /// generating an "extract from vector registers" instruction.
5279 static unsigned getExtFactor(SDValue &V) {
5280 EVT EltType = V.getValueType().getVectorElementType();
5281 return EltType.getSizeInBits() / 8;
5284 /// NarrowVector - Given a value in the V128 register class, produce the
5285 /// equivalent value in the V64 register class.
5286 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5287 EVT VT = V128Reg.getValueType();
5288 unsigned WideSize = VT.getVectorNumElements();
5289 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5290 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5293 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5296 // Gather data to see if the operation can be modelled as a
5297 // shuffle in combination with VEXTs.
5298 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5299 SelectionDAG &DAG) const {
5300 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5302 EVT VT = Op.getValueType();
5303 unsigned NumElts = VT.getVectorNumElements();
5305 struct ShuffleSourceInfo {
5310 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5311 // be compatible with the shuffle we intend to construct. As a result
5312 // ShuffleVec will be some sliding window into the original Vec.
5315 // Code should guarantee that element i in Vec starts at element "WindowBase
5316 // + i * WindowScale in ShuffleVec".
5320 ShuffleSourceInfo(SDValue Vec)
5321 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5322 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5324 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5327 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5329 SmallVector<ShuffleSourceInfo, 2> Sources;
5330 for (unsigned i = 0; i < NumElts; ++i) {
5331 SDValue V = Op.getOperand(i);
5334 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5335 !isa<ConstantSDNode>(V.getOperand(1))) {
5336 // A shuffle can only come from building a vector from various
5337 // elements of other vectors, provided their indices are constant.
5341 // Add this element source to the list if it's not already there.
5342 SDValue SourceVec = V.getOperand(0);
5343 auto Source = find(Sources, SourceVec);
5344 if (Source == Sources.end())
5345 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5347 // Update the minimum and maximum lane number seen.
5348 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5349 Source->MinElt = std::min(Source->MinElt, EltNo);
5350 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5353 // Currently only do something sane when at most two source vectors
5355 if (Sources.size() > 2)
5358 // Find out the smallest element size among result and two sources, and use
5359 // it as element size to build the shuffle_vector.
5360 EVT SmallestEltTy = VT.getVectorElementType();
5361 for (auto &Source : Sources) {
5362 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5363 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5364 SmallestEltTy = SrcEltTy;
5367 unsigned ResMultiplier =
5368 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5369 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5370 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5372 // If the source vector is too wide or too narrow, we may nevertheless be able
5373 // to construct a compatible shuffle either by concatenating it with UNDEF or
5374 // extracting a suitable range of elements.
5375 for (auto &Src : Sources) {
5376 EVT SrcVT = Src.ShuffleVec.getValueType();
5378 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5381 // This stage of the search produces a source with the same element type as
5382 // the original, but with a total width matching the BUILD_VECTOR output.
5383 EVT EltVT = SrcVT.getVectorElementType();
5384 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5385 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5387 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5388 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5389 // We can pad out the smaller vector for free, so if it's part of a
5392 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5393 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5397 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5399 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5400 // Span too large for a VEXT to cope
5404 if (Src.MinElt >= NumSrcElts) {
5405 // The extraction can just take the second half
5407 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5408 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5409 Src.WindowBase = -NumSrcElts;
5410 } else if (Src.MaxElt < NumSrcElts) {
5411 // The extraction can just take the first half
5413 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5414 DAG.getConstant(0, dl, MVT::i64));
5416 // An actual VEXT is needed
5418 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5419 DAG.getConstant(0, dl, MVT::i64));
5421 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5422 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5423 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5425 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5427 DAG.getConstant(Imm, dl, MVT::i32));
5428 Src.WindowBase = -Src.MinElt;
5432 // Another possible incompatibility occurs from the vector element types. We
5433 // can fix this by bitcasting the source vectors to the same type we intend
5435 for (auto &Src : Sources) {
5436 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5437 if (SrcEltTy == SmallestEltTy)
5439 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5440 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5441 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5442 Src.WindowBase *= Src.WindowScale;
5445 // Final sanity check before we try to actually produce a shuffle.
5447 for (auto Src : Sources)
5448 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5451 // The stars all align, our next step is to produce the mask for the shuffle.
5452 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5453 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5454 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5455 SDValue Entry = Op.getOperand(i);
5456 if (Entry.isUndef())
5459 auto Src = find(Sources, Entry.getOperand(0));
5460 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5462 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5463 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5465 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5467 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5468 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5470 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5471 // starting at the appropriate offset.
5472 int *LaneMask = &Mask[i * ResMultiplier];
5474 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5475 ExtractBase += NumElts * (Src - Sources.begin());
5476 for (int j = 0; j < LanesDefined; ++j)
5477 LaneMask[j] = ExtractBase + j;
5480 // Final check before we try to produce nonsense...
5481 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5484 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5485 for (unsigned i = 0; i < Sources.size(); ++i)
5486 ShuffleOps[i] = Sources[i].ShuffleVec;
5488 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5489 ShuffleOps[1], Mask);
5490 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5493 // check if an EXT instruction can handle the shuffle mask when the
5494 // vector sources of the shuffle are the same.
5495 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5496 unsigned NumElts = VT.getVectorNumElements();
5498 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5504 // If this is a VEXT shuffle, the immediate value is the index of the first
5505 // element. The other shuffle indices must be the successive elements after
5507 unsigned ExpectedElt = Imm;
5508 for (unsigned i = 1; i < NumElts; ++i) {
5509 // Increment the expected index. If it wraps around, just follow it
5510 // back to index zero and keep going.
5512 if (ExpectedElt == NumElts)
5516 continue; // ignore UNDEF indices
5517 if (ExpectedElt != static_cast<unsigned>(M[i]))
5524 // check if an EXT instruction can handle the shuffle mask when the
5525 // vector sources of the shuffle are different.
5526 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5528 // Look for the first non-undef element.
5529 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5531 // Benefit form APInt to handle overflow when calculating expected element.
5532 unsigned NumElts = VT.getVectorNumElements();
5533 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5534 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5535 // The following shuffle indices must be the successive elements after the
5536 // first real element.
5537 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5538 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5539 if (FirstWrongElt != M.end())
5542 // The index of an EXT is the first element if it is not UNDEF.
5543 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5544 // value of the first element. E.g.
5545 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5546 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5547 // ExpectedElt is the last mask index plus 1.
5548 Imm = ExpectedElt.getZExtValue();
5550 // There are two difference cases requiring to reverse input vectors.
5551 // For example, for vector <4 x i32> we have the following cases,
5552 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5553 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5554 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5555 // to reverse two input vectors.
5564 /// isREVMask - Check if a vector shuffle corresponds to a REV
5565 /// instruction with the specified blocksize. (The order of the elements
5566 /// within each block of the vector is reversed.)
5567 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5568 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5569 "Only possible block sizes for REV are: 16, 32, 64");
5571 unsigned EltSz = VT.getScalarSizeInBits();
5575 unsigned NumElts = VT.getVectorNumElements();
5576 unsigned BlockElts = M[0] + 1;
5577 // If the first shuffle index is UNDEF, be optimistic.
5579 BlockElts = BlockSize / EltSz;
5581 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5584 for (unsigned i = 0; i < NumElts; ++i) {
5586 continue; // ignore UNDEF indices
5587 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5594 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5595 unsigned NumElts = VT.getVectorNumElements();
5596 WhichResult = (M[0] == 0 ? 0 : 1);
5597 unsigned Idx = WhichResult * NumElts / 2;
5598 for (unsigned i = 0; i != NumElts; i += 2) {
5599 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5600 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5608 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5609 unsigned NumElts = VT.getVectorNumElements();
5610 WhichResult = (M[0] == 0 ? 0 : 1);
5611 for (unsigned i = 0; i != NumElts; ++i) {
5613 continue; // ignore UNDEF indices
5614 if ((unsigned)M[i] != 2 * i + WhichResult)
5621 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5622 unsigned NumElts = VT.getVectorNumElements();
5623 WhichResult = (M[0] == 0 ? 0 : 1);
5624 for (unsigned i = 0; i < NumElts; i += 2) {
5625 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5626 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5632 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5633 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5634 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5635 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5636 unsigned NumElts = VT.getVectorNumElements();
5637 WhichResult = (M[0] == 0 ? 0 : 1);
5638 unsigned Idx = WhichResult * NumElts / 2;
5639 for (unsigned i = 0; i != NumElts; i += 2) {
5640 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5641 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5649 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5650 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5651 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5652 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5653 unsigned Half = VT.getVectorNumElements() / 2;
5654 WhichResult = (M[0] == 0 ? 0 : 1);
5655 for (unsigned j = 0; j != 2; ++j) {
5656 unsigned Idx = WhichResult;
5657 for (unsigned i = 0; i != Half; ++i) {
5658 int MIdx = M[i + j * Half];
5659 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5668 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5669 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5670 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5671 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5672 unsigned NumElts = VT.getVectorNumElements();
5673 WhichResult = (M[0] == 0 ? 0 : 1);
5674 for (unsigned i = 0; i < NumElts; i += 2) {
5675 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5676 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5682 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5683 bool &DstIsLeft, int &Anomaly) {
5684 if (M.size() != static_cast<size_t>(NumInputElements))
5687 int NumLHSMatch = 0, NumRHSMatch = 0;
5688 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5690 for (int i = 0; i < NumInputElements; ++i) {
5700 LastLHSMismatch = i;
5702 if (M[i] == i + NumInputElements)
5705 LastRHSMismatch = i;
5708 if (NumLHSMatch == NumInputElements - 1) {
5710 Anomaly = LastLHSMismatch;
5712 } else if (NumRHSMatch == NumInputElements - 1) {
5714 Anomaly = LastRHSMismatch;
5721 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5722 if (VT.getSizeInBits() != 128)
5725 unsigned NumElts = VT.getVectorNumElements();
5727 for (int I = 0, E = NumElts / 2; I != E; I++) {
5732 int Offset = NumElts / 2;
5733 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5734 if (Mask[I] != I + SplitLHS * Offset)
5741 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5743 EVT VT = Op.getValueType();
5744 SDValue V0 = Op.getOperand(0);
5745 SDValue V1 = Op.getOperand(1);
5746 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5748 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5749 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5752 bool SplitV0 = V0.getValueSizeInBits() == 128;
5754 if (!isConcatMask(Mask, VT, SplitV0))
5757 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5758 VT.getVectorNumElements() / 2);
5760 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5761 DAG.getConstant(0, DL, MVT::i64));
5763 if (V1.getValueSizeInBits() == 128) {
5764 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5765 DAG.getConstant(0, DL, MVT::i64));
5767 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5770 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5771 /// the specified operations to build the shuffle.
5772 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5773 SDValue RHS, SelectionDAG &DAG,
5775 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5776 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5777 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5780 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5789 OP_VUZPL, // VUZP, left result
5790 OP_VUZPR, // VUZP, right result
5791 OP_VZIPL, // VZIP, left result
5792 OP_VZIPR, // VZIP, right result
5793 OP_VTRNL, // VTRN, left result
5794 OP_VTRNR // VTRN, right result
5797 if (OpNum == OP_COPY) {
5798 if (LHSID == (1 * 9 + 2) * 9 + 3)
5800 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5804 SDValue OpLHS, OpRHS;
5805 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5806 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5807 EVT VT = OpLHS.getValueType();
5811 llvm_unreachable("Unknown shuffle opcode!");
5813 // VREV divides the vector in half and swaps within the half.
5814 if (VT.getVectorElementType() == MVT::i32 ||
5815 VT.getVectorElementType() == MVT::f32)
5816 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5817 // vrev <4 x i16> -> REV32
5818 if (VT.getVectorElementType() == MVT::i16 ||
5819 VT.getVectorElementType() == MVT::f16)
5820 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5821 // vrev <4 x i8> -> REV16
5822 assert(VT.getVectorElementType() == MVT::i8);
5823 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5828 EVT EltTy = VT.getVectorElementType();
5830 if (EltTy == MVT::i8)
5831 Opcode = AArch64ISD::DUPLANE8;
5832 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5833 Opcode = AArch64ISD::DUPLANE16;
5834 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5835 Opcode = AArch64ISD::DUPLANE32;
5836 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5837 Opcode = AArch64ISD::DUPLANE64;
5839 llvm_unreachable("Invalid vector element type?");
5841 if (VT.getSizeInBits() == 64)
5842 OpLHS = WidenVector(OpLHS, DAG);
5843 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5844 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5849 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5850 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5851 DAG.getConstant(Imm, dl, MVT::i32));
5854 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5857 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5860 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5863 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5866 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5869 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5874 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5875 SelectionDAG &DAG) {
5876 // Check to see if we can use the TBL instruction.
5877 SDValue V1 = Op.getOperand(0);
5878 SDValue V2 = Op.getOperand(1);
5881 EVT EltVT = Op.getValueType().getVectorElementType();
5882 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5884 SmallVector<SDValue, 8> TBLMask;
5885 for (int Val : ShuffleMask) {
5886 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5887 unsigned Offset = Byte + Val * BytesPerElt;
5888 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5892 MVT IndexVT = MVT::v8i8;
5893 unsigned IndexLen = 8;
5894 if (Op.getValueSizeInBits() == 128) {
5895 IndexVT = MVT::v16i8;
5899 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5900 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5903 if (V2.getNode()->isUndef()) {
5905 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5906 Shuffle = DAG.getNode(
5907 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5908 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5909 DAG.getBuildVector(IndexVT, DL,
5910 makeArrayRef(TBLMask.data(), IndexLen)));
5912 if (IndexLen == 8) {
5913 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5914 Shuffle = DAG.getNode(
5915 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5916 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5917 DAG.getBuildVector(IndexVT, DL,
5918 makeArrayRef(TBLMask.data(), IndexLen)));
5920 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5921 // cannot currently represent the register constraints on the input
5923 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5924 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5926 Shuffle = DAG.getNode(
5927 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5928 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5929 V2Cst, DAG.getBuildVector(IndexVT, DL,
5930 makeArrayRef(TBLMask.data(), IndexLen)));
5933 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5936 static unsigned getDUPLANEOp(EVT EltType) {
5937 if (EltType == MVT::i8)
5938 return AArch64ISD::DUPLANE8;
5939 if (EltType == MVT::i16 || EltType == MVT::f16)
5940 return AArch64ISD::DUPLANE16;
5941 if (EltType == MVT::i32 || EltType == MVT::f32)
5942 return AArch64ISD::DUPLANE32;
5943 if (EltType == MVT::i64 || EltType == MVT::f64)
5944 return AArch64ISD::DUPLANE64;
5946 llvm_unreachable("Invalid vector element type?");
5949 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5950 SelectionDAG &DAG) const {
5952 EVT VT = Op.getValueType();
5954 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5956 // Convert shuffles that are directly supported on NEON to target-specific
5957 // DAG nodes, instead of keeping them as shuffles and matching them again
5958 // during code selection. This is more efficient and avoids the possibility
5959 // of inconsistencies between legalization and selection.
5960 ArrayRef<int> ShuffleMask = SVN->getMask();
5962 SDValue V1 = Op.getOperand(0);
5963 SDValue V2 = Op.getOperand(1);
5965 if (SVN->isSplat()) {
5966 int Lane = SVN->getSplatIndex();
5967 // If this is undef splat, generate it via "just" vdup, if possible.
5971 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5972 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5974 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5975 // constant. If so, we can just reference the lane's definition directly.
5976 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5977 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5978 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5980 // Otherwise, duplicate from the lane of the input vector.
5981 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5983 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5984 // to make a vector of the same size as this SHUFFLE. We can ignore the
5985 // extract entirely, and canonicalise the concat using WidenVector.
5986 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5987 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5988 V1 = V1.getOperand(0);
5989 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5990 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5991 Lane -= Idx * VT.getVectorNumElements() / 2;
5992 V1 = WidenVector(V1.getOperand(Idx), DAG);
5993 } else if (VT.getSizeInBits() == 64)
5994 V1 = WidenVector(V1, DAG);
5996 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5999 if (isREVMask(ShuffleMask, VT, 64))
6000 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6001 if (isREVMask(ShuffleMask, VT, 32))
6002 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6003 if (isREVMask(ShuffleMask, VT, 16))
6004 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6006 bool ReverseEXT = false;
6008 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6011 Imm *= getExtFactor(V1);
6012 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6013 DAG.getConstant(Imm, dl, MVT::i32));
6014 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6015 Imm *= getExtFactor(V1);
6016 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6017 DAG.getConstant(Imm, dl, MVT::i32));
6020 unsigned WhichResult;
6021 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6022 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6023 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6025 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6026 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6027 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6029 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6030 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6031 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6034 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6035 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6036 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6038 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6039 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6040 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6042 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6043 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6044 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6047 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6052 int NumInputElements = V1.getValueType().getVectorNumElements();
6053 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6054 SDValue DstVec = DstIsLeft ? V1 : V2;
6055 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6057 SDValue SrcVec = V1;
6058 int SrcLane = ShuffleMask[Anomaly];
6059 if (SrcLane >= NumInputElements) {
6061 SrcLane -= VT.getVectorNumElements();
6063 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6065 EVT ScalarVT = VT.getVectorElementType();
6067 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6068 ScalarVT = MVT::i32;
6071 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6072 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6076 // If the shuffle is not directly supported and it has 4 elements, use
6077 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6078 unsigned NumElts = VT.getVectorNumElements();
6080 unsigned PFIndexes[4];
6081 for (unsigned i = 0; i != 4; ++i) {
6082 if (ShuffleMask[i] < 0)
6085 PFIndexes[i] = ShuffleMask[i];
6088 // Compute the index in the perfect shuffle table.
6089 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6090 PFIndexes[2] * 9 + PFIndexes[3];
6091 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6092 unsigned Cost = (PFEntry >> 30);
6095 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6098 return GenerateTBL(Op, ShuffleMask, DAG);
6101 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6103 EVT VT = BVN->getValueType(0);
6104 APInt SplatBits, SplatUndef;
6105 unsigned SplatBitSize;
6107 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6108 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6110 for (unsigned i = 0; i < NumSplats; ++i) {
6111 CnstBits <<= SplatBitSize;
6112 UndefBits <<= SplatBitSize;
6113 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6114 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6123 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6124 SelectionDAG &DAG) const {
6125 BuildVectorSDNode *BVN =
6126 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6127 SDValue LHS = Op.getOperand(0);
6129 EVT VT = Op.getValueType();
6134 APInt CnstBits(VT.getSizeInBits(), 0);
6135 APInt UndefBits(VT.getSizeInBits(), 0);
6136 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6137 // We only have BIC vector immediate instruction, which is and-not.
6138 CnstBits = ~CnstBits;
6140 // We make use of a little bit of goto ickiness in order to avoid having to
6141 // duplicate the immediate matching logic for the undef toggled case.
6142 bool SecondTry = false;
6145 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6146 CnstBits = CnstBits.zextOrTrunc(64);
6147 uint64_t CnstVal = CnstBits.getZExtValue();
6149 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6150 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6151 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6152 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6153 DAG.getConstant(CnstVal, dl, MVT::i32),
6154 DAG.getConstant(0, dl, MVT::i32));
6155 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6158 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6159 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6160 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6161 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6162 DAG.getConstant(CnstVal, dl, MVT::i32),
6163 DAG.getConstant(8, dl, MVT::i32));
6164 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6167 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6168 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6169 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6170 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6171 DAG.getConstant(CnstVal, dl, MVT::i32),
6172 DAG.getConstant(16, dl, MVT::i32));
6173 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6176 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6177 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6178 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6179 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6180 DAG.getConstant(CnstVal, dl, MVT::i32),
6181 DAG.getConstant(24, dl, MVT::i32));
6182 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6185 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6186 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6187 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6188 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6189 DAG.getConstant(CnstVal, dl, MVT::i32),
6190 DAG.getConstant(0, dl, MVT::i32));
6191 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6194 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6195 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6196 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6197 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6198 DAG.getConstant(CnstVal, dl, MVT::i32),
6199 DAG.getConstant(8, dl, MVT::i32));
6200 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6207 CnstBits = ~UndefBits;
6211 // We can always fall back to a non-immediate AND.
6216 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6217 // consists of only the same constant int value, returned in reference arg
6219 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6220 uint64_t &ConstVal) {
6221 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6224 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6227 EVT VT = Bvec->getValueType(0);
6228 unsigned NumElts = VT.getVectorNumElements();
6229 for (unsigned i = 1; i < NumElts; ++i)
6230 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6232 ConstVal = FirstElt->getZExtValue();
6236 static unsigned getIntrinsicID(const SDNode *N) {
6237 unsigned Opcode = N->getOpcode();
6240 return Intrinsic::not_intrinsic;
6241 case ISD::INTRINSIC_WO_CHAIN: {
6242 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6243 if (IID < Intrinsic::num_intrinsics)
6245 return Intrinsic::not_intrinsic;
6250 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6251 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6252 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6253 // Also, logical shift right -> sri, with the same structure.
6254 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6255 EVT VT = N->getValueType(0);
6262 // Is the first op an AND?
6263 const SDValue And = N->getOperand(0);
6264 if (And.getOpcode() != ISD::AND)
6267 // Is the second op an shl or lshr?
6268 SDValue Shift = N->getOperand(1);
6269 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6270 // or AArch64ISD::VLSHR vector, #shift
6271 unsigned ShiftOpc = Shift.getOpcode();
6272 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6274 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6276 // Is the shift amount constant?
6277 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6281 // Is the and mask vector all constant?
6283 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6286 // Is C1 == ~C2, taking into account how much one can shift elements of a
6288 uint64_t C2 = C2node->getZExtValue();
6289 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6290 if (C2 > ElemSizeInBits)
6292 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6293 if ((C1 & ElemMask) != (~C2 & ElemMask))
6296 SDValue X = And.getOperand(0);
6297 SDValue Y = Shift.getOperand(0);
6300 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6302 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6303 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6304 Shift.getOperand(1));
6306 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6307 DEBUG(N->dump(&DAG));
6308 DEBUG(dbgs() << "into: \n");
6309 DEBUG(ResultSLI->dump(&DAG));
6315 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6316 SelectionDAG &DAG) const {
6317 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6318 if (EnableAArch64SlrGeneration) {
6319 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6323 BuildVectorSDNode *BVN =
6324 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6325 SDValue LHS = Op.getOperand(1);
6327 EVT VT = Op.getValueType();
6329 // OR commutes, so try swapping the operands.
6331 LHS = Op.getOperand(0);
6332 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6337 APInt CnstBits(VT.getSizeInBits(), 0);
6338 APInt UndefBits(VT.getSizeInBits(), 0);
6339 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6340 // We make use of a little bit of goto ickiness in order to avoid having to
6341 // duplicate the immediate matching logic for the undef toggled case.
6342 bool SecondTry = false;
6345 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6346 CnstBits = CnstBits.zextOrTrunc(64);
6347 uint64_t CnstVal = CnstBits.getZExtValue();
6349 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6350 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6351 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6352 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6353 DAG.getConstant(CnstVal, dl, MVT::i32),
6354 DAG.getConstant(0, dl, MVT::i32));
6355 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6358 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6359 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6360 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6361 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6362 DAG.getConstant(CnstVal, dl, MVT::i32),
6363 DAG.getConstant(8, dl, MVT::i32));
6364 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6367 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6368 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6369 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6370 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6371 DAG.getConstant(CnstVal, dl, MVT::i32),
6372 DAG.getConstant(16, dl, MVT::i32));
6373 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6376 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6377 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6378 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6379 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6380 DAG.getConstant(CnstVal, dl, MVT::i32),
6381 DAG.getConstant(24, dl, MVT::i32));
6382 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6385 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6386 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6387 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6388 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6389 DAG.getConstant(CnstVal, dl, MVT::i32),
6390 DAG.getConstant(0, dl, MVT::i32));
6391 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6394 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6395 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6396 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6397 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6398 DAG.getConstant(CnstVal, dl, MVT::i32),
6399 DAG.getConstant(8, dl, MVT::i32));
6400 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6407 CnstBits = UndefBits;
6411 // We can always fall back to a non-immediate OR.
6416 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6417 // be truncated to fit element width.
6418 static SDValue NormalizeBuildVector(SDValue Op,
6419 SelectionDAG &DAG) {
6420 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6422 EVT VT = Op.getValueType();
6423 EVT EltTy= VT.getVectorElementType();
6425 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6428 SmallVector<SDValue, 16> Ops;
6429 for (SDValue Lane : Op->ops()) {
6430 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6431 APInt LowBits(EltTy.getSizeInBits(),
6432 CstLane->getZExtValue());
6433 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6435 Ops.push_back(Lane);
6437 return DAG.getBuildVector(VT, dl, Ops);
6440 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6441 SelectionDAG &DAG) const {
6443 EVT VT = Op.getValueType();
6444 Op = NormalizeBuildVector(Op, DAG);
6445 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6447 APInt CnstBits(VT.getSizeInBits(), 0);
6448 APInt UndefBits(VT.getSizeInBits(), 0);
6449 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6450 // We make use of a little bit of goto ickiness in order to avoid having to
6451 // duplicate the immediate matching logic for the undef toggled case.
6452 bool SecondTry = false;
6455 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6456 CnstBits = CnstBits.zextOrTrunc(64);
6457 uint64_t CnstVal = CnstBits.getZExtValue();
6459 // Certain magic vector constants (used to express things like NOT
6460 // and NEG) are passed through unmodified. This allows codegen patterns
6461 // for these operations to match. Special-purpose patterns will lower
6462 // these immediates to MOVIs if it proves necessary.
6463 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6466 // The many faces of MOVI...
6467 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6468 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6469 if (VT.getSizeInBits() == 128) {
6470 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6471 DAG.getConstant(CnstVal, dl, MVT::i32));
6472 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6475 // Support the V64 version via subregister insertion.
6476 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6477 DAG.getConstant(CnstVal, dl, MVT::i32));
6478 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6481 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6482 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6483 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6484 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6485 DAG.getConstant(CnstVal, dl, MVT::i32),
6486 DAG.getConstant(0, dl, MVT::i32));
6487 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6490 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6491 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6492 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6493 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6494 DAG.getConstant(CnstVal, dl, MVT::i32),
6495 DAG.getConstant(8, dl, MVT::i32));
6496 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6499 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6500 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6501 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6502 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6503 DAG.getConstant(CnstVal, dl, MVT::i32),
6504 DAG.getConstant(16, dl, MVT::i32));
6505 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6508 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6509 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6510 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6511 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6512 DAG.getConstant(CnstVal, dl, MVT::i32),
6513 DAG.getConstant(24, dl, MVT::i32));
6514 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6517 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6518 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6519 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6520 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6521 DAG.getConstant(CnstVal, dl, MVT::i32),
6522 DAG.getConstant(0, dl, MVT::i32));
6523 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6526 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6527 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6528 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6529 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6530 DAG.getConstant(CnstVal, dl, MVT::i32),
6531 DAG.getConstant(8, dl, MVT::i32));
6532 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6535 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6536 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6537 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6538 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6539 DAG.getConstant(CnstVal, dl, MVT::i32),
6540 DAG.getConstant(264, dl, MVT::i32));
6541 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6544 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6545 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6546 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6547 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6548 DAG.getConstant(CnstVal, dl, MVT::i32),
6549 DAG.getConstant(272, dl, MVT::i32));
6550 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6553 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6554 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6555 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6556 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6557 DAG.getConstant(CnstVal, dl, MVT::i32));
6558 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6561 // The few faces of FMOV...
6562 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6563 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6564 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6565 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6566 DAG.getConstant(CnstVal, dl, MVT::i32));
6567 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6570 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6571 VT.getSizeInBits() == 128) {
6572 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6573 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6574 DAG.getConstant(CnstVal, dl, MVT::i32));
6575 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6578 // The many faces of MVNI...
6580 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6581 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6582 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6583 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6584 DAG.getConstant(CnstVal, dl, MVT::i32),
6585 DAG.getConstant(0, dl, MVT::i32));
6586 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6589 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6590 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6591 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6592 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6593 DAG.getConstant(CnstVal, dl, MVT::i32),
6594 DAG.getConstant(8, dl, MVT::i32));
6595 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6598 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6599 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6600 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6601 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6602 DAG.getConstant(CnstVal, dl, MVT::i32),
6603 DAG.getConstant(16, dl, MVT::i32));
6604 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6607 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6608 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6609 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6610 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6611 DAG.getConstant(CnstVal, dl, MVT::i32),
6612 DAG.getConstant(24, dl, MVT::i32));
6613 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6616 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6617 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6618 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6619 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6620 DAG.getConstant(CnstVal, dl, MVT::i32),
6621 DAG.getConstant(0, dl, MVT::i32));
6622 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6625 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6626 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6627 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6628 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6629 DAG.getConstant(CnstVal, dl, MVT::i32),
6630 DAG.getConstant(8, dl, MVT::i32));
6631 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6634 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6635 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6636 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6637 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6638 DAG.getConstant(CnstVal, dl, MVT::i32),
6639 DAG.getConstant(264, dl, MVT::i32));
6640 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6643 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6644 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6645 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6646 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6647 DAG.getConstant(CnstVal, dl, MVT::i32),
6648 DAG.getConstant(272, dl, MVT::i32));
6649 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6656 CnstBits = UndefBits;
6661 // Scan through the operands to find some interesting properties we can
6663 // 1) If only one value is used, we can use a DUP, or
6664 // 2) if only the low element is not undef, we can just insert that, or
6665 // 3) if only one constant value is used (w/ some non-constant lanes),
6666 // we can splat the constant value into the whole vector then fill
6667 // in the non-constant lanes.
6668 // 4) FIXME: If different constant values are used, but we can intelligently
6669 // select the values we'll be overwriting for the non-constant
6670 // lanes such that we can directly materialize the vector
6671 // some other way (MOVI, e.g.), we can be sneaky.
6672 unsigned NumElts = VT.getVectorNumElements();
6673 bool isOnlyLowElement = true;
6674 bool usesOnlyOneValue = true;
6675 bool usesOnlyOneConstantValue = true;
6676 bool isConstant = true;
6677 unsigned NumConstantLanes = 0;
6679 SDValue ConstantValue;
6680 for (unsigned i = 0; i < NumElts; ++i) {
6681 SDValue V = Op.getOperand(i);
6685 isOnlyLowElement = false;
6686 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6689 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6691 if (!ConstantValue.getNode())
6693 else if (ConstantValue != V)
6694 usesOnlyOneConstantValue = false;
6697 if (!Value.getNode())
6699 else if (V != Value)
6700 usesOnlyOneValue = false;
6703 if (!Value.getNode())
6704 return DAG.getUNDEF(VT);
6706 if (isOnlyLowElement)
6707 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6709 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6710 // i32 and try again.
6711 if (usesOnlyOneValue) {
6713 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6714 Value.getValueType() != VT)
6715 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6717 // This is actually a DUPLANExx operation, which keeps everything vectory.
6719 // DUPLANE works on 128-bit vectors, widen it if necessary.
6720 SDValue Lane = Value.getOperand(1);
6721 Value = Value.getOperand(0);
6722 if (Value.getValueSizeInBits() == 64)
6723 Value = WidenVector(Value, DAG);
6725 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6726 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6729 if (VT.getVectorElementType().isFloatingPoint()) {
6730 SmallVector<SDValue, 8> Ops;
6731 EVT EltTy = VT.getVectorElementType();
6732 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6733 "Unsupported floating-point vector type");
6734 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6735 for (unsigned i = 0; i < NumElts; ++i)
6736 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6737 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6738 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6739 Val = LowerBUILD_VECTOR(Val, DAG);
6741 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6745 // If there was only one constant value used and for more than one lane,
6746 // start by splatting that value, then replace the non-constant lanes. This
6747 // is better than the default, which will perform a separate initialization
6749 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6750 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6751 // Now insert the non-constant lanes.
6752 for (unsigned i = 0; i < NumElts; ++i) {
6753 SDValue V = Op.getOperand(i);
6754 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6755 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6756 // Note that type legalization likely mucked about with the VT of the
6757 // source operand, so we may have to convert it here before inserting.
6758 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6764 // If all elements are constants and the case above didn't get hit, fall back
6765 // to the default expansion, which will generate a load from the constant
6770 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6772 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6776 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6777 // know the default expansion would otherwise fall back on something even
6778 // worse. For a vector with one or two non-undef values, that's
6779 // scalar_to_vector for the elements followed by a shuffle (provided the
6780 // shuffle is valid for the target) and materialization element by element
6781 // on the stack followed by a load for everything else.
6782 if (!isConstant && !usesOnlyOneValue) {
6783 SDValue Vec = DAG.getUNDEF(VT);
6784 SDValue Op0 = Op.getOperand(0);
6787 // Use SCALAR_TO_VECTOR for lane zero to
6788 // a) Avoid a RMW dependency on the full vector register, and
6789 // b) Allow the register coalescer to fold away the copy if the
6790 // value is already in an S or D register, and we're forced to emit an
6791 // INSERT_SUBREG that we can't fold anywhere.
6793 // We also allow types like i8 and i16 which are illegal scalar but legal
6794 // vector element types. After type-legalization the inserted value is
6795 // extended (i32) and it is safe to cast them to the vector type by ignoring
6796 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6797 if (!Op0.isUndef()) {
6798 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
6801 for (; i < NumElts; ++i) {
6802 SDValue V = Op.getOperand(i);
6805 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6806 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6811 // Just use the default expansion. We failed to find a better alternative.
6815 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6816 SelectionDAG &DAG) const {
6817 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6819 // Check for non-constant or out of range lane.
6820 EVT VT = Op.getOperand(0).getValueType();
6821 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6822 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6826 // Insertion/extraction are legal for V128 types.
6827 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6828 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6832 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6833 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6836 // For V64 types, we perform insertion by expanding the value
6837 // to a V128 type and perform the insertion on that.
6839 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6840 EVT WideTy = WideVec.getValueType();
6842 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6843 Op.getOperand(1), Op.getOperand(2));
6844 // Re-narrow the resultant vector.
6845 return NarrowVector(Node, DAG);
6849 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6850 SelectionDAG &DAG) const {
6851 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6853 // Check for non-constant or out of range lane.
6854 EVT VT = Op.getOperand(0).getValueType();
6855 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6856 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6860 // Insertion/extraction are legal for V128 types.
6861 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6862 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6866 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6867 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6870 // For V64 types, we perform extraction by expanding the value
6871 // to a V128 type and perform the extraction on that.
6873 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6874 EVT WideTy = WideVec.getValueType();
6876 EVT ExtrTy = WideTy.getVectorElementType();
6877 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6880 // For extractions, we just return the result directly.
6881 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6885 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6886 SelectionDAG &DAG) const {
6887 EVT VT = Op.getOperand(0).getValueType();
6893 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6896 unsigned Val = Cst->getZExtValue();
6898 unsigned Size = Op.getValueSizeInBits();
6900 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6904 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6906 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6912 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6914 if (VT.getVectorNumElements() == 4 &&
6915 (VT.is128BitVector() || VT.is64BitVector())) {
6916 unsigned PFIndexes[4];
6917 for (unsigned i = 0; i != 4; ++i) {
6921 PFIndexes[i] = M[i];
6924 // Compute the index in the perfect shuffle table.
6925 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6926 PFIndexes[2] * 9 + PFIndexes[3];
6927 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6928 unsigned Cost = (PFEntry >> 30);
6936 unsigned DummyUnsigned;
6938 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6939 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6940 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6941 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6942 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6943 isZIPMask(M, VT, DummyUnsigned) ||
6944 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6945 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6946 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6947 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6948 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6951 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6952 /// operand of a vector shift operation, where all the elements of the
6953 /// build_vector must have the same constant integer value.
6954 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6955 // Ignore bit_converts.
6956 while (Op.getOpcode() == ISD::BITCAST)
6957 Op = Op.getOperand(0);
6958 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6959 APInt SplatBits, SplatUndef;
6960 unsigned SplatBitSize;
6962 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6963 HasAnyUndefs, ElementBits) ||
6964 SplatBitSize > ElementBits)
6966 Cnt = SplatBits.getSExtValue();
6970 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6971 /// operand of a vector shift left operation. That value must be in the range:
6972 /// 0 <= Value < ElementBits for a left shift; or
6973 /// 0 <= Value <= ElementBits for a long left shift.
6974 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6975 assert(VT.isVector() && "vector shift count is not a vector type");
6976 int64_t ElementBits = VT.getScalarSizeInBits();
6977 if (!getVShiftImm(Op, ElementBits, Cnt))
6979 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6982 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6983 /// operand of a vector shift right operation. The value must be in the range:
6984 /// 1 <= Value <= ElementBits for a right shift; or
6985 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6986 assert(VT.isVector() && "vector shift count is not a vector type");
6987 int64_t ElementBits = VT.getScalarSizeInBits();
6988 if (!getVShiftImm(Op, ElementBits, Cnt))
6990 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6993 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6994 SelectionDAG &DAG) const {
6995 EVT VT = Op.getValueType();
6999 if (!Op.getOperand(1).getValueType().isVector())
7001 unsigned EltSize = VT.getScalarSizeInBits();
7003 switch (Op.getOpcode()) {
7005 llvm_unreachable("unexpected shift opcode");
7008 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7009 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7010 DAG.getConstant(Cnt, DL, MVT::i32));
7011 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7012 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7014 Op.getOperand(0), Op.getOperand(1));
7017 // Right shift immediate
7018 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7020 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7021 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7022 DAG.getConstant(Cnt, DL, MVT::i32));
7025 // Right shift register. Note, there is not a shift right register
7026 // instruction, but the shift left register instruction takes a signed
7027 // value, where negative numbers specify a right shift.
7028 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7029 : Intrinsic::aarch64_neon_ushl;
7030 // negate the shift amount
7031 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7032 SDValue NegShiftLeft =
7033 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7034 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7036 return NegShiftLeft;
7042 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7043 AArch64CC::CondCode CC, bool NoNans, EVT VT,
7044 const SDLoc &dl, SelectionDAG &DAG) {
7045 EVT SrcVT = LHS.getValueType();
7046 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7047 "function only supposed to emit natural comparisons");
7049 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7050 APInt CnstBits(VT.getSizeInBits(), 0);
7051 APInt UndefBits(VT.getSizeInBits(), 0);
7052 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7053 bool IsZero = IsCnst && (CnstBits == 0);
7055 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7059 case AArch64CC::NE: {
7062 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7064 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7065 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7069 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7070 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7073 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7074 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7077 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7078 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7081 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7082 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7086 // If we ignore NaNs then we can use to the MI implementation.
7090 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7091 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7098 case AArch64CC::NE: {
7101 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7103 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7104 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7108 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7109 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7112 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7113 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7116 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7117 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7120 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7121 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7123 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7125 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7128 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7129 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7131 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7133 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7137 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7138 SelectionDAG &DAG) const {
7139 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7140 SDValue LHS = Op.getOperand(0);
7141 SDValue RHS = Op.getOperand(1);
7142 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7145 if (LHS.getValueType().getVectorElementType().isInteger()) {
7146 assert(LHS.getValueType() == RHS.getValueType());
7147 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7149 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7150 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7153 if (LHS.getValueType().getVectorElementType() == MVT::f16)
7156 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7157 LHS.getValueType().getVectorElementType() == MVT::f64);
7159 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7160 // clean. Some of them require two branches to implement.
7161 AArch64CC::CondCode CC1, CC2;
7163 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7165 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7167 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7171 if (CC2 != AArch64CC::AL) {
7173 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7174 if (!Cmp2.getNode())
7177 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7180 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7183 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7188 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7189 SelectionDAG &DAG) {
7190 SDValue VecOp = ScalarOp.getOperand(0);
7191 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7192 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7193 DAG.getConstant(0, DL, MVT::i64));
7196 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7197 SelectionDAG &DAG) const {
7199 switch (Op.getOpcode()) {
7200 case ISD::VECREDUCE_ADD:
7201 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7202 case ISD::VECREDUCE_SMAX:
7203 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7204 case ISD::VECREDUCE_SMIN:
7205 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7206 case ISD::VECREDUCE_UMAX:
7207 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7208 case ISD::VECREDUCE_UMIN:
7209 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7210 case ISD::VECREDUCE_FMAX: {
7211 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7213 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7214 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7217 case ISD::VECREDUCE_FMIN: {
7218 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7220 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7221 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7225 llvm_unreachable("Unhandled reduction");
7229 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7230 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7231 /// specified in the intrinsic calls.
7232 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7234 unsigned Intrinsic) const {
7235 auto &DL = I.getModule()->getDataLayout();
7236 switch (Intrinsic) {
7237 case Intrinsic::aarch64_neon_ld2:
7238 case Intrinsic::aarch64_neon_ld3:
7239 case Intrinsic::aarch64_neon_ld4:
7240 case Intrinsic::aarch64_neon_ld1x2:
7241 case Intrinsic::aarch64_neon_ld1x3:
7242 case Intrinsic::aarch64_neon_ld1x4:
7243 case Intrinsic::aarch64_neon_ld2lane:
7244 case Intrinsic::aarch64_neon_ld3lane:
7245 case Intrinsic::aarch64_neon_ld4lane:
7246 case Intrinsic::aarch64_neon_ld2r:
7247 case Intrinsic::aarch64_neon_ld3r:
7248 case Intrinsic::aarch64_neon_ld4r: {
7249 Info.opc = ISD::INTRINSIC_W_CHAIN;
7250 // Conservatively set memVT to the entire set of vectors loaded.
7251 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7252 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7253 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7256 Info.vol = false; // volatile loads with NEON intrinsics not supported
7257 Info.readMem = true;
7258 Info.writeMem = false;
7261 case Intrinsic::aarch64_neon_st2:
7262 case Intrinsic::aarch64_neon_st3:
7263 case Intrinsic::aarch64_neon_st4:
7264 case Intrinsic::aarch64_neon_st1x2:
7265 case Intrinsic::aarch64_neon_st1x3:
7266 case Intrinsic::aarch64_neon_st1x4:
7267 case Intrinsic::aarch64_neon_st2lane:
7268 case Intrinsic::aarch64_neon_st3lane:
7269 case Intrinsic::aarch64_neon_st4lane: {
7270 Info.opc = ISD::INTRINSIC_VOID;
7271 // Conservatively set memVT to the entire set of vectors stored.
7272 unsigned NumElts = 0;
7273 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7274 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7275 if (!ArgTy->isVectorTy())
7277 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7279 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7280 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7283 Info.vol = false; // volatile stores with NEON intrinsics not supported
7284 Info.readMem = false;
7285 Info.writeMem = true;
7288 case Intrinsic::aarch64_ldaxr:
7289 case Intrinsic::aarch64_ldxr: {
7290 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7291 Info.opc = ISD::INTRINSIC_W_CHAIN;
7292 Info.memVT = MVT::getVT(PtrTy->getElementType());
7293 Info.ptrVal = I.getArgOperand(0);
7295 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7297 Info.readMem = true;
7298 Info.writeMem = false;
7301 case Intrinsic::aarch64_stlxr:
7302 case Intrinsic::aarch64_stxr: {
7303 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7304 Info.opc = ISD::INTRINSIC_W_CHAIN;
7305 Info.memVT = MVT::getVT(PtrTy->getElementType());
7306 Info.ptrVal = I.getArgOperand(1);
7308 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7310 Info.readMem = false;
7311 Info.writeMem = true;
7314 case Intrinsic::aarch64_ldaxp:
7315 case Intrinsic::aarch64_ldxp:
7316 Info.opc = ISD::INTRINSIC_W_CHAIN;
7317 Info.memVT = MVT::i128;
7318 Info.ptrVal = I.getArgOperand(0);
7322 Info.readMem = true;
7323 Info.writeMem = false;
7325 case Intrinsic::aarch64_stlxp:
7326 case Intrinsic::aarch64_stxp:
7327 Info.opc = ISD::INTRINSIC_W_CHAIN;
7328 Info.memVT = MVT::i128;
7329 Info.ptrVal = I.getArgOperand(2);
7333 Info.readMem = false;
7334 Info.writeMem = true;
7343 // Truncations from 64-bit GPR to 32-bit GPR is free.
7344 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7345 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7347 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7348 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7349 return NumBits1 > NumBits2;
7351 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7352 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7354 unsigned NumBits1 = VT1.getSizeInBits();
7355 unsigned NumBits2 = VT2.getSizeInBits();
7356 return NumBits1 > NumBits2;
7359 /// Check if it is profitable to hoist instruction in then/else to if.
7360 /// Not profitable if I and it's user can form a FMA instruction
7361 /// because we prefer FMSUB/FMADD.
7362 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7363 if (I->getOpcode() != Instruction::FMul)
7366 if (!I->hasOneUse())
7369 Instruction *User = I->user_back();
7372 !(User->getOpcode() == Instruction::FSub ||
7373 User->getOpcode() == Instruction::FAdd))
7376 const TargetOptions &Options = getTargetMachine().Options;
7377 const DataLayout &DL = I->getModule()->getDataLayout();
7378 EVT VT = getValueType(DL, User->getOperand(0)->getType());
7380 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7381 isOperationLegalOrCustom(ISD::FMA, VT) &&
7382 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7383 Options.UnsafeFPMath));
7386 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7388 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7389 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7391 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7392 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7393 return NumBits1 == 32 && NumBits2 == 64;
7395 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7396 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7398 unsigned NumBits1 = VT1.getSizeInBits();
7399 unsigned NumBits2 = VT2.getSizeInBits();
7400 return NumBits1 == 32 && NumBits2 == 64;
7403 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7404 EVT VT1 = Val.getValueType();
7405 if (isZExtFree(VT1, VT2)) {
7409 if (Val.getOpcode() != ISD::LOAD)
7412 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7413 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7414 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7415 VT1.getSizeInBits() <= 32);
7418 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7419 if (isa<FPExtInst>(Ext))
7422 // Vector types are next free.
7423 if (Ext->getType()->isVectorTy())
7426 for (const Use &U : Ext->uses()) {
7427 // The extension is free if we can fold it with a left shift in an
7428 // addressing mode or an arithmetic operation: add, sub, and cmp.
7430 // Is there a shift?
7431 const Instruction *Instr = cast<Instruction>(U.getUser());
7433 // Is this a constant shift?
7434 switch (Instr->getOpcode()) {
7435 case Instruction::Shl:
7436 if (!isa<ConstantInt>(Instr->getOperand(1)))
7439 case Instruction::GetElementPtr: {
7440 gep_type_iterator GTI = gep_type_begin(Instr);
7441 auto &DL = Ext->getModule()->getDataLayout();
7442 std::advance(GTI, U.getOperandNo()-1);
7443 Type *IdxTy = GTI.getIndexedType();
7444 // This extension will end up with a shift because of the scaling factor.
7445 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7446 // Get the shift amount based on the scaling factor:
7447 // log2(sizeof(IdxTy)) - log2(8).
7449 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7450 // Is the constant foldable in the shift of the addressing mode?
7451 // I.e., shift amount is between 1 and 4 inclusive.
7452 if (ShiftAmt == 0 || ShiftAmt > 4)
7456 case Instruction::Trunc:
7457 // Check if this is a noop.
7458 // trunc(sext ty1 to ty2) to ty1.
7459 if (Instr->getType() == Ext->getOperand(0)->getType())
7466 // At this point we can use the bfm family, so this extension is free
7472 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7473 unsigned &RequiredAligment) const {
7474 if (!LoadedType.isSimple() ||
7475 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7477 // Cyclone supports unaligned accesses.
7478 RequiredAligment = 0;
7479 unsigned NumBits = LoadedType.getSizeInBits();
7480 return NumBits == 32 || NumBits == 64;
7483 /// A helper function for determining the number of interleaved accesses we
7484 /// will generate when lowering accesses of the given type.
7486 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7487 const DataLayout &DL) const {
7488 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7491 MachineMemOperand::Flags
7492 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
7493 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
7494 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
7495 return MOStridedAccess;
7496 return MachineMemOperand::MONone;
7499 bool AArch64TargetLowering::isLegalInterleavedAccessType(
7500 VectorType *VecTy, const DataLayout &DL) const {
7502 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7503 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7505 // Ensure the number of vector elements is greater than 1.
7506 if (VecTy->getNumElements() < 2)
7509 // Ensure the element type is legal.
7510 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7513 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7514 // 128 will be split into multiple interleaved accesses.
7515 return VecSize == 64 || VecSize % 128 == 0;
7518 /// \brief Lower an interleaved load into a ldN intrinsic.
7520 /// E.g. Lower an interleaved load (Factor = 2):
7521 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7522 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7523 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7526 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7527 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7528 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7529 bool AArch64TargetLowering::lowerInterleavedLoad(
7530 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7531 ArrayRef<unsigned> Indices, unsigned Factor) const {
7532 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7533 "Invalid interleave factor");
7534 assert(!Shuffles.empty() && "Empty shufflevector input");
7535 assert(Shuffles.size() == Indices.size() &&
7536 "Unmatched number of shufflevectors and indices");
7538 const DataLayout &DL = LI->getModule()->getDataLayout();
7540 VectorType *VecTy = Shuffles[0]->getType();
7542 // Skip if we do not have NEON and skip illegal vector types. We can
7543 // "legalize" wide vector types into multiple interleaved accesses as long as
7544 // the vector types are divisible by 128.
7545 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
7548 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7550 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7551 // load integer vectors first and then convert to pointer vectors.
7552 Type *EltTy = VecTy->getVectorElementType();
7553 if (EltTy->isPointerTy())
7555 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7557 IRBuilder<> Builder(LI);
7559 // The base address of the load.
7560 Value *BaseAddr = LI->getPointerOperand();
7563 // If we're going to generate more than one load, reset the sub-vector type
7564 // to something legal.
7565 VecTy = VectorType::get(VecTy->getVectorElementType(),
7566 VecTy->getVectorNumElements() / NumLoads);
7568 // We will compute the pointer operand of each load from the original base
7569 // address using GEPs. Cast the base address to a pointer to the scalar
7571 BaseAddr = Builder.CreateBitCast(
7572 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7573 LI->getPointerAddressSpace()));
7576 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7577 Type *Tys[2] = {VecTy, PtrTy};
7578 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7579 Intrinsic::aarch64_neon_ld3,
7580 Intrinsic::aarch64_neon_ld4};
7582 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7584 // Holds sub-vectors extracted from the load intrinsic return values. The
7585 // sub-vectors are associated with the shufflevector instructions they will
7587 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
7589 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
7591 // If we're generating more than one load, compute the base address of
7592 // subsequent loads as an offset from the previous.
7594 BaseAddr = Builder.CreateConstGEP1_32(
7595 BaseAddr, VecTy->getVectorNumElements() * Factor);
7597 CallInst *LdN = Builder.CreateCall(
7598 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
7600 // Extract and store the sub-vectors returned by the load intrinsic.
7601 for (unsigned i = 0; i < Shuffles.size(); i++) {
7602 ShuffleVectorInst *SVI = Shuffles[i];
7603 unsigned Index = Indices[i];
7605 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7607 // Convert the integer vector to pointer vector if the element is pointer.
7608 if (EltTy->isPointerTy())
7609 SubVec = Builder.CreateIntToPtr(
7610 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
7611 VecTy->getVectorNumElements()));
7612 SubVecs[SVI].push_back(SubVec);
7616 // Replace uses of the shufflevector instructions with the sub-vectors
7617 // returned by the load intrinsic. If a shufflevector instruction is
7618 // associated with more than one sub-vector, those sub-vectors will be
7619 // concatenated into a single wide vector.
7620 for (ShuffleVectorInst *SVI : Shuffles) {
7621 auto &SubVec = SubVecs[SVI];
7623 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7624 SVI->replaceAllUsesWith(WideVec);
7630 /// \brief Lower an interleaved store into a stN intrinsic.
7632 /// E.g. Lower an interleaved store (Factor = 3):
7633 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7634 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7635 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7638 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7639 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7640 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7641 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7643 /// Note that the new shufflevectors will be removed and we'll only generate one
7644 /// st3 instruction in CodeGen.
7646 /// Example for a more general valid mask (Factor 3). Lower:
7647 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7648 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7649 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7652 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7653 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7654 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7655 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7656 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7657 ShuffleVectorInst *SVI,
7658 unsigned Factor) const {
7659 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7660 "Invalid interleave factor");
7662 VectorType *VecTy = SVI->getType();
7663 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7664 "Invalid interleaved store");
7666 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7667 Type *EltTy = VecTy->getVectorElementType();
7668 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7670 const DataLayout &DL = SI->getModule()->getDataLayout();
7672 // Skip if we do not have NEON and skip illegal vector types. We can
7673 // "legalize" wide vector types into multiple interleaved accesses as long as
7674 // the vector types are divisible by 128.
7675 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
7678 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7680 Value *Op0 = SVI->getOperand(0);
7681 Value *Op1 = SVI->getOperand(1);
7682 IRBuilder<> Builder(SI);
7684 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7685 // vectors to integer vectors.
7686 if (EltTy->isPointerTy()) {
7687 Type *IntTy = DL.getIntPtrType(EltTy);
7688 unsigned NumOpElts =
7689 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7691 // Convert to the corresponding integer vector.
7692 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7693 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7694 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7696 SubVecTy = VectorType::get(IntTy, LaneLen);
7699 // The base address of the store.
7700 Value *BaseAddr = SI->getPointerOperand();
7702 if (NumStores > 1) {
7703 // If we're going to generate more than one store, reset the lane length
7704 // and sub-vector type to something legal.
7705 LaneLen /= NumStores;
7706 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7708 // We will compute the pointer operand of each store from the original base
7709 // address using GEPs. Cast the base address to a pointer to the scalar
7711 BaseAddr = Builder.CreateBitCast(
7712 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7713 SI->getPointerAddressSpace()));
7716 auto Mask = SVI->getShuffleMask();
7718 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7719 Type *Tys[2] = {SubVecTy, PtrTy};
7720 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7721 Intrinsic::aarch64_neon_st3,
7722 Intrinsic::aarch64_neon_st4};
7724 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7726 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
7728 SmallVector<Value *, 5> Ops;
7730 // Split the shufflevector operands into sub vectors for the new stN call.
7731 for (unsigned i = 0; i < Factor; i++) {
7732 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7733 if (Mask[IdxI] >= 0) {
7734 Ops.push_back(Builder.CreateShuffleVector(
7735 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7737 unsigned StartMask = 0;
7738 for (unsigned j = 1; j < LaneLen; j++) {
7739 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7740 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7741 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7745 // Note: Filling undef gaps with random elements is ok, since
7746 // those elements were being written anyway (with undefs).
7747 // In the case of all undefs we're defaulting to using elems from 0
7748 // Note: StartMask cannot be negative, it's checked in
7749 // isReInterleaveMask
7750 Ops.push_back(Builder.CreateShuffleVector(
7751 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7755 // If we generating more than one store, we compute the base address of
7756 // subsequent stores as an offset from the previous.
7758 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7760 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7761 Builder.CreateCall(StNFunc, Ops);
7766 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7767 unsigned AlignCheck) {
7768 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7769 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7772 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7773 unsigned SrcAlign, bool IsMemset,
7776 MachineFunction &MF) const {
7777 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7778 // instruction to materialize the v2i64 zero and one store (with restrictive
7779 // addressing mode). Just do two i64 store of zero-registers.
7781 const Function *F = MF.getFunction();
7782 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7783 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7784 (memOpAlign(SrcAlign, DstAlign, 16) ||
7785 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7789 (memOpAlign(SrcAlign, DstAlign, 8) ||
7790 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7794 (memOpAlign(SrcAlign, DstAlign, 4) ||
7795 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7801 // 12-bit optionally shifted immediates are legal for adds.
7802 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7803 // Avoid UB for INT64_MIN.
7804 if (Immed == std::numeric_limits<int64_t>::min())
7806 // Same encoding for add/sub, just flip the sign.
7807 Immed = std::abs(Immed);
7808 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7811 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7812 // immediates is the same as for an add or a sub.
7813 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7814 return isLegalAddImmediate(Immed);
7817 /// isLegalAddressingMode - Return true if the addressing mode represented
7818 /// by AM is legal for this target, for a load/store of the specified type.
7819 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7820 const AddrMode &AM, Type *Ty,
7821 unsigned AS) const {
7822 // AArch64 has five basic addressing modes:
7824 // reg + 9-bit signed offset
7825 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7827 // reg + SIZE_IN_BYTES * reg
7829 // No global is ever allowed as a base.
7833 // No reg+reg+imm addressing.
7834 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7837 // check reg + imm case:
7838 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7839 uint64_t NumBytes = 0;
7840 if (Ty->isSized()) {
7841 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7842 NumBytes = NumBits / 8;
7843 if (!isPowerOf2_64(NumBits))
7848 int64_t Offset = AM.BaseOffs;
7850 // 9-bit signed offset
7851 if (isInt<9>(Offset))
7854 // 12-bit unsigned offset
7855 unsigned shift = Log2_64(NumBytes);
7856 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7857 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7858 (Offset >> shift) << shift == Offset)
7863 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7865 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7868 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7869 const AddrMode &AM, Type *Ty,
7870 unsigned AS) const {
7871 // Scaling factors are not free at all.
7872 // Operands | Rt Latency
7873 // -------------------------------------------
7875 // -------------------------------------------
7876 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7877 // Rt, [Xn, Wm, <extend> #imm] |
7878 if (isLegalAddressingMode(DL, AM, Ty, AS))
7879 // Scale represents reg2 * scale, thus account for 1 if
7880 // it is not equal to 0 or 1.
7881 return AM.Scale != 0 && AM.Scale != 1;
7885 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7886 VT = VT.getScalarType();
7891 switch (VT.getSimpleVT().SimpleTy) {
7903 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7904 // LR is a callee-save register, but we must treat it as clobbered by any call
7905 // site. Hence we include LR in the scratch registers, which are in turn added
7906 // as implicit-defs for stackmaps and patchpoints.
7907 static const MCPhysReg ScratchRegs[] = {
7908 AArch64::X16, AArch64::X17, AArch64::LR, 0
7914 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7915 EVT VT = N->getValueType(0);
7916 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7917 // it with shift to let it be lowered to UBFX.
7918 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7919 isa<ConstantSDNode>(N->getOperand(1))) {
7920 uint64_t TruncMask = N->getConstantOperandVal(1);
7921 if (isMask_64(TruncMask) &&
7922 N->getOperand(0).getOpcode() == ISD::SRL &&
7923 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7929 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7931 assert(Ty->isIntegerTy());
7933 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7937 int64_t Val = Imm.getSExtValue();
7938 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7941 if ((int64_t)Val < 0)
7944 Val &= (1LL << 32) - 1;
7946 unsigned LZ = countLeadingZeros((uint64_t)Val);
7947 unsigned Shift = (63 - LZ) / 16;
7948 // MOVZ is free so return true for one or fewer MOVK.
7952 /// Turn vector tests of the signbit in the form of:
7953 /// xor (sra X, elt_size(X)-1), -1
7956 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7957 const AArch64Subtarget *Subtarget) {
7958 EVT VT = N->getValueType(0);
7959 if (!Subtarget->hasNEON() || !VT.isVector())
7962 // There must be a shift right algebraic before the xor, and the xor must be a
7964 SDValue Shift = N->getOperand(0);
7965 SDValue Ones = N->getOperand(1);
7966 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7967 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7970 // The shift should be smearing the sign bit across each vector element.
7971 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7972 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7973 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7976 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7979 // Generate SUBS and CSEL for integer abs.
7980 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7981 EVT VT = N->getValueType(0);
7983 SDValue N0 = N->getOperand(0);
7984 SDValue N1 = N->getOperand(1);
7987 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7988 // and change it to SUB and CSEL.
7989 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7990 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7991 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7992 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7993 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7994 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7996 // Generate SUBS & CSEL.
7998 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7999 N0.getOperand(0), DAG.getConstant(0, DL, VT));
8000 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
8001 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
8002 SDValue(Cmp.getNode(), 1));
8007 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8008 TargetLowering::DAGCombinerInfo &DCI,
8009 const AArch64Subtarget *Subtarget) {
8010 if (DCI.isBeforeLegalizeOps())
8013 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8016 return performIntegerAbsCombine(N, DAG);
8020 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8022 std::vector<SDNode *> *Created) const {
8023 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
8024 if (isIntDivCheap(N->getValueType(0), Attr))
8025 return SDValue(N,0); // Lower SDIV as SDIV
8027 // fold (sdiv X, pow2)
8028 EVT VT = N->getValueType(0);
8029 if ((VT != MVT::i32 && VT != MVT::i64) ||
8030 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8034 SDValue N0 = N->getOperand(0);
8035 unsigned Lg2 = Divisor.countTrailingZeros();
8036 SDValue Zero = DAG.getConstant(0, DL, VT);
8037 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
8039 // Add (N0 < 0) ? Pow2 - 1 : 0;
8041 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8042 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8043 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8046 Created->push_back(Cmp.getNode());
8047 Created->push_back(Add.getNode());
8048 Created->push_back(CSel.getNode());
8053 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
8055 // If we're dividing by a positive value, we're done. Otherwise, we must
8056 // negate the result.
8057 if (Divisor.isNonNegative())
8061 Created->push_back(SRA.getNode());
8062 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
8065 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8066 TargetLowering::DAGCombinerInfo &DCI,
8067 const AArch64Subtarget *Subtarget) {
8068 if (DCI.isBeforeLegalizeOps())
8071 // The below optimizations require a constant RHS.
8072 if (!isa<ConstantSDNode>(N->getOperand(1)))
8075 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8076 const APInt &ConstValue = C->getAPIntValue();
8078 // Multiplication of a power of two plus/minus one can be done more
8079 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8080 // future CPUs have a cheaper MADD instruction, this may need to be
8081 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8082 // 64-bit is 5 cycles, so this is always a win.
8083 // More aggressively, some multiplications N0 * C can be lowered to
8084 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8085 // e.g. 6=3*2=(2+1)*2.
8086 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8087 // which equals to (1+2)*16-(1+2).
8088 SDValue N0 = N->getOperand(0);
8089 // TrailingZeroes is used to test if the mul can be lowered to
8091 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8092 if (TrailingZeroes) {
8093 // Conservatively do not lower to shift+add+shift if the mul might be
8094 // folded into smul or umul.
8095 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8096 isZeroExtended(N0.getNode(), DAG)))
8098 // Conservatively do not lower to shift+add+shift if the mul might be
8099 // folded into madd or msub.
8100 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8101 N->use_begin()->getOpcode() == ISD::SUB))
8104 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8105 // and shift+add+shift.
8106 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8108 unsigned ShiftAmt, AddSubOpc;
8109 // Is the shifted value the LHS operand of the add/sub?
8110 bool ShiftValUseIsN0 = true;
8111 // Do we need to negate the result?
8112 bool NegateResult = false;
8114 if (ConstValue.isNonNegative()) {
8115 // (mul x, 2^N + 1) => (add (shl x, N), x)
8116 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8117 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8118 APInt SCVMinus1 = ShiftedConstValue - 1;
8119 APInt CVPlus1 = ConstValue + 1;
8120 if (SCVMinus1.isPowerOf2()) {
8121 ShiftAmt = SCVMinus1.logBase2();
8122 AddSubOpc = ISD::ADD;
8123 } else if (CVPlus1.isPowerOf2()) {
8124 ShiftAmt = CVPlus1.logBase2();
8125 AddSubOpc = ISD::SUB;
8129 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8130 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8131 APInt CVNegPlus1 = -ConstValue + 1;
8132 APInt CVNegMinus1 = -ConstValue - 1;
8133 if (CVNegPlus1.isPowerOf2()) {
8134 ShiftAmt = CVNegPlus1.logBase2();
8135 AddSubOpc = ISD::SUB;
8136 ShiftValUseIsN0 = false;
8137 } else if (CVNegMinus1.isPowerOf2()) {
8138 ShiftAmt = CVNegMinus1.logBase2();
8139 AddSubOpc = ISD::ADD;
8140 NegateResult = true;
8146 EVT VT = N->getValueType(0);
8147 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8148 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8150 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8151 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8152 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8153 assert(!(NegateResult && TrailingZeroes) &&
8154 "NegateResult and TrailingZeroes cannot both be true for now.");
8155 // Negate the result.
8157 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8158 // Shift the result.
8160 return DAG.getNode(ISD::SHL, DL, VT, Res,
8161 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8165 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8166 SelectionDAG &DAG) {
8167 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8168 // optimize away operation when it's from a constant.
8170 // The general transformation is:
8171 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8172 // AND(VECTOR_CMP(x,y), constant2)
8173 // constant2 = UNARYOP(constant)
8175 // Early exit if this isn't a vector operation, the operand of the
8176 // unary operation isn't a bitwise AND, or if the sizes of the operations
8178 EVT VT = N->getValueType(0);
8179 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8180 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8181 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8184 // Now check that the other operand of the AND is a constant. We could
8185 // make the transformation for non-constant splats as well, but it's unclear
8186 // that would be a benefit as it would not eliminate any operations, just
8187 // perform one more step in scalar code before moving to the vector unit.
8188 if (BuildVectorSDNode *BV =
8189 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8190 // Bail out if the vector isn't a constant.
8191 if (!BV->isConstant())
8194 // Everything checks out. Build up the new and improved node.
8196 EVT IntVT = BV->getValueType(0);
8197 // Create a new constant of the appropriate type for the transformed
8199 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8200 // The AND node needs bitcasts to/from an integer vector type around it.
8201 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8202 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8203 N->getOperand(0)->getOperand(0), MaskConst);
8204 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8211 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8212 const AArch64Subtarget *Subtarget) {
8213 // First try to optimize away the conversion when it's conditionally from
8214 // a constant. Vectors only.
8215 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8218 EVT VT = N->getValueType(0);
8219 if (VT != MVT::f32 && VT != MVT::f64)
8222 // Only optimize when the source and destination types have the same width.
8223 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8226 // If the result of an integer load is only used by an integer-to-float
8227 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8228 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8229 SDValue N0 = N->getOperand(0);
8230 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8231 // Do not change the width of a volatile load.
8232 !cast<LoadSDNode>(N0)->isVolatile()) {
8233 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8234 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8235 LN0->getPointerInfo(), LN0->getAlignment(),
8236 LN0->getMemOperand()->getFlags());
8238 // Make sure successors of the original load stay after it by updating them
8239 // to use the new Chain.
8240 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8243 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8244 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8250 /// Fold a floating-point multiply by power of two into floating-point to
8251 /// fixed-point conversion.
8252 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8253 TargetLowering::DAGCombinerInfo &DCI,
8254 const AArch64Subtarget *Subtarget) {
8255 if (!Subtarget->hasNEON())
8258 SDValue Op = N->getOperand(0);
8259 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8260 Op.getOpcode() != ISD::FMUL)
8263 SDValue ConstVec = Op->getOperand(1);
8264 if (!isa<BuildVectorSDNode>(ConstVec))
8267 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8268 uint32_t FloatBits = FloatTy.getSizeInBits();
8269 if (FloatBits != 32 && FloatBits != 64)
8272 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8273 uint32_t IntBits = IntTy.getSizeInBits();
8274 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8277 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8278 if (IntBits > FloatBits)
8281 BitVector UndefElements;
8282 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8283 int32_t Bits = IntBits == 64 ? 64 : 32;
8284 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8285 if (C == -1 || C == 0 || C > Bits)
8289 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8294 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8297 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8301 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8304 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8305 "Illegal vector type after legalization");
8308 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8309 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8310 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8312 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8313 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8314 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8315 // We can handle smaller integers by generating an extra trunc.
8316 if (IntBits < FloatBits)
8317 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8322 /// Fold a floating-point divide by power of two into fixed-point to
8323 /// floating-point conversion.
8324 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
8325 TargetLowering::DAGCombinerInfo &DCI,
8326 const AArch64Subtarget *Subtarget) {
8327 if (!Subtarget->hasNEON())
8330 SDValue Op = N->getOperand(0);
8331 unsigned Opc = Op->getOpcode();
8332 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8333 !Op.getOperand(0).getValueType().isSimple() ||
8334 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8337 SDValue ConstVec = N->getOperand(1);
8338 if (!isa<BuildVectorSDNode>(ConstVec))
8341 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8342 int32_t IntBits = IntTy.getSizeInBits();
8343 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8346 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8347 int32_t FloatBits = FloatTy.getSizeInBits();
8348 if (FloatBits != 32 && FloatBits != 64)
8351 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8352 if (IntBits > FloatBits)
8355 BitVector UndefElements;
8356 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8357 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8358 if (C == -1 || C == 0 || C > FloatBits)
8362 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8367 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8370 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8374 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8378 SDValue ConvInput = Op.getOperand(0);
8379 bool IsSigned = Opc == ISD::SINT_TO_FP;
8380 if (IntBits < FloatBits)
8381 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8384 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8385 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8386 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8387 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8388 DAG.getConstant(C, DL, MVT::i32));
8391 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8392 /// searches for and classifies those shifts.
8393 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8395 if (N.getOpcode() == ISD::SHL)
8397 else if (N.getOpcode() == ISD::SRL)
8402 if (!isa<ConstantSDNode>(N.getOperand(1)))
8405 ShiftAmount = N->getConstantOperandVal(1);
8406 Src = N->getOperand(0);
8410 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8411 /// registers viewed as a high/low pair. This function looks for the pattern:
8412 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
8413 /// with an EXTR. Can't quite be done in TableGen because the two immediates
8414 /// aren't independent.
8415 static SDValue tryCombineToEXTR(SDNode *N,
8416 TargetLowering::DAGCombinerInfo &DCI) {
8417 SelectionDAG &DAG = DCI.DAG;
8419 EVT VT = N->getValueType(0);
8421 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8423 if (VT != MVT::i32 && VT != MVT::i64)
8427 uint32_t ShiftLHS = 0;
8428 bool LHSFromHi = false;
8429 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8433 uint32_t ShiftRHS = 0;
8434 bool RHSFromHi = false;
8435 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8438 // If they're both trying to come from the high part of the register, they're
8439 // not really an EXTR.
8440 if (LHSFromHi == RHSFromHi)
8443 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8447 std::swap(LHS, RHS);
8448 std::swap(ShiftLHS, ShiftRHS);
8451 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8452 DAG.getConstant(ShiftRHS, DL, MVT::i64));
8455 static SDValue tryCombineToBSL(SDNode *N,
8456 TargetLowering::DAGCombinerInfo &DCI) {
8457 EVT VT = N->getValueType(0);
8458 SelectionDAG &DAG = DCI.DAG;
8464 SDValue N0 = N->getOperand(0);
8465 if (N0.getOpcode() != ISD::AND)
8468 SDValue N1 = N->getOperand(1);
8469 if (N1.getOpcode() != ISD::AND)
8472 // We only have to look for constant vectors here since the general, variable
8473 // case can be handled in TableGen.
8474 unsigned Bits = VT.getScalarSizeInBits();
8475 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8476 for (int i = 1; i >= 0; --i)
8477 for (int j = 1; j >= 0; --j) {
8478 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8479 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8483 bool FoundMatch = true;
8484 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8485 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8486 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8488 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8495 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8496 N0->getOperand(1 - i), N1->getOperand(1 - j));
8502 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8503 const AArch64Subtarget *Subtarget) {
8504 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8505 SelectionDAG &DAG = DCI.DAG;
8506 EVT VT = N->getValueType(0);
8508 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8511 if (SDValue Res = tryCombineToEXTR(N, DCI))
8514 if (SDValue Res = tryCombineToBSL(N, DCI))
8520 static SDValue performSRLCombine(SDNode *N,
8521 TargetLowering::DAGCombinerInfo &DCI) {
8522 SelectionDAG &DAG = DCI.DAG;
8523 EVT VT = N->getValueType(0);
8524 if (VT != MVT::i32 && VT != MVT::i64)
8527 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8528 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8529 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8530 SDValue N0 = N->getOperand(0);
8531 if (N0.getOpcode() == ISD::BSWAP) {
8533 SDValue N1 = N->getOperand(1);
8534 SDValue N00 = N0.getOperand(0);
8535 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8536 uint64_t ShiftAmt = C->getZExtValue();
8537 if (VT == MVT::i32 && ShiftAmt == 16 &&
8538 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8539 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8540 if (VT == MVT::i64 && ShiftAmt == 32 &&
8541 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8542 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8548 static SDValue performBitcastCombine(SDNode *N,
8549 TargetLowering::DAGCombinerInfo &DCI,
8550 SelectionDAG &DAG) {
8551 // Wait 'til after everything is legalized to try this. That way we have
8552 // legal vector types and such.
8553 if (DCI.isBeforeLegalizeOps())
8556 // Remove extraneous bitcasts around an extract_subvector.
8558 // (v4i16 (bitconvert
8559 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8561 // (extract_subvector ((v8i16 ...), (i64 4)))
8563 // Only interested in 64-bit vectors as the ultimate result.
8564 EVT VT = N->getValueType(0);
8567 if (VT.getSimpleVT().getSizeInBits() != 64)
8569 // Is the operand an extract_subvector starting at the beginning or halfway
8570 // point of the vector? A low half may also come through as an
8571 // EXTRACT_SUBREG, so look for that, too.
8572 SDValue Op0 = N->getOperand(0);
8573 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8574 !(Op0->isMachineOpcode() &&
8575 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8577 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8578 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8579 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8581 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8582 if (idx != AArch64::dsub)
8584 // The dsub reference is equivalent to a lane zero subvector reference.
8587 // Look through the bitcast of the input to the extract.
8588 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8590 SDValue Source = Op0->getOperand(0)->getOperand(0);
8591 // If the source type has twice the number of elements as our destination
8592 // type, we know this is an extract of the high or low half of the vector.
8593 EVT SVT = Source->getValueType(0);
8594 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8597 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8599 // Create the simplified form to just extract the low or high half of the
8600 // vector directly rather than bothering with the bitcasts.
8602 unsigned NumElements = VT.getVectorNumElements();
8604 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8605 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8607 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8608 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8614 static SDValue performConcatVectorsCombine(SDNode *N,
8615 TargetLowering::DAGCombinerInfo &DCI,
8616 SelectionDAG &DAG) {
8618 EVT VT = N->getValueType(0);
8619 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8621 // Optimize concat_vectors of truncated vectors, where the intermediate
8622 // type is illegal, to avoid said illegality, e.g.,
8623 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8624 // (v2i16 (truncate (v2i64)))))
8626 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8627 // (v4i32 (bitcast (v2i64))),
8629 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8630 // on both input and result type, so we might generate worse code.
8631 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8632 if (N->getNumOperands() == 2 &&
8633 N0->getOpcode() == ISD::TRUNCATE &&
8634 N1->getOpcode() == ISD::TRUNCATE) {
8635 SDValue N00 = N0->getOperand(0);
8636 SDValue N10 = N1->getOperand(0);
8637 EVT N00VT = N00.getValueType();
8639 if (N00VT == N10.getValueType() &&
8640 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8641 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8642 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8643 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8644 for (size_t i = 0; i < Mask.size(); ++i)
8646 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8647 DAG.getVectorShuffle(
8649 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8650 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8654 // Wait 'til after everything is legalized to try this. That way we have
8655 // legal vector types and such.
8656 if (DCI.isBeforeLegalizeOps())
8659 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8660 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8661 // canonicalise to that.
8662 if (N0 == N1 && VT.getVectorNumElements() == 2) {
8663 assert(VT.getScalarSizeInBits() == 64);
8664 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8665 DAG.getConstant(0, dl, MVT::i64));
8668 // Canonicalise concat_vectors so that the right-hand vector has as few
8669 // bit-casts as possible before its real operation. The primary matching
8670 // destination for these operations will be the narrowing "2" instructions,
8671 // which depend on the operation being performed on this right-hand vector.
8673 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8675 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8677 if (N1->getOpcode() != ISD::BITCAST)
8679 SDValue RHS = N1->getOperand(0);
8680 MVT RHSTy = RHS.getValueType().getSimpleVT();
8681 // If the RHS is not a vector, this is not the pattern we're looking for.
8682 if (!RHSTy.isVector())
8685 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8687 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8688 RHSTy.getVectorNumElements() * 2);
8689 return DAG.getNode(ISD::BITCAST, dl, VT,
8690 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8691 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8695 static SDValue tryCombineFixedPointConvert(SDNode *N,
8696 TargetLowering::DAGCombinerInfo &DCI,
8697 SelectionDAG &DAG) {
8698 // Wait 'til after everything is legalized to try this. That way we have
8699 // legal vector types and such.
8700 if (DCI.isBeforeLegalizeOps())
8702 // Transform a scalar conversion of a value from a lane extract into a
8703 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8704 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8705 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8707 // The second form interacts better with instruction selection and the
8708 // register allocator to avoid cross-class register copies that aren't
8709 // coalescable due to a lane reference.
8711 // Check the operand and see if it originates from a lane extract.
8712 SDValue Op1 = N->getOperand(1);
8713 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8714 // Yep, no additional predication needed. Perform the transform.
8715 SDValue IID = N->getOperand(0);
8716 SDValue Shift = N->getOperand(2);
8717 SDValue Vec = Op1.getOperand(0);
8718 SDValue Lane = Op1.getOperand(1);
8719 EVT ResTy = N->getValueType(0);
8723 // The vector width should be 128 bits by the time we get here, even
8724 // if it started as 64 bits (the extract_vector handling will have
8726 assert(Vec.getValueSizeInBits() == 128 &&
8727 "unexpected vector size on extract_vector_elt!");
8728 if (Vec.getValueType() == MVT::v4i32)
8729 VecResTy = MVT::v4f32;
8730 else if (Vec.getValueType() == MVT::v2i64)
8731 VecResTy = MVT::v2f64;
8733 llvm_unreachable("unexpected vector type!");
8736 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8737 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8742 // AArch64 high-vector "long" operations are formed by performing the non-high
8743 // version on an extract_subvector of each operand which gets the high half:
8745 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8747 // However, there are cases which don't have an extract_high explicitly, but
8748 // have another operation that can be made compatible with one for free. For
8751 // (dupv64 scalar) --> (extract_high (dup128 scalar))
8753 // This routine does the actual conversion of such DUPs, once outer routines
8754 // have determined that everything else is in order.
8755 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8757 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8758 switch (N.getOpcode()) {
8759 case AArch64ISD::DUP:
8760 case AArch64ISD::DUPLANE8:
8761 case AArch64ISD::DUPLANE16:
8762 case AArch64ISD::DUPLANE32:
8763 case AArch64ISD::DUPLANE64:
8764 case AArch64ISD::MOVI:
8765 case AArch64ISD::MOVIshift:
8766 case AArch64ISD::MOVIedit:
8767 case AArch64ISD::MOVImsl:
8768 case AArch64ISD::MVNIshift:
8769 case AArch64ISD::MVNImsl:
8772 // FMOV could be supported, but isn't very useful, as it would only occur
8773 // if you passed a bitcast' floating point immediate to an eligible long
8774 // integer op (addl, smull, ...).
8778 MVT NarrowTy = N.getSimpleValueType();
8779 if (!NarrowTy.is64BitVector())
8782 MVT ElementTy = NarrowTy.getVectorElementType();
8783 unsigned NumElems = NarrowTy.getVectorNumElements();
8784 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8787 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8788 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8789 DAG.getConstant(NumElems, dl, MVT::i64));
8792 static bool isEssentiallyExtractSubvector(SDValue N) {
8793 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8796 return N.getOpcode() == ISD::BITCAST &&
8797 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8800 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8801 struct GenericSetCCInfo {
8802 const SDValue *Opnd0;
8803 const SDValue *Opnd1;
8807 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8808 struct AArch64SetCCInfo {
8810 AArch64CC::CondCode CC;
8813 /// \brief Helper structure to keep track of SetCC information.
8815 GenericSetCCInfo Generic;
8816 AArch64SetCCInfo AArch64;
8819 /// \brief Helper structure to be able to read SetCC information. If set to
8820 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8821 /// GenericSetCCInfo.
8822 struct SetCCInfoAndKind {
8827 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8829 /// AArch64 lowered one.
8830 /// \p SetCCInfo is filled accordingly.
8831 /// \post SetCCInfo is meanginfull only when this function returns true.
8832 /// \return True when Op is a kind of SET_CC operation.
8833 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8834 // If this is a setcc, this is straight forward.
8835 if (Op.getOpcode() == ISD::SETCC) {
8836 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8837 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8838 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8839 SetCCInfo.IsAArch64 = false;
8842 // Otherwise, check if this is a matching csel instruction.
8846 if (Op.getOpcode() != AArch64ISD::CSEL)
8848 // Set the information about the operands.
8849 // TODO: we want the operands of the Cmp not the csel
8850 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8851 SetCCInfo.IsAArch64 = true;
8852 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8853 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8855 // Check that the operands matches the constraints:
8856 // (1) Both operands must be constants.
8857 // (2) One must be 1 and the other must be 0.
8858 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8859 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8862 if (!TValue || !FValue)
8866 if (!TValue->isOne()) {
8867 // Update the comparison when we are interested in !cc.
8868 std::swap(TValue, FValue);
8869 SetCCInfo.Info.AArch64.CC =
8870 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8872 return TValue->isOne() && FValue->isNullValue();
8875 // Returns true if Op is setcc or zext of setcc.
8876 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8877 if (isSetCC(Op, Info))
8879 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8880 isSetCC(Op->getOperand(0), Info));
8883 // The folding we want to perform is:
8884 // (add x, [zext] (setcc cc ...) )
8886 // (csel x, (add x, 1), !cc ...)
8888 // The latter will get matched to a CSINC instruction.
8889 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8890 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8891 SDValue LHS = Op->getOperand(0);
8892 SDValue RHS = Op->getOperand(1);
8893 SetCCInfoAndKind InfoAndKind;
8895 // If neither operand is a SET_CC, give up.
8896 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8897 std::swap(LHS, RHS);
8898 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8902 // FIXME: This could be generatized to work for FP comparisons.
8903 EVT CmpVT = InfoAndKind.IsAArch64
8904 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8905 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8906 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8912 if (InfoAndKind.IsAArch64) {
8913 CCVal = DAG.getConstant(
8914 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8916 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8918 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8919 *InfoAndKind.Info.Generic.Opnd1,
8920 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8923 EVT VT = Op->getValueType(0);
8924 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8925 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8928 // The basic add/sub long vector instructions have variants with "2" on the end
8929 // which act on the high-half of their inputs. They are normally matched by
8932 // (add (zeroext (extract_high LHS)),
8933 // (zeroext (extract_high RHS)))
8934 // -> uaddl2 vD, vN, vM
8936 // However, if one of the extracts is something like a duplicate, this
8937 // instruction can still be used profitably. This function puts the DAG into a
8938 // more appropriate form for those patterns to trigger.
8939 static SDValue performAddSubLongCombine(SDNode *N,
8940 TargetLowering::DAGCombinerInfo &DCI,
8941 SelectionDAG &DAG) {
8942 if (DCI.isBeforeLegalizeOps())
8945 MVT VT = N->getSimpleValueType(0);
8946 if (!VT.is128BitVector()) {
8947 if (N->getOpcode() == ISD::ADD)
8948 return performSetccAddFolding(N, DAG);
8952 // Make sure both branches are extended in the same way.
8953 SDValue LHS = N->getOperand(0);
8954 SDValue RHS = N->getOperand(1);
8955 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8956 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8957 LHS.getOpcode() != RHS.getOpcode())
8960 unsigned ExtType = LHS.getOpcode();
8962 // It's not worth doing if at least one of the inputs isn't already an
8963 // extract, but we don't know which it'll be so we have to try both.
8964 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8965 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8969 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8970 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8971 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8975 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8978 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8981 // Massage DAGs which we can use the high-half "long" operations on into
8982 // something isel will recognize better. E.g.
8984 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8985 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8986 // (extract_high (v2i64 (dup128 scalar)))))
8988 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8989 TargetLowering::DAGCombinerInfo &DCI,
8990 SelectionDAG &DAG) {
8991 if (DCI.isBeforeLegalizeOps())
8994 SDValue LHS = N->getOperand(1);
8995 SDValue RHS = N->getOperand(2);
8996 assert(LHS.getValueType().is64BitVector() &&
8997 RHS.getValueType().is64BitVector() &&
8998 "unexpected shape for long operation");
9000 // Either node could be a DUP, but it's not worth doing both of them (you'd
9001 // just as well use the non-high version) so look for a corresponding extract
9002 // operation on the other "wing".
9003 if (isEssentiallyExtractSubvector(LHS)) {
9004 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9007 } else if (isEssentiallyExtractSubvector(RHS)) {
9008 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9013 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9014 N->getOperand(0), LHS, RHS);
9017 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9018 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9019 unsigned ElemBits = ElemTy.getSizeInBits();
9021 int64_t ShiftAmount;
9022 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9023 APInt SplatValue, SplatUndef;
9024 unsigned SplatBitSize;
9026 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9027 HasAnyUndefs, ElemBits) ||
9028 SplatBitSize != ElemBits)
9031 ShiftAmount = SplatValue.getSExtValue();
9032 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9033 ShiftAmount = CVN->getSExtValue();
9041 llvm_unreachable("Unknown shift intrinsic");
9042 case Intrinsic::aarch64_neon_sqshl:
9043 Opcode = AArch64ISD::SQSHL_I;
9044 IsRightShift = false;
9046 case Intrinsic::aarch64_neon_uqshl:
9047 Opcode = AArch64ISD::UQSHL_I;
9048 IsRightShift = false;
9050 case Intrinsic::aarch64_neon_srshl:
9051 Opcode = AArch64ISD::SRSHR_I;
9052 IsRightShift = true;
9054 case Intrinsic::aarch64_neon_urshl:
9055 Opcode = AArch64ISD::URSHR_I;
9056 IsRightShift = true;
9058 case Intrinsic::aarch64_neon_sqshlu:
9059 Opcode = AArch64ISD::SQSHLU_I;
9060 IsRightShift = false;
9064 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9066 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9067 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9068 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9070 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9071 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9077 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9078 // the intrinsics must be legal and take an i32, this means there's almost
9079 // certainly going to be a zext in the DAG which we can eliminate.
9080 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9081 SDValue AndN = N->getOperand(2);
9082 if (AndN.getOpcode() != ISD::AND)
9085 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9086 if (!CMask || CMask->getZExtValue() != Mask)
9089 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9090 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9093 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9094 SelectionDAG &DAG) {
9096 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9097 DAG.getNode(Opc, dl,
9098 N->getOperand(1).getSimpleValueType(),
9100 DAG.getConstant(0, dl, MVT::i64));
9103 static SDValue performIntrinsicCombine(SDNode *N,
9104 TargetLowering::DAGCombinerInfo &DCI,
9105 const AArch64Subtarget *Subtarget) {
9106 SelectionDAG &DAG = DCI.DAG;
9107 unsigned IID = getIntrinsicID(N);
9111 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9112 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9113 return tryCombineFixedPointConvert(N, DCI, DAG);
9114 case Intrinsic::aarch64_neon_saddv:
9115 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9116 case Intrinsic::aarch64_neon_uaddv:
9117 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9118 case Intrinsic::aarch64_neon_sminv:
9119 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9120 case Intrinsic::aarch64_neon_uminv:
9121 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9122 case Intrinsic::aarch64_neon_smaxv:
9123 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9124 case Intrinsic::aarch64_neon_umaxv:
9125 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9126 case Intrinsic::aarch64_neon_fmax:
9127 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
9128 N->getOperand(1), N->getOperand(2));
9129 case Intrinsic::aarch64_neon_fmin:
9130 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
9131 N->getOperand(1), N->getOperand(2));
9132 case Intrinsic::aarch64_neon_fmaxnm:
9133 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9134 N->getOperand(1), N->getOperand(2));
9135 case Intrinsic::aarch64_neon_fminnm:
9136 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9137 N->getOperand(1), N->getOperand(2));
9138 case Intrinsic::aarch64_neon_smull:
9139 case Intrinsic::aarch64_neon_umull:
9140 case Intrinsic::aarch64_neon_pmull:
9141 case Intrinsic::aarch64_neon_sqdmull:
9142 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9143 case Intrinsic::aarch64_neon_sqshl:
9144 case Intrinsic::aarch64_neon_uqshl:
9145 case Intrinsic::aarch64_neon_sqshlu:
9146 case Intrinsic::aarch64_neon_srshl:
9147 case Intrinsic::aarch64_neon_urshl:
9148 return tryCombineShiftImm(IID, N, DAG);
9149 case Intrinsic::aarch64_crc32b:
9150 case Intrinsic::aarch64_crc32cb:
9151 return tryCombineCRC32(0xff, N, DAG);
9152 case Intrinsic::aarch64_crc32h:
9153 case Intrinsic::aarch64_crc32ch:
9154 return tryCombineCRC32(0xffff, N, DAG);
9159 static SDValue performExtendCombine(SDNode *N,
9160 TargetLowering::DAGCombinerInfo &DCI,
9161 SelectionDAG &DAG) {
9162 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9163 // we can convert that DUP into another extract_high (of a bigger DUP), which
9164 // helps the backend to decide that an sabdl2 would be useful, saving a real
9165 // extract_high operation.
9166 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9167 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9168 SDNode *ABDNode = N->getOperand(0).getNode();
9169 unsigned IID = getIntrinsicID(ABDNode);
9170 if (IID == Intrinsic::aarch64_neon_sabd ||
9171 IID == Intrinsic::aarch64_neon_uabd) {
9172 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9173 if (!NewABD.getNode())
9176 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9181 // This is effectively a custom type legalization for AArch64.
9183 // Type legalization will split an extend of a small, legal, type to a larger
9184 // illegal type by first splitting the destination type, often creating
9185 // illegal source types, which then get legalized in isel-confusing ways,
9186 // leading to really terrible codegen. E.g.,
9187 // %result = v8i32 sext v8i8 %value
9189 // %losrc = extract_subreg %value, ...
9190 // %hisrc = extract_subreg %value, ...
9191 // %lo = v4i32 sext v4i8 %losrc
9192 // %hi = v4i32 sext v4i8 %hisrc
9193 // Things go rapidly downhill from there.
9195 // For AArch64, the [sz]ext vector instructions can only go up one element
9196 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9197 // take two instructions.
9199 // This implies that the most efficient way to do the extend from v8i8
9200 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9201 // the normal splitting to happen for the v8i16->v8i32.
9203 // This is pre-legalization to catch some cases where the default
9204 // type legalization will create ill-tempered code.
9205 if (!DCI.isBeforeLegalizeOps())
9208 // We're only interested in cleaning things up for non-legal vector types
9209 // here. If both the source and destination are legal, things will just
9210 // work naturally without any fiddling.
9211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9212 EVT ResVT = N->getValueType(0);
9213 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9215 // If the vector type isn't a simple VT, it's beyond the scope of what
9216 // we're worried about here. Let legalization do its thing and hope for
9218 SDValue Src = N->getOperand(0);
9219 EVT SrcVT = Src->getValueType(0);
9220 if (!ResVT.isSimple() || !SrcVT.isSimple())
9223 // If the source VT is a 64-bit vector, we can play games and get the
9224 // better results we want.
9225 if (SrcVT.getSizeInBits() != 64)
9228 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9229 unsigned ElementCount = SrcVT.getVectorNumElements();
9230 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9232 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9234 // Now split the rest of the operation into two halves, each with a 64
9238 unsigned NumElements = ResVT.getVectorNumElements();
9239 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9240 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9241 ResVT.getVectorElementType(), NumElements / 2);
9243 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9244 LoVT.getVectorNumElements());
9245 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9246 DAG.getConstant(0, DL, MVT::i64));
9247 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9248 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9249 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9250 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9252 // Now combine the parts back together so we still have a single result
9253 // like the combiner expects.
9254 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9257 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9258 SDValue SplatVal, unsigned NumVecElts) {
9259 unsigned OrigAlignment = St.getAlignment();
9260 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
9262 // Create scalar stores. This is at least as good as the code sequence for a
9263 // split unaligned store which is a dup.s, ext.b, and two stores.
9264 // Most of the time the three stores should be replaced by store pair
9265 // instructions (stp).
9267 SDValue BasePtr = St.getBasePtr();
9268 uint64_t BaseOffset = 0;
9270 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
9272 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
9273 OrigAlignment, St.getMemOperand()->getFlags());
9275 // As this in ISel, we will not merge this add which may degrade results.
9276 if (BasePtr->getOpcode() == ISD::ADD &&
9277 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9278 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9279 BasePtr = BasePtr->getOperand(0);
9282 unsigned Offset = EltOffset;
9283 while (--NumVecElts) {
9284 unsigned Alignment = MinAlign(OrigAlignment, Offset);
9286 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9287 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
9288 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
9289 PtrInfo.getWithOffset(Offset), Alignment,
9290 St.getMemOperand()->getFlags());
9291 Offset += EltOffset;
9296 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9297 /// load store optimizer pass will merge them to store pair stores. This should
9298 /// be better than a movi to create the vector zero followed by a vector store
9299 /// if the zero constant is not re-used, since one instructions and one register
9300 /// live range will be removed.
9302 /// For example, the final generated code should be:
9304 /// stp xzr, xzr, [x0]
9311 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9312 SDValue StVal = St.getValue();
9313 EVT VT = StVal.getValueType();
9315 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9316 // 2, 3 or 4 i32 elements.
9317 int NumVecElts = VT.getVectorNumElements();
9318 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9319 VT.getVectorElementType().getSizeInBits() == 64) ||
9320 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9321 VT.getVectorElementType().getSizeInBits() == 32)))
9324 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9327 // If the zero constant has more than one use then the vector store could be
9328 // better since the constant mov will be amortized and stp q instructions
9329 // should be able to be formed.
9330 if (!StVal.hasOneUse())
9333 // If the immediate offset of the address operand is too large for the stp
9334 // instruction, then bail out.
9335 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9336 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
9337 if (Offset < -512 || Offset > 504)
9341 for (int I = 0; I < NumVecElts; ++I) {
9342 SDValue EltVal = StVal.getOperand(I);
9343 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9347 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9348 // undoing this transformation.
9349 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9350 ? DAG.getRegister(AArch64::WZR, MVT::i32)
9351 : DAG.getRegister(AArch64::XZR, MVT::i64);
9352 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9355 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9356 /// value. The load store optimizer pass will merge them to store pair stores.
9357 /// This has better performance than a splat of the scalar followed by a split
9358 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9359 /// followed by an ext.b and two stores.
9360 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9361 SDValue StVal = St.getValue();
9362 EVT VT = StVal.getValueType();
9364 // Don't replace floating point stores, they possibly won't be transformed to
9365 // stp because of the store pair suppress pass.
9366 if (VT.isFloatingPoint())
9369 // We can express a splat as store pair(s) for 2 or 4 elements.
9370 unsigned NumVecElts = VT.getVectorNumElements();
9371 if (NumVecElts != 4 && NumVecElts != 2)
9374 // Check that this is a splat.
9375 // Make sure that each of the relevant vector element locations are inserted
9376 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9377 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9379 for (unsigned I = 0; I < NumVecElts; ++I) {
9380 // Check for insert vector elements.
9381 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9384 // Check that same value is inserted at each vector element.
9386 SplatVal = StVal.getOperand(1);
9387 else if (StVal.getOperand(1) != SplatVal)
9390 // Check insert element index.
9391 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9394 uint64_t IndexVal = CIndex->getZExtValue();
9395 if (IndexVal >= NumVecElts)
9397 IndexNotInserted.reset(IndexVal);
9399 StVal = StVal.getOperand(0);
9401 // Check that all vector element locations were inserted to.
9402 if (IndexNotInserted.any())
9405 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9408 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9410 const AArch64Subtarget *Subtarget) {
9411 if (!DCI.isBeforeLegalize())
9414 StoreSDNode *S = cast<StoreSDNode>(N);
9415 if (S->isVolatile() || S->isIndexed())
9418 SDValue StVal = S->getValue();
9419 EVT VT = StVal.getValueType();
9423 // If we get a splat of zeros, convert this vector store to a store of
9424 // scalars. They will be merged into store pairs of xzr thereby removing one
9425 // instruction and one register.
9426 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9427 return ReplacedZeroSplat;
9429 // FIXME: The logic for deciding if an unaligned store should be split should
9430 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9431 // a call to that function here.
9433 if (!Subtarget->isMisaligned128StoreSlow())
9436 // Don't split at -Oz.
9437 if (DAG.getMachineFunction().getFunction()->optForMinSize())
9440 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9441 // those up regresses performance on micro-benchmarks and olden/bh.
9442 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9445 // Split unaligned 16B stores. They are terrible for performance.
9446 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9447 // extensions can use this to mark that it does not want splitting to happen
9448 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9449 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9450 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9451 S->getAlignment() <= 2)
9454 // If we get a splat of a scalar convert this vector store to a store of
9455 // scalars. They will be merged into store pairs thereby removing two
9457 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9458 return ReplacedSplat;
9461 unsigned NumElts = VT.getVectorNumElements() / 2;
9462 // Split VT into two.
9464 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9465 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9466 DAG.getConstant(0, DL, MVT::i64));
9467 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9468 DAG.getConstant(NumElts, DL, MVT::i64));
9469 SDValue BasePtr = S->getBasePtr();
9471 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9472 S->getAlignment(), S->getMemOperand()->getFlags());
9473 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9474 DAG.getConstant(8, DL, MVT::i64));
9475 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9476 S->getPointerInfo(), S->getAlignment(),
9477 S->getMemOperand()->getFlags());
9480 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9481 /// post-increment LD1R.
9482 static SDValue performPostLD1Combine(SDNode *N,
9483 TargetLowering::DAGCombinerInfo &DCI,
9485 if (DCI.isBeforeLegalizeOps())
9488 SelectionDAG &DAG = DCI.DAG;
9489 EVT VT = N->getValueType(0);
9491 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9492 SDNode *LD = N->getOperand(LoadIdx).getNode();
9493 // If it is not LOAD, can not do such combine.
9494 if (LD->getOpcode() != ISD::LOAD)
9497 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9498 EVT MemVT = LoadSDN->getMemoryVT();
9499 // Check if memory operand is the same type as the vector element.
9500 if (MemVT != VT.getVectorElementType())
9503 // Check if there are other uses. If so, do not combine as it will introduce
9505 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9507 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9513 SDValue Addr = LD->getOperand(1);
9514 SDValue Vector = N->getOperand(0);
9515 // Search for a use of the address operand that is an increment.
9516 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9517 Addr.getNode()->use_end(); UI != UE; ++UI) {
9519 if (User->getOpcode() != ISD::ADD
9520 || UI.getUse().getResNo() != Addr.getResNo())
9523 // Check that the add is independent of the load. Otherwise, folding it
9524 // would create a cycle.
9525 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9527 // Also check that add is not used in the vector operand. This would also
9529 if (User->isPredecessorOf(Vector.getNode()))
9532 // If the increment is a constant, it must match the memory ref size.
9533 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9534 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9535 uint32_t IncVal = CInc->getZExtValue();
9536 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9537 if (IncVal != NumBytes)
9539 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9542 // Finally, check that the vector doesn't depend on the load.
9543 // Again, this would create a cycle.
9544 // The load depending on the vector is fine, as that's the case for the
9545 // LD1*post we'll eventually generate anyway.
9546 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9549 SmallVector<SDValue, 8> Ops;
9550 Ops.push_back(LD->getOperand(0)); // Chain
9552 Ops.push_back(Vector); // The vector to be inserted
9553 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9555 Ops.push_back(Addr);
9558 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9559 SDVTList SDTys = DAG.getVTList(Tys);
9560 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9561 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9563 LoadSDN->getMemOperand());
9566 SDValue NewResults[] = {
9567 SDValue(LD, 0), // The result of load
9568 SDValue(UpdN.getNode(), 2) // Chain
9570 DCI.CombineTo(LD, NewResults);
9571 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9572 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9579 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
9580 /// address translation.
9581 static bool performTBISimplification(SDValue Addr,
9582 TargetLowering::DAGCombinerInfo &DCI,
9583 SelectionDAG &DAG) {
9584 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9586 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9587 DCI.isBeforeLegalizeOps());
9588 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9589 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
9590 DCI.CommitTargetLoweringOpt(TLO);
9596 static SDValue performSTORECombine(SDNode *N,
9597 TargetLowering::DAGCombinerInfo &DCI,
9599 const AArch64Subtarget *Subtarget) {
9600 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9603 if (Subtarget->supportsAddressTopByteIgnored() &&
9604 performTBISimplification(N->getOperand(2), DCI, DAG))
9605 return SDValue(N, 0);
9611 /// Target-specific DAG combine function for NEON load/store intrinsics
9612 /// to merge base address updates.
9613 static SDValue performNEONPostLDSTCombine(SDNode *N,
9614 TargetLowering::DAGCombinerInfo &DCI,
9615 SelectionDAG &DAG) {
9616 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9619 unsigned AddrOpIdx = N->getNumOperands() - 1;
9620 SDValue Addr = N->getOperand(AddrOpIdx);
9622 // Search for a use of the address operand that is an increment.
9623 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9624 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9626 if (User->getOpcode() != ISD::ADD ||
9627 UI.getUse().getResNo() != Addr.getResNo())
9630 // Check that the add is independent of the load/store. Otherwise, folding
9631 // it would create a cycle.
9632 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9635 // Find the new opcode for the updating load/store.
9636 bool IsStore = false;
9637 bool IsLaneOp = false;
9638 bool IsDupOp = false;
9639 unsigned NewOpc = 0;
9640 unsigned NumVecs = 0;
9641 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9643 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9644 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9646 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9648 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9650 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9651 NumVecs = 2; IsStore = true; break;
9652 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9653 NumVecs = 3; IsStore = true; break;
9654 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9655 NumVecs = 4; IsStore = true; break;
9656 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9658 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9660 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9662 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9663 NumVecs = 2; IsStore = true; break;
9664 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9665 NumVecs = 3; IsStore = true; break;
9666 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9667 NumVecs = 4; IsStore = true; break;
9668 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9669 NumVecs = 2; IsDupOp = true; break;
9670 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9671 NumVecs = 3; IsDupOp = true; break;
9672 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9673 NumVecs = 4; IsDupOp = true; break;
9674 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9675 NumVecs = 2; IsLaneOp = true; break;
9676 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9677 NumVecs = 3; IsLaneOp = true; break;
9678 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9679 NumVecs = 4; IsLaneOp = true; break;
9680 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9681 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9682 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9683 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9684 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9685 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9690 VecTy = N->getOperand(2).getValueType();
9692 VecTy = N->getValueType(0);
9694 // If the increment is a constant, it must match the memory ref size.
9695 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9696 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9697 uint32_t IncVal = CInc->getZExtValue();
9698 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9699 if (IsLaneOp || IsDupOp)
9700 NumBytes /= VecTy.getVectorNumElements();
9701 if (IncVal != NumBytes)
9703 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9705 SmallVector<SDValue, 8> Ops;
9706 Ops.push_back(N->getOperand(0)); // Incoming chain
9707 // Load lane and store have vector list as input.
9708 if (IsLaneOp || IsStore)
9709 for (unsigned i = 2; i < AddrOpIdx; ++i)
9710 Ops.push_back(N->getOperand(i));
9711 Ops.push_back(Addr); // Base register
9716 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9718 for (n = 0; n < NumResultVecs; ++n)
9720 Tys[n++] = MVT::i64; // Type of write back register
9721 Tys[n] = MVT::Other; // Type of the chain
9722 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9724 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9725 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9726 MemInt->getMemoryVT(),
9727 MemInt->getMemOperand());
9730 std::vector<SDValue> NewResults;
9731 for (unsigned i = 0; i < NumResultVecs; ++i) {
9732 NewResults.push_back(SDValue(UpdN.getNode(), i));
9734 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9735 DCI.CombineTo(N, NewResults);
9736 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9743 // Checks to see if the value is the prescribed width and returns information
9744 // about its extension mode.
9746 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9747 ExtType = ISD::NON_EXTLOAD;
9748 switch(V.getNode()->getOpcode()) {
9752 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9753 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9754 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9755 ExtType = LoadNode->getExtensionType();
9760 case ISD::AssertSext: {
9761 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9762 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9763 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9764 ExtType = ISD::SEXTLOAD;
9769 case ISD::AssertZext: {
9770 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9771 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9772 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9773 ExtType = ISD::ZEXTLOAD;
9779 case ISD::TargetConstant: {
9780 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9788 // This function does a whole lot of voodoo to determine if the tests are
9789 // equivalent without and with a mask. Essentially what happens is that given a
9792 // +-------------+ +-------------+ +-------------+ +-------------+
9793 // | Input | | AddConstant | | CompConstant| | CC |
9794 // +-------------+ +-------------+ +-------------+ +-------------+
9796 // V V | +----------+
9797 // +-------------+ +----+ | |
9798 // | ADD | |0xff| | |
9799 // +-------------+ +----+ | |
9802 // +-------------+ | |
9804 // +-------------+ | |
9813 // The AND node may be safely removed for some combinations of inputs. In
9814 // particular we need to take into account the extension type of the Input,
9815 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9816 // width of the input (this can work for any width inputs, the above graph is
9817 // specific to 8 bits.
9819 // The specific equations were worked out by generating output tables for each
9820 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9821 // problem was simplified by working with 4 bit inputs, which means we only
9822 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9823 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9824 // patterns present in both extensions (0,7). For every distinct set of
9825 // AddConstant and CompConstants bit patterns we can consider the masked and
9826 // unmasked versions to be equivalent if the result of this function is true for
9827 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9830 // and w10, w8, #0x0f
9832 // cset w9, AArch64CC
9834 // cset w11, AArch64CC
9839 // Since the above function shows when the outputs are equivalent it defines
9840 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9841 // would be expensive to run during compiles. The equations below were written
9842 // in a test harness that confirmed they gave equivalent outputs to the above
9843 // for all inputs function, so they can be used determine if the removal is
9846 // isEquivalentMaskless() is the code for testing if the AND can be removed
9847 // factored out of the DAG recognition as the DAG can take several forms.
9849 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9850 ISD::LoadExtType ExtType, int AddConstant,
9852 // By being careful about our equations and only writing the in term
9853 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9854 // make them generally applicable to all bit widths.
9855 int MaxUInt = (1 << width);
9857 // For the purposes of these comparisons sign extending the type is
9858 // equivalent to zero extending the add and displacing it by half the integer
9859 // width. Provided we are careful and make sure our equations are valid over
9860 // the whole range we can just adjust the input and avoid writing equations
9861 // for sign extended inputs.
9862 if (ExtType == ISD::SEXTLOAD)
9863 AddConstant -= (1 << (width-1));
9868 if ((AddConstant == 0) ||
9869 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9870 (AddConstant >= 0 && CompConstant < 0) ||
9871 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9876 if ((AddConstant == 0) ||
9877 (AddConstant >= 0 && CompConstant <= 0) ||
9878 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9883 if ((AddConstant >= 0 && CompConstant < 0) ||
9884 (AddConstant <= 0 && CompConstant >= -1 &&
9885 CompConstant < AddConstant + MaxUInt))
9890 if ((AddConstant == 0) ||
9891 (AddConstant > 0 && CompConstant <= 0) ||
9892 (AddConstant < 0 && CompConstant <= AddConstant))
9897 if ((AddConstant >= 0 && CompConstant <= 0) ||
9898 (AddConstant <= 0 && CompConstant >= 0 &&
9899 CompConstant <= AddConstant + MaxUInt))
9904 if ((AddConstant > 0 && CompConstant < 0) ||
9905 (AddConstant < 0 && CompConstant >= 0 &&
9906 CompConstant < AddConstant + MaxUInt) ||
9907 (AddConstant >= 0 && CompConstant >= 0 &&
9908 CompConstant >= AddConstant) ||
9909 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9917 case AArch64CC::Invalid:
9925 SDValue performCONDCombine(SDNode *N,
9926 TargetLowering::DAGCombinerInfo &DCI,
9927 SelectionDAG &DAG, unsigned CCIndex,
9928 unsigned CmpIndex) {
9929 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9930 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9931 unsigned CondOpcode = SubsNode->getOpcode();
9933 if (CondOpcode != AArch64ISD::SUBS)
9936 // There is a SUBS feeding this condition. Is it fed by a mask we can
9939 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9940 unsigned MaskBits = 0;
9942 if (AndNode->getOpcode() != ISD::AND)
9945 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9946 uint32_t CNV = CN->getZExtValue();
9949 else if (CNV == 65535)
9956 SDValue AddValue = AndNode->getOperand(0);
9958 if (AddValue.getOpcode() != ISD::ADD)
9961 // The basic dag structure is correct, grab the inputs and validate them.
9963 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9964 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9965 SDValue SubsInputValue = SubsNode->getOperand(1);
9967 // The mask is present and the provenance of all the values is a smaller type,
9968 // lets see if the mask is superfluous.
9970 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9971 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9974 ISD::LoadExtType ExtType;
9976 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9977 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9978 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9981 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9982 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9983 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9986 // The AND is not necessary, remove it.
9988 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9989 SubsNode->getValueType(1));
9990 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9992 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9993 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9995 return SDValue(N, 0);
9998 // Optimize compare with zero and branch.
9999 static SDValue performBRCONDCombine(SDNode *N,
10000 TargetLowering::DAGCombinerInfo &DCI,
10001 SelectionDAG &DAG) {
10002 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10004 SDValue Chain = N->getOperand(0);
10005 SDValue Dest = N->getOperand(1);
10006 SDValue CCVal = N->getOperand(2);
10007 SDValue Cmp = N->getOperand(3);
10009 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10010 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10011 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10014 unsigned CmpOpc = Cmp.getOpcode();
10015 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10018 // Only attempt folding if there is only one use of the flag and no use of the
10020 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10023 SDValue LHS = Cmp.getOperand(0);
10024 SDValue RHS = Cmp.getOperand(1);
10026 assert(LHS.getValueType() == RHS.getValueType() &&
10027 "Expected the value type to be the same for both operands!");
10028 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10031 if (isNullConstant(LHS))
10032 std::swap(LHS, RHS);
10034 if (!isNullConstant(RHS))
10037 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10038 LHS.getOpcode() == ISD::SRL)
10041 // Fold the compare into the branch instruction.
10043 if (CC == AArch64CC::EQ)
10044 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10046 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10048 // Do not add new nodes to DAG combiner worklist.
10049 DCI.CombineTo(N, BR, false);
10054 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10055 // as well as whether the test should be inverted. This code is required to
10056 // catch these cases (as opposed to standard dag combines) because
10057 // AArch64ISD::TBZ is matched during legalization.
10058 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10059 SelectionDAG &DAG) {
10061 if (!Op->hasOneUse())
10064 // We don't handle undef/constant-fold cases below, as they should have
10065 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10068 // (tbz (trunc x), b) -> (tbz x, b)
10069 // This case is just here to enable more of the below cases to be caught.
10070 if (Op->getOpcode() == ISD::TRUNCATE &&
10071 Bit < Op->getValueType(0).getSizeInBits()) {
10072 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10075 if (Op->getNumOperands() != 2)
10078 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10082 switch (Op->getOpcode()) {
10086 // (tbz (and x, m), b) -> (tbz x, b)
10088 if ((C->getZExtValue() >> Bit) & 1)
10089 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10092 // (tbz (shl x, c), b) -> (tbz x, b-c)
10094 if (C->getZExtValue() <= Bit &&
10095 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10096 Bit = Bit - C->getZExtValue();
10097 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10101 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10103 Bit = Bit + C->getZExtValue();
10104 if (Bit >= Op->getValueType(0).getSizeInBits())
10105 Bit = Op->getValueType(0).getSizeInBits() - 1;
10106 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10108 // (tbz (srl x, c), b) -> (tbz x, b+c)
10110 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10111 Bit = Bit + C->getZExtValue();
10112 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10116 // (tbz (xor x, -1), b) -> (tbnz x, b)
10118 if ((C->getZExtValue() >> Bit) & 1)
10120 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10124 // Optimize test single bit zero/non-zero and branch.
10125 static SDValue performTBZCombine(SDNode *N,
10126 TargetLowering::DAGCombinerInfo &DCI,
10127 SelectionDAG &DAG) {
10128 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10129 bool Invert = false;
10130 SDValue TestSrc = N->getOperand(1);
10131 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10133 if (TestSrc == NewTestSrc)
10136 unsigned NewOpc = N->getOpcode();
10138 if (NewOpc == AArch64ISD::TBZ)
10139 NewOpc = AArch64ISD::TBNZ;
10141 assert(NewOpc == AArch64ISD::TBNZ);
10142 NewOpc = AArch64ISD::TBZ;
10147 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10148 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10151 // vselect (v1i1 setcc) ->
10152 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
10153 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10154 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10156 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10157 SDValue N0 = N->getOperand(0);
10158 EVT CCVT = N0.getValueType();
10160 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10161 CCVT.getVectorElementType() != MVT::i1)
10164 EVT ResVT = N->getValueType(0);
10165 EVT CmpVT = N0.getOperand(0).getValueType();
10166 // Only combine when the result type is of the same size as the compared
10168 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10171 SDValue IfTrue = N->getOperand(1);
10172 SDValue IfFalse = N->getOperand(2);
10174 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10175 N0.getOperand(0), N0.getOperand(1),
10176 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10177 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10181 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10182 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10183 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10184 /// with a vector one followed by a DUP shuffle on the result.
10185 static SDValue performSelectCombine(SDNode *N,
10186 TargetLowering::DAGCombinerInfo &DCI) {
10187 SelectionDAG &DAG = DCI.DAG;
10188 SDValue N0 = N->getOperand(0);
10189 EVT ResVT = N->getValueType(0);
10191 if (N0.getOpcode() != ISD::SETCC)
10194 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10195 // scalar SetCCResultType. We also don't expect vectors, because we assume
10196 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10197 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10198 "Scalar-SETCC feeding SELECT has unexpected result type!");
10200 // If NumMaskElts == 0, the comparison is larger than select result. The
10201 // largest real NEON comparison is 64-bits per lane, which means the result is
10202 // at most 32-bits and an illegal vector. Just bail out for now.
10203 EVT SrcVT = N0.getOperand(0).getValueType();
10205 // Don't try to do this optimization when the setcc itself has i1 operands.
10206 // There are no legal vectors of i1, so this would be pointless.
10207 if (SrcVT == MVT::i1)
10210 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10211 if (!ResVT.isVector() || NumMaskElts == 0)
10214 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10215 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10217 // Also bail out if the vector CCVT isn't the same size as ResVT.
10218 // This can happen if the SETCC operand size doesn't divide the ResVT size
10219 // (e.g., f64 vs v3f32).
10220 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10223 // Make sure we didn't create illegal types, if we're not supposed to.
10224 assert(DCI.isBeforeLegalize() ||
10225 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10227 // First perform a vector comparison, where lane 0 is the one we're interested
10231 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10233 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10234 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10236 // Now duplicate the comparison mask we want across all other lanes.
10237 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10238 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10239 Mask = DAG.getNode(ISD::BITCAST, DL,
10240 ResVT.changeVectorElementTypeToInteger(), Mask);
10242 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10245 /// Get rid of unnecessary NVCASTs (that don't change the type).
10246 static SDValue performNVCASTCombine(SDNode *N) {
10247 if (N->getValueType(0) == N->getOperand(0).getValueType())
10248 return N->getOperand(0);
10253 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10254 DAGCombinerInfo &DCI) const {
10255 SelectionDAG &DAG = DCI.DAG;
10256 switch (N->getOpcode()) {
10261 return performAddSubLongCombine(N, DCI, DAG);
10263 return performXorCombine(N, DAG, DCI, Subtarget);
10265 return performMulCombine(N, DAG, DCI, Subtarget);
10266 case ISD::SINT_TO_FP:
10267 case ISD::UINT_TO_FP:
10268 return performIntToFpCombine(N, DAG, Subtarget);
10269 case ISD::FP_TO_SINT:
10270 case ISD::FP_TO_UINT:
10271 return performFpToIntCombine(N, DAG, DCI, Subtarget);
10273 return performFDivCombine(N, DAG, DCI, Subtarget);
10275 return performORCombine(N, DCI, Subtarget);
10277 return performSRLCombine(N, DCI);
10278 case ISD::INTRINSIC_WO_CHAIN:
10279 return performIntrinsicCombine(N, DCI, Subtarget);
10280 case ISD::ANY_EXTEND:
10281 case ISD::ZERO_EXTEND:
10282 case ISD::SIGN_EXTEND:
10283 return performExtendCombine(N, DCI, DAG);
10285 return performBitcastCombine(N, DCI, DAG);
10286 case ISD::CONCAT_VECTORS:
10287 return performConcatVectorsCombine(N, DCI, DAG);
10289 return performSelectCombine(N, DCI);
10291 return performVSelectCombine(N, DCI.DAG);
10293 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10294 return SDValue(N, 0);
10297 return performSTORECombine(N, DCI, DAG, Subtarget);
10298 case AArch64ISD::BRCOND:
10299 return performBRCONDCombine(N, DCI, DAG);
10300 case AArch64ISD::TBNZ:
10301 case AArch64ISD::TBZ:
10302 return performTBZCombine(N, DCI, DAG);
10303 case AArch64ISD::CSEL:
10304 return performCONDCombine(N, DCI, DAG, 2, 3);
10305 case AArch64ISD::DUP:
10306 return performPostLD1Combine(N, DCI, false);
10307 case AArch64ISD::NVCAST:
10308 return performNVCASTCombine(N);
10309 case ISD::INSERT_VECTOR_ELT:
10310 return performPostLD1Combine(N, DCI, true);
10311 case ISD::INTRINSIC_VOID:
10312 case ISD::INTRINSIC_W_CHAIN:
10313 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10314 case Intrinsic::aarch64_neon_ld2:
10315 case Intrinsic::aarch64_neon_ld3:
10316 case Intrinsic::aarch64_neon_ld4:
10317 case Intrinsic::aarch64_neon_ld1x2:
10318 case Intrinsic::aarch64_neon_ld1x3:
10319 case Intrinsic::aarch64_neon_ld1x4:
10320 case Intrinsic::aarch64_neon_ld2lane:
10321 case Intrinsic::aarch64_neon_ld3lane:
10322 case Intrinsic::aarch64_neon_ld4lane:
10323 case Intrinsic::aarch64_neon_ld2r:
10324 case Intrinsic::aarch64_neon_ld3r:
10325 case Intrinsic::aarch64_neon_ld4r:
10326 case Intrinsic::aarch64_neon_st2:
10327 case Intrinsic::aarch64_neon_st3:
10328 case Intrinsic::aarch64_neon_st4:
10329 case Intrinsic::aarch64_neon_st1x2:
10330 case Intrinsic::aarch64_neon_st1x3:
10331 case Intrinsic::aarch64_neon_st1x4:
10332 case Intrinsic::aarch64_neon_st2lane:
10333 case Intrinsic::aarch64_neon_st3lane:
10334 case Intrinsic::aarch64_neon_st4lane:
10335 return performNEONPostLDSTCombine(N, DCI, DAG);
10343 // Check if the return value is used as only a return value, as otherwise
10344 // we can't perform a tail-call. In particular, we need to check for
10345 // target ISD nodes that are returns and any other "odd" constructs
10346 // that the generic analysis code won't necessarily catch.
10347 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10348 SDValue &Chain) const {
10349 if (N->getNumValues() != 1)
10351 if (!N->hasNUsesOfValue(1, 0))
10354 SDValue TCChain = Chain;
10355 SDNode *Copy = *N->use_begin();
10356 if (Copy->getOpcode() == ISD::CopyToReg) {
10357 // If the copy has a glue operand, we conservatively assume it isn't safe to
10358 // perform a tail call.
10359 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10362 TCChain = Copy->getOperand(0);
10363 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10366 bool HasRet = false;
10367 for (SDNode *Node : Copy->uses()) {
10368 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10380 // Return whether the an instruction can potentially be optimized to a tail
10381 // call. This will cause the optimizers to attempt to move, or duplicate,
10382 // return instructions to help enable tail call optimizations for this
10384 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10385 return CI->isTailCall();
10388 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10390 ISD::MemIndexedMode &AM,
10392 SelectionDAG &DAG) const {
10393 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10396 Base = Op->getOperand(0);
10397 // All of the indexed addressing mode instructions take a signed
10398 // 9 bit immediate offset.
10399 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10400 int64_t RHSC = RHS->getSExtValue();
10401 if (Op->getOpcode() == ISD::SUB)
10402 RHSC = -(uint64_t)RHSC;
10403 if (!isInt<9>(RHSC))
10405 IsInc = (Op->getOpcode() == ISD::ADD);
10406 Offset = Op->getOperand(1);
10412 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10414 ISD::MemIndexedMode &AM,
10415 SelectionDAG &DAG) const {
10418 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10419 VT = LD->getMemoryVT();
10420 Ptr = LD->getBasePtr();
10421 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10422 VT = ST->getMemoryVT();
10423 Ptr = ST->getBasePtr();
10428 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10430 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10434 bool AArch64TargetLowering::getPostIndexedAddressParts(
10435 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10436 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10439 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10440 VT = LD->getMemoryVT();
10441 Ptr = LD->getBasePtr();
10442 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10443 VT = ST->getMemoryVT();
10444 Ptr = ST->getBasePtr();
10449 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10451 // Post-indexing updates the base, so it's not a valid transform
10452 // if that's not the same as the load's pointer.
10455 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10459 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10460 SelectionDAG &DAG) {
10462 SDValue Op = N->getOperand(0);
10464 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10468 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10469 DAG.getUNDEF(MVT::i32), Op,
10470 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10472 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10473 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10476 static void ReplaceReductionResults(SDNode *N,
10477 SmallVectorImpl<SDValue> &Results,
10478 SelectionDAG &DAG, unsigned InterOp,
10479 unsigned AcrossOp) {
10483 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10484 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10485 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10486 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10487 Results.push_back(SplitVal);
10490 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10492 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10493 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10494 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10495 DAG.getConstant(64, DL, MVT::i64)));
10496 return std::make_pair(Lo, Hi);
10499 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10500 SmallVectorImpl<SDValue> & Results,
10501 SelectionDAG &DAG) {
10502 assert(N->getValueType(0) == MVT::i128 &&
10503 "AtomicCmpSwap on types less than 128 should be legal");
10504 auto Desired = splitInt128(N->getOperand(2), DAG);
10505 auto New = splitInt128(N->getOperand(3), DAG);
10506 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10507 New.first, New.second, N->getOperand(0)};
10508 SDNode *CmpSwap = DAG.getMachineNode(
10509 AArch64::CMP_SWAP_128, SDLoc(N),
10510 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10512 MachineFunction &MF = DAG.getMachineFunction();
10513 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10514 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10515 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10517 Results.push_back(SDValue(CmpSwap, 0));
10518 Results.push_back(SDValue(CmpSwap, 1));
10519 Results.push_back(SDValue(CmpSwap, 3));
10522 void AArch64TargetLowering::ReplaceNodeResults(
10523 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10524 switch (N->getOpcode()) {
10526 llvm_unreachable("Don't know how to custom expand this");
10528 ReplaceBITCASTResults(N, Results, DAG);
10530 case ISD::VECREDUCE_ADD:
10531 case ISD::VECREDUCE_SMAX:
10532 case ISD::VECREDUCE_SMIN:
10533 case ISD::VECREDUCE_UMAX:
10534 case ISD::VECREDUCE_UMIN:
10535 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
10538 case AArch64ISD::SADDV:
10539 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10541 case AArch64ISD::UADDV:
10542 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10544 case AArch64ISD::SMINV:
10545 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10547 case AArch64ISD::UMINV:
10548 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10550 case AArch64ISD::SMAXV:
10551 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10553 case AArch64ISD::UMAXV:
10554 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10556 case ISD::FP_TO_UINT:
10557 case ISD::FP_TO_SINT:
10558 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10559 // Let normal code take care of it by not adding anything to Results.
10561 case ISD::ATOMIC_CMP_SWAP:
10562 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10567 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10568 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10569 return TargetLowering::useLoadStackGuardNode();
10573 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10574 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10575 // reciprocal if there are three or more FDIVs.
10579 TargetLoweringBase::LegalizeTypeAction
10580 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10581 MVT SVT = VT.getSimpleVT();
10582 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10583 // v4i16, v2i32 instead of to promote.
10584 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10585 || SVT == MVT::v1f32)
10586 return TypeWidenVector;
10588 return TargetLoweringBase::getPreferredVectorAction(VT);
10591 // Loads and stores less than 128-bits are already atomic; ones above that
10592 // are doomed anyway, so defer to the default libcall and blame the OS when
10593 // things go wrong.
10594 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10595 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10596 return Size == 128;
10599 // Loads and stores less than 128-bits are already atomic; ones above that
10600 // are doomed anyway, so defer to the default libcall and blame the OS when
10601 // things go wrong.
10602 TargetLowering::AtomicExpansionKind
10603 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10604 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10605 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10608 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10609 TargetLowering::AtomicExpansionKind
10610 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10611 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10612 if (Size > 128) return AtomicExpansionKind::None;
10613 // Nand not supported in LSE.
10614 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
10615 // Leave 128 bits to LLSC.
10616 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
10619 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10620 AtomicCmpXchgInst *AI) const {
10621 // If subtarget has LSE, leave cmpxchg intact for codegen.
10622 if (Subtarget->hasLSE()) return false;
10623 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10624 // implement cmpxchg without spilling. If the address being exchanged is also
10625 // on the stack and close enough to the spill slot, this can lead to a
10626 // situation where the monitor always gets cleared and the atomic operation
10627 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10628 return getTargetMachine().getOptLevel() != 0;
10631 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10632 AtomicOrdering Ord) const {
10633 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10634 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10635 bool IsAcquire = isAcquireOrStronger(Ord);
10637 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10638 // intrinsic must return {i64, i64} and we have to recombine them into a
10639 // single i128 here.
10640 if (ValTy->getPrimitiveSizeInBits() == 128) {
10641 Intrinsic::ID Int =
10642 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10643 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10645 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10646 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10648 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10649 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10650 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10651 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10652 return Builder.CreateOr(
10653 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10656 Type *Tys[] = { Addr->getType() };
10657 Intrinsic::ID Int =
10658 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10659 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10661 return Builder.CreateTruncOrBitCast(
10662 Builder.CreateCall(Ldxr, Addr),
10663 cast<PointerType>(Addr->getType())->getElementType());
10666 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10667 IRBuilder<> &Builder) const {
10668 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10669 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10672 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10673 Value *Val, Value *Addr,
10674 AtomicOrdering Ord) const {
10675 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10676 bool IsRelease = isReleaseOrStronger(Ord);
10678 // Since the intrinsics must have legal type, the i128 intrinsics take two
10679 // parameters: "i64, i64". We must marshal Val into the appropriate form
10680 // before the call.
10681 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10682 Intrinsic::ID Int =
10683 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10684 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10685 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10687 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10688 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10689 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10690 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10693 Intrinsic::ID Int =
10694 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10695 Type *Tys[] = { Addr->getType() };
10696 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10698 return Builder.CreateCall(Stxr,
10699 {Builder.CreateZExtOrBitCast(
10700 Val, Stxr->getFunctionType()->getParamType(0)),
10704 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10705 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10706 return Ty->isArrayTy();
10709 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10714 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
10715 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10716 Function *ThreadPointerFunc =
10717 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10718 return IRB.CreatePointerCast(
10719 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
10720 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10723 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10724 // Android provides a fixed TLS slot for the stack cookie. See the definition
10725 // of TLS_SLOT_STACK_GUARD in
10726 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10727 if (Subtarget->isTargetAndroid())
10728 return UseTlsOffset(IRB, 0x28);
10730 // Fuchsia is similar.
10731 // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10732 if (Subtarget->isTargetFuchsia())
10733 return UseTlsOffset(IRB, -0x10);
10735 return TargetLowering::getIRStackGuard(IRB);
10738 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10739 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10740 // definition of TLS_SLOT_SAFESTACK in
10741 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10742 if (Subtarget->isTargetAndroid())
10743 return UseTlsOffset(IRB, 0x48);
10745 // Fuchsia is similar.
10746 // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10747 if (Subtarget->isTargetFuchsia())
10748 return UseTlsOffset(IRB, -0x8);
10750 return TargetLowering::getSafeStackPointerLocation(IRB);
10753 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10754 const Instruction &AndI) const {
10755 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10756 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10757 // may be beneficial to sink in other cases, but we would have to check that
10758 // the cmp would not get folded into the br to form a cbz for these to be
10760 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10763 return Mask->getUniqueInteger().isPowerOf2();
10766 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10767 // Update IsSplitCSR in AArch64unctionInfo.
10768 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10769 AFI->setIsSplitCSR(true);
10772 void AArch64TargetLowering::insertCopiesSplitCSR(
10773 MachineBasicBlock *Entry,
10774 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10775 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10776 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10780 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10781 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10782 MachineBasicBlock::iterator MBBI = Entry->begin();
10783 for (const MCPhysReg *I = IStart; *I; ++I) {
10784 const TargetRegisterClass *RC = nullptr;
10785 if (AArch64::GPR64RegClass.contains(*I))
10786 RC = &AArch64::GPR64RegClass;
10787 else if (AArch64::FPR64RegClass.contains(*I))
10788 RC = &AArch64::FPR64RegClass;
10790 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10792 unsigned NewVR = MRI->createVirtualRegister(RC);
10793 // Create copy from CSR to a virtual register.
10794 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10795 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10796 // nounwind. If we want to generalize this later, we may need to emit
10797 // CFI pseudo-instructions.
10798 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10799 Attribute::NoUnwind) &&
10800 "Function should be nounwind in insertCopiesSplitCSR!");
10801 Entry->addLiveIn(*I);
10802 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10805 // Insert the copy-back instructions right before the terminator.
10806 for (auto *Exit : Exits)
10807 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10808 TII->get(TargetOpcode::COPY), *I)
10813 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
10814 // Integer division on AArch64 is expensive. However, when aggressively
10815 // optimizing for code size, we prefer to use a div instruction, as it is
10816 // usually smaller than the alternative sequence.
10817 // The exception to this is vector division. Since AArch64 doesn't have vector
10818 // integer division, leaving the division as-is is a loss even in terms of
10819 // size, because it will have to be scalarized, while the alternative code
10820 // sequence can be performed in vector form.
10822 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
10823 return OptSize && !VT.isVector();
10827 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10828 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
10829 return getPointerTy(DL).getSizeInBits();
10831 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;