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 "AArch64CallingConvention.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64ISelLowering.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/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.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/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/IRBuilder.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/MathExtras.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Target/TargetCallingConv.h"
73 #include "llvm/Target/TargetInstrInfo.h"
74 #include "llvm/Target/TargetMachine.h"
75 #include "llvm/Target/TargetOptions.h"
90 #define DEBUG_TYPE "aarch64-lower"
92 STATISTIC(NumTailCalls, "Number of tail calls");
93 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
96 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
97 cl::desc("Allow AArch64 SLI/SRI formation"),
100 // FIXME: The necessary dtprel relocations don't seem to be supported
101 // well in the GNU bfd and gold linkers at the moment. Therefore, by
102 // default, for now, fall back to GeneralDynamic code generation.
103 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
104 "aarch64-elf-ldtls-generation", cl::Hidden,
105 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108 /// Value type used for condition codes.
109 static const MVT MVT_CC = MVT::i32;
111 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
112 const AArch64Subtarget &STI)
113 : TargetLowering(TM), Subtarget(&STI) {
114 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
115 // we have to make something up. Arbitrarily, choose ZeroOrOne.
116 setBooleanContents(ZeroOrOneBooleanContent);
117 // When comparing vectors the result sets the different elements in the
118 // vector to all-one or all-zero.
119 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
121 // Set up the register classes.
122 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
123 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
125 if (Subtarget->hasFPARMv8()) {
126 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
127 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
128 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
129 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
132 if (Subtarget->hasNEON()) {
133 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
134 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
135 // Someone set us up the NEON.
136 addDRTypeForNEON(MVT::v2f32);
137 addDRTypeForNEON(MVT::v8i8);
138 addDRTypeForNEON(MVT::v4i16);
139 addDRTypeForNEON(MVT::v2i32);
140 addDRTypeForNEON(MVT::v1i64);
141 addDRTypeForNEON(MVT::v1f64);
142 addDRTypeForNEON(MVT::v4f16);
144 addQRTypeForNEON(MVT::v4f32);
145 addQRTypeForNEON(MVT::v2f64);
146 addQRTypeForNEON(MVT::v16i8);
147 addQRTypeForNEON(MVT::v8i16);
148 addQRTypeForNEON(MVT::v4i32);
149 addQRTypeForNEON(MVT::v2i64);
150 addQRTypeForNEON(MVT::v8f16);
153 // Compute derived properties from the register classes
154 computeRegisterProperties(Subtarget->getRegisterInfo());
156 // Provide all sorts of operation actions
157 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
158 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
159 setOperationAction(ISD::SETCC, MVT::i32, Custom);
160 setOperationAction(ISD::SETCC, MVT::i64, Custom);
161 setOperationAction(ISD::SETCC, MVT::f32, Custom);
162 setOperationAction(ISD::SETCC, MVT::f64, Custom);
163 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
164 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
165 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
166 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
167 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
168 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
169 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
170 setOperationAction(ISD::SELECT, MVT::i32, Custom);
171 setOperationAction(ISD::SELECT, MVT::i64, Custom);
172 setOperationAction(ISD::SELECT, MVT::f32, Custom);
173 setOperationAction(ISD::SELECT, MVT::f64, Custom);
174 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
175 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
176 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
177 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
178 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
181 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
182 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
183 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
185 setOperationAction(ISD::FREM, MVT::f32, Expand);
186 setOperationAction(ISD::FREM, MVT::f64, Expand);
187 setOperationAction(ISD::FREM, MVT::f80, Expand);
189 // Custom lowering hooks are needed for XOR
190 // to fold it into CSINC/CSINV.
191 setOperationAction(ISD::XOR, MVT::i32, Custom);
192 setOperationAction(ISD::XOR, MVT::i64, Custom);
194 // Virtually no operation on f128 is legal, but LLVM can't expand them when
195 // there's a valid register class, so we need custom operations in most cases.
196 setOperationAction(ISD::FABS, MVT::f128, Expand);
197 setOperationAction(ISD::FADD, MVT::f128, Custom);
198 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
199 setOperationAction(ISD::FCOS, MVT::f128, Expand);
200 setOperationAction(ISD::FDIV, MVT::f128, Custom);
201 setOperationAction(ISD::FMA, MVT::f128, Expand);
202 setOperationAction(ISD::FMUL, MVT::f128, Custom);
203 setOperationAction(ISD::FNEG, MVT::f128, Expand);
204 setOperationAction(ISD::FPOW, MVT::f128, Expand);
205 setOperationAction(ISD::FREM, MVT::f128, Expand);
206 setOperationAction(ISD::FRINT, MVT::f128, Expand);
207 setOperationAction(ISD::FSIN, MVT::f128, Expand);
208 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
209 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
210 setOperationAction(ISD::FSUB, MVT::f128, Custom);
211 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
212 setOperationAction(ISD::SETCC, MVT::f128, Custom);
213 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
214 setOperationAction(ISD::SELECT, MVT::f128, Custom);
215 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
216 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
218 // Lowering for many of the conversions is actually specified by the non-f128
219 // type. The LowerXXX function will be trivial when f128 isn't involved.
220 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
221 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
222 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
223 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
224 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
225 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
226 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
227 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
228 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
229 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
230 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
231 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
232 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
233 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
235 // Variable arguments.
236 setOperationAction(ISD::VASTART, MVT::Other, Custom);
237 setOperationAction(ISD::VAARG, MVT::Other, Custom);
238 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
239 setOperationAction(ISD::VAEND, MVT::Other, Expand);
241 // Variable-sized objects.
242 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
243 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
244 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
246 // Constant pool entries
247 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
250 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
252 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
253 setOperationAction(ISD::ADDC, MVT::i32, Custom);
254 setOperationAction(ISD::ADDE, MVT::i32, Custom);
255 setOperationAction(ISD::SUBC, MVT::i32, Custom);
256 setOperationAction(ISD::SUBE, MVT::i32, Custom);
257 setOperationAction(ISD::ADDC, MVT::i64, Custom);
258 setOperationAction(ISD::ADDE, MVT::i64, Custom);
259 setOperationAction(ISD::SUBC, MVT::i64, Custom);
260 setOperationAction(ISD::SUBE, MVT::i64, Custom);
262 // AArch64 lacks both left-rotate and popcount instructions.
263 setOperationAction(ISD::ROTL, MVT::i32, Expand);
264 setOperationAction(ISD::ROTL, MVT::i64, Expand);
265 for (MVT VT : MVT::vector_valuetypes()) {
266 setOperationAction(ISD::ROTL, VT, Expand);
267 setOperationAction(ISD::ROTR, VT, Expand);
270 // AArch64 doesn't have {U|S}MUL_LOHI.
271 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
272 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
274 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
275 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
277 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
278 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
279 for (MVT VT : MVT::vector_valuetypes()) {
280 setOperationAction(ISD::SDIVREM, VT, Expand);
281 setOperationAction(ISD::UDIVREM, VT, Expand);
283 setOperationAction(ISD::SREM, MVT::i32, Expand);
284 setOperationAction(ISD::SREM, MVT::i64, Expand);
285 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
286 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287 setOperationAction(ISD::UREM, MVT::i32, Expand);
288 setOperationAction(ISD::UREM, MVT::i64, Expand);
290 // Custom lower Add/Sub/Mul with overflow.
291 setOperationAction(ISD::SADDO, MVT::i32, Custom);
292 setOperationAction(ISD::SADDO, MVT::i64, Custom);
293 setOperationAction(ISD::UADDO, MVT::i32, Custom);
294 setOperationAction(ISD::UADDO, MVT::i64, Custom);
295 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
296 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
297 setOperationAction(ISD::USUBO, MVT::i32, Custom);
298 setOperationAction(ISD::USUBO, MVT::i64, Custom);
299 setOperationAction(ISD::SMULO, MVT::i32, Custom);
300 setOperationAction(ISD::SMULO, MVT::i64, Custom);
301 setOperationAction(ISD::UMULO, MVT::i32, Custom);
302 setOperationAction(ISD::UMULO, MVT::i64, Custom);
304 setOperationAction(ISD::FSIN, MVT::f32, Expand);
305 setOperationAction(ISD::FSIN, MVT::f64, Expand);
306 setOperationAction(ISD::FCOS, MVT::f32, Expand);
307 setOperationAction(ISD::FCOS, MVT::f64, Expand);
308 setOperationAction(ISD::FPOW, MVT::f32, Expand);
309 setOperationAction(ISD::FPOW, MVT::f64, Expand);
310 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
311 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
313 // f16 is a storage-only type, always promote it to f32.
314 setOperationAction(ISD::SETCC, MVT::f16, Promote);
315 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
316 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
317 setOperationAction(ISD::SELECT, MVT::f16, Promote);
318 setOperationAction(ISD::FADD, MVT::f16, Promote);
319 setOperationAction(ISD::FSUB, MVT::f16, Promote);
320 setOperationAction(ISD::FMUL, MVT::f16, Promote);
321 setOperationAction(ISD::FDIV, MVT::f16, Promote);
322 setOperationAction(ISD::FREM, MVT::f16, Promote);
323 setOperationAction(ISD::FMA, MVT::f16, Promote);
324 setOperationAction(ISD::FNEG, MVT::f16, Promote);
325 setOperationAction(ISD::FABS, MVT::f16, Promote);
326 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
327 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
328 setOperationAction(ISD::FCOS, MVT::f16, Promote);
329 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
330 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
331 setOperationAction(ISD::FPOW, MVT::f16, Promote);
332 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
333 setOperationAction(ISD::FRINT, MVT::f16, Promote);
334 setOperationAction(ISD::FSIN, MVT::f16, Promote);
335 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
336 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
337 setOperationAction(ISD::FEXP, MVT::f16, Promote);
338 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
339 setOperationAction(ISD::FLOG, MVT::f16, Promote);
340 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
341 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
342 setOperationAction(ISD::FROUND, MVT::f16, Promote);
343 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
344 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
345 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
346 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
347 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
349 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
351 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
352 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
353 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
354 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
355 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
356 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
357 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
358 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
359 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
360 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
361 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
362 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
364 // Expand all other v4f16 operations.
365 // FIXME: We could generate better code by promoting some operations to
367 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
368 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
369 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
370 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
371 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
372 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
373 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
374 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
375 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
376 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
377 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
378 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
379 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
380 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
381 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
382 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
383 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
384 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
385 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
386 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
387 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
388 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
389 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
390 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
391 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
392 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
395 // v8f16 is also a storage-only type, so expand it.
396 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
397 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
398 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
399 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
400 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
401 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
402 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
403 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
404 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
405 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
406 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
407 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
408 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
409 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
410 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
411 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
412 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
413 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
414 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
415 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
416 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
417 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
418 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
419 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
420 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
421 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
422 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
423 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
424 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
425 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
426 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
428 // AArch64 has implementations of a lot of rounding-like FP operations.
429 for (MVT Ty : {MVT::f32, MVT::f64}) {
430 setOperationAction(ISD::FFLOOR, Ty, Legal);
431 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
432 setOperationAction(ISD::FCEIL, Ty, Legal);
433 setOperationAction(ISD::FRINT, Ty, Legal);
434 setOperationAction(ISD::FTRUNC, Ty, Legal);
435 setOperationAction(ISD::FROUND, Ty, Legal);
436 setOperationAction(ISD::FMINNUM, Ty, Legal);
437 setOperationAction(ISD::FMAXNUM, Ty, Legal);
438 setOperationAction(ISD::FMINNAN, Ty, Legal);
439 setOperationAction(ISD::FMAXNAN, Ty, Legal);
442 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
444 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
446 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
447 // This requires the Performance Monitors extension.
448 if (Subtarget->hasPerfMon())
449 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
451 if (Subtarget->isTargetMachO()) {
452 // For iOS, we don't want to the normal expansion of a libcall to
453 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
455 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
456 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
458 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
459 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
462 // Make floating-point constants legal for the large code model, so they don't
463 // become loads from the constant pool.
464 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
465 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
466 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
469 // AArch64 does not have floating-point extending loads, i1 sign-extending
470 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
471 for (MVT VT : MVT::fp_valuetypes()) {
472 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
473 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
474 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
475 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
477 for (MVT VT : MVT::integer_valuetypes())
478 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
480 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
481 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
482 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
483 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
484 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
485 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
486 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
488 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
489 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
491 // Indexed loads and stores are supported.
492 for (unsigned im = (unsigned)ISD::PRE_INC;
493 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
494 setIndexedLoadAction(im, MVT::i8, Legal);
495 setIndexedLoadAction(im, MVT::i16, Legal);
496 setIndexedLoadAction(im, MVT::i32, Legal);
497 setIndexedLoadAction(im, MVT::i64, Legal);
498 setIndexedLoadAction(im, MVT::f64, Legal);
499 setIndexedLoadAction(im, MVT::f32, Legal);
500 setIndexedLoadAction(im, MVT::f16, Legal);
501 setIndexedStoreAction(im, MVT::i8, Legal);
502 setIndexedStoreAction(im, MVT::i16, Legal);
503 setIndexedStoreAction(im, MVT::i32, Legal);
504 setIndexedStoreAction(im, MVT::i64, Legal);
505 setIndexedStoreAction(im, MVT::f64, Legal);
506 setIndexedStoreAction(im, MVT::f32, Legal);
507 setIndexedStoreAction(im, MVT::f16, Legal);
511 setOperationAction(ISD::TRAP, MVT::Other, Legal);
513 // We combine OR nodes for bitfield operations.
514 setTargetDAGCombine(ISD::OR);
516 // Vector add and sub nodes may conceal a high-half opportunity.
517 // Also, try to fold ADD into CSINC/CSINV..
518 setTargetDAGCombine(ISD::ADD);
519 setTargetDAGCombine(ISD::SUB);
520 setTargetDAGCombine(ISD::SRL);
521 setTargetDAGCombine(ISD::XOR);
522 setTargetDAGCombine(ISD::SINT_TO_FP);
523 setTargetDAGCombine(ISD::UINT_TO_FP);
525 setTargetDAGCombine(ISD::FP_TO_SINT);
526 setTargetDAGCombine(ISD::FP_TO_UINT);
527 setTargetDAGCombine(ISD::FDIV);
529 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
531 setTargetDAGCombine(ISD::ANY_EXTEND);
532 setTargetDAGCombine(ISD::ZERO_EXTEND);
533 setTargetDAGCombine(ISD::SIGN_EXTEND);
534 setTargetDAGCombine(ISD::BITCAST);
535 setTargetDAGCombine(ISD::CONCAT_VECTORS);
536 setTargetDAGCombine(ISD::STORE);
537 if (Subtarget->supportsAddressTopByteIgnored())
538 setTargetDAGCombine(ISD::LOAD);
540 setTargetDAGCombine(ISD::MUL);
542 setTargetDAGCombine(ISD::SELECT);
543 setTargetDAGCombine(ISD::VSELECT);
545 setTargetDAGCombine(ISD::INTRINSIC_VOID);
546 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
547 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
548 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
550 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
551 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
552 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
554 setStackPointerRegisterToSaveRestore(AArch64::SP);
556 setSchedulingPreference(Sched::Hybrid);
558 EnableExtLdPromotion = true;
560 // Set required alignment.
561 setMinFunctionAlignment(2);
562 // Set preferred alignments.
563 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
564 setPrefLoopAlignment(STI.getPrefLoopAlignment());
566 // Only change the limit for entries in a jump table if specified by
567 // the subtarget, but not at the command line.
568 unsigned MaxJT = STI.getMaximumJumpTableSize();
569 if (MaxJT && getMaximumJumpTableSize() == 0)
570 setMaximumJumpTableSize(MaxJT);
572 setHasExtractBitsInsn(true);
574 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
576 if (Subtarget->hasNEON()) {
577 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
578 // silliness like this:
579 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
580 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
581 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
582 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
583 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
584 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
585 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
586 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
587 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
588 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
589 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
590 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
591 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
592 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
593 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
594 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
595 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
596 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
597 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
598 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
599 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
600 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
601 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
602 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
603 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
605 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
606 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
607 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
608 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
609 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
611 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
613 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
614 // elements smaller than i32, so promote the input to i32 first.
615 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
616 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
617 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
618 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
619 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
620 // -> v8f16 conversions.
621 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
622 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
623 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
624 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
625 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
626 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
627 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
628 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
629 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
630 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
631 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
632 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
633 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
635 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
636 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
638 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
639 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
640 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
641 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
642 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
643 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
644 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
645 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
647 // AArch64 doesn't have MUL.2d:
648 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
649 // Custom handling for some quad-vector types to detect MULL.
650 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
651 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
652 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
654 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
655 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
656 // Likewise, narrowing and extending vector loads/stores aren't handled
658 for (MVT VT : MVT::vector_valuetypes()) {
659 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
661 setOperationAction(ISD::MULHS, VT, Expand);
662 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
663 setOperationAction(ISD::MULHU, VT, Expand);
664 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
666 setOperationAction(ISD::BSWAP, VT, Expand);
668 for (MVT InnerVT : MVT::vector_valuetypes()) {
669 setTruncStoreAction(VT, InnerVT, Expand);
670 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
671 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
672 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
676 // AArch64 has implementations of a lot of rounding-like FP operations.
677 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
678 setOperationAction(ISD::FFLOOR, Ty, Legal);
679 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
680 setOperationAction(ISD::FCEIL, Ty, Legal);
681 setOperationAction(ISD::FRINT, Ty, Legal);
682 setOperationAction(ISD::FTRUNC, Ty, Legal);
683 setOperationAction(ISD::FROUND, Ty, Legal);
687 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
690 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
691 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
692 setOperationAction(ISD::LOAD, VT, Promote);
693 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
695 setOperationAction(ISD::STORE, VT, Promote);
696 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
697 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
698 setOperationAction(ISD::LOAD, VT, Promote);
699 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
701 setOperationAction(ISD::STORE, VT, Promote);
702 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
705 // Mark vector float intrinsics as expand.
706 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
707 setOperationAction(ISD::FSIN, VT, Expand);
708 setOperationAction(ISD::FCOS, VT, Expand);
709 setOperationAction(ISD::FPOWI, VT, Expand);
710 setOperationAction(ISD::FPOW, VT, Expand);
711 setOperationAction(ISD::FLOG, VT, Expand);
712 setOperationAction(ISD::FLOG2, VT, Expand);
713 setOperationAction(ISD::FLOG10, VT, Expand);
714 setOperationAction(ISD::FEXP, VT, Expand);
715 setOperationAction(ISD::FEXP2, VT, Expand);
717 // But we do support custom-lowering for FCOPYSIGN.
718 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
721 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
722 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
723 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
724 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
725 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
726 setOperationAction(ISD::SRA, VT, Custom);
727 setOperationAction(ISD::SRL, VT, Custom);
728 setOperationAction(ISD::SHL, VT, Custom);
729 setOperationAction(ISD::AND, VT, Custom);
730 setOperationAction(ISD::OR, VT, Custom);
731 setOperationAction(ISD::SETCC, VT, Custom);
732 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
734 setOperationAction(ISD::SELECT, VT, Expand);
735 setOperationAction(ISD::SELECT_CC, VT, Expand);
736 setOperationAction(ISD::VSELECT, VT, Expand);
737 for (MVT InnerVT : MVT::all_valuetypes())
738 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
740 // CNT supports only B element sizes.
741 if (VT != MVT::v8i8 && VT != MVT::v16i8)
742 setOperationAction(ISD::CTPOP, VT, Expand);
744 setOperationAction(ISD::UDIV, VT, Expand);
745 setOperationAction(ISD::SDIV, VT, Expand);
746 setOperationAction(ISD::UREM, VT, Expand);
747 setOperationAction(ISD::SREM, VT, Expand);
748 setOperationAction(ISD::FREM, VT, Expand);
750 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
751 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
753 // [SU][MIN|MAX] are available for all NEON types apart from i64.
754 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
755 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
756 setOperationAction(Opcode, VT, Legal);
758 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
759 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
760 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
761 ISD::FMINNUM, ISD::FMAXNUM})
762 setOperationAction(Opcode, VT, Legal);
764 if (Subtarget->isLittleEndian()) {
765 for (unsigned im = (unsigned)ISD::PRE_INC;
766 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
767 setIndexedLoadAction(im, VT, Legal);
768 setIndexedStoreAction(im, VT, Legal);
773 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
774 addRegisterClass(VT, &AArch64::FPR64RegClass);
775 addTypeForNEON(VT, MVT::v2i32);
778 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
779 addRegisterClass(VT, &AArch64::FPR128RegClass);
780 addTypeForNEON(VT, MVT::v4i32);
783 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
787 return VT.changeVectorElementTypeToInteger();
790 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
791 /// Mask are known to be either zero or one and return them in the
792 /// KnownZero/KnownOne bitsets.
793 void AArch64TargetLowering::computeKnownBitsForTargetNode(
794 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
795 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
796 switch (Op.getOpcode()) {
799 case AArch64ISD::CSEL: {
800 APInt KnownZero2, KnownOne2;
801 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
802 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
803 KnownZero &= KnownZero2;
804 KnownOne &= KnownOne2;
807 case ISD::INTRINSIC_W_CHAIN: {
808 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
809 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
812 case Intrinsic::aarch64_ldaxr:
813 case Intrinsic::aarch64_ldxr: {
814 unsigned BitWidth = KnownOne.getBitWidth();
815 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
816 unsigned MemBits = VT.getScalarSizeInBits();
817 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
823 case ISD::INTRINSIC_WO_CHAIN:
824 case ISD::INTRINSIC_VOID: {
825 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
829 case Intrinsic::aarch64_neon_umaxv:
830 case Intrinsic::aarch64_neon_uminv: {
831 // Figure out the datatype of the vector operand. The UMINV instruction
832 // will zero extend the result, so we can mark as known zero all the
833 // bits larger than the element datatype. 32-bit or larget doesn't need
834 // this as those are legal types and will be handled by isel directly.
835 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
836 unsigned BitWidth = KnownZero.getBitWidth();
837 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
838 assert(BitWidth >= 8 && "Unexpected width!");
839 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
841 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
842 assert(BitWidth >= 16 && "Unexpected width!");
843 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
853 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
858 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
862 if (Subtarget->requiresStrictAlign())
866 // Some CPUs are fine with unaligned stores except for 128-bit ones.
867 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
868 // See comments in performSTORECombine() for more details about
871 // Code that uses clang vector extensions can mark that it
872 // wants unaligned accesses to be treated as fast by
873 // underspecifying alignment to be 1 or 2.
876 // Disregard v2i64. Memcpy lowering produces those and splitting
877 // them regresses performance on micro-benchmarks and olden/bh.
884 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
885 const TargetLibraryInfo *libInfo) const {
886 return AArch64::createFastISel(funcInfo, libInfo);
889 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
890 switch ((AArch64ISD::NodeType)Opcode) {
891 case AArch64ISD::FIRST_NUMBER: break;
892 case AArch64ISD::CALL: return "AArch64ISD::CALL";
893 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
894 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
895 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
896 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
897 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
898 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
899 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
900 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
901 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
902 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
903 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
904 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
905 case AArch64ISD::ADC: return "AArch64ISD::ADC";
906 case AArch64ISD::SBC: return "AArch64ISD::SBC";
907 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
908 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
909 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
910 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
911 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
912 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
913 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
914 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
915 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
916 case AArch64ISD::DUP: return "AArch64ISD::DUP";
917 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
918 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
919 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
920 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
921 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
922 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
923 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
924 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
925 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
926 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
927 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
928 case AArch64ISD::BICi: return "AArch64ISD::BICi";
929 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
930 case AArch64ISD::BSL: return "AArch64ISD::BSL";
931 case AArch64ISD::NEG: return "AArch64ISD::NEG";
932 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
933 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
934 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
935 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
936 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
937 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
938 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
939 case AArch64ISD::REV16: return "AArch64ISD::REV16";
940 case AArch64ISD::REV32: return "AArch64ISD::REV32";
941 case AArch64ISD::REV64: return "AArch64ISD::REV64";
942 case AArch64ISD::EXT: return "AArch64ISD::EXT";
943 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
944 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
945 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
946 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
947 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
948 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
949 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
950 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
951 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
952 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
953 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
954 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
955 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
956 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
957 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
958 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
959 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
960 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
961 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
962 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
963 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
964 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
965 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
966 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
967 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
968 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
969 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
970 case AArch64ISD::NOT: return "AArch64ISD::NOT";
971 case AArch64ISD::BIT: return "AArch64ISD::BIT";
972 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
973 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
974 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
975 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
976 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
977 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
978 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
979 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
980 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
981 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
982 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
983 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
984 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
985 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
986 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
987 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
988 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
989 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
990 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
991 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
992 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
993 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
994 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
995 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
996 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
997 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
998 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
999 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1000 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1001 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1002 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1003 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1004 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1005 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1006 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1007 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1008 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1009 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1010 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1011 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1012 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1013 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1014 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1015 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1021 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1022 MachineBasicBlock *MBB) const {
1023 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1027 // [... previous instrs leading to comparison ...]
1033 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1035 MachineFunction *MF = MBB->getParent();
1036 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1037 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1038 DebugLoc DL = MI.getDebugLoc();
1039 MachineFunction::iterator It = ++MBB->getIterator();
1041 unsigned DestReg = MI.getOperand(0).getReg();
1042 unsigned IfTrueReg = MI.getOperand(1).getReg();
1043 unsigned IfFalseReg = MI.getOperand(2).getReg();
1044 unsigned CondCode = MI.getOperand(3).getImm();
1045 bool NZCVKilled = MI.getOperand(4).isKill();
1047 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1049 MF->insert(It, TrueBB);
1050 MF->insert(It, EndBB);
1052 // Transfer rest of current basic-block to EndBB
1053 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1055 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1057 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1058 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1059 MBB->addSuccessor(TrueBB);
1060 MBB->addSuccessor(EndBB);
1062 // TrueBB falls through to the end.
1063 TrueBB->addSuccessor(EndBB);
1066 TrueBB->addLiveIn(AArch64::NZCV);
1067 EndBB->addLiveIn(AArch64::NZCV);
1070 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1076 MI.eraseFromParent();
1080 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1081 MachineInstr &MI, MachineBasicBlock *BB) const {
1082 switch (MI.getOpcode()) {
1087 llvm_unreachable("Unexpected instruction for custom inserter!");
1089 case AArch64::F128CSEL:
1090 return EmitF128CSEL(MI, BB);
1092 case TargetOpcode::STACKMAP:
1093 case TargetOpcode::PATCHPOINT:
1094 return emitPatchPoint(MI, BB);
1098 //===----------------------------------------------------------------------===//
1099 // AArch64 Lowering private implementation.
1100 //===----------------------------------------------------------------------===//
1102 //===----------------------------------------------------------------------===//
1104 //===----------------------------------------------------------------------===//
1106 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1108 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1111 llvm_unreachable("Unknown condition code!");
1113 return AArch64CC::NE;
1115 return AArch64CC::EQ;
1117 return AArch64CC::GT;
1119 return AArch64CC::GE;
1121 return AArch64CC::LT;
1123 return AArch64CC::LE;
1125 return AArch64CC::HI;
1127 return AArch64CC::HS;
1129 return AArch64CC::LO;
1131 return AArch64CC::LS;
1135 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1136 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1137 AArch64CC::CondCode &CondCode,
1138 AArch64CC::CondCode &CondCode2) {
1139 CondCode2 = AArch64CC::AL;
1142 llvm_unreachable("Unknown FP condition!");
1145 CondCode = AArch64CC::EQ;
1149 CondCode = AArch64CC::GT;
1153 CondCode = AArch64CC::GE;
1156 CondCode = AArch64CC::MI;
1159 CondCode = AArch64CC::LS;
1162 CondCode = AArch64CC::MI;
1163 CondCode2 = AArch64CC::GT;
1166 CondCode = AArch64CC::VC;
1169 CondCode = AArch64CC::VS;
1172 CondCode = AArch64CC::EQ;
1173 CondCode2 = AArch64CC::VS;
1176 CondCode = AArch64CC::HI;
1179 CondCode = AArch64CC::PL;
1183 CondCode = AArch64CC::LT;
1187 CondCode = AArch64CC::LE;
1191 CondCode = AArch64CC::NE;
1196 /// Convert a DAG fp condition code to an AArch64 CC.
1197 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1198 /// should be AND'ed instead of OR'ed.
1199 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1200 AArch64CC::CondCode &CondCode,
1201 AArch64CC::CondCode &CondCode2) {
1202 CondCode2 = AArch64CC::AL;
1205 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1206 assert(CondCode2 == AArch64CC::AL);
1210 // == ((a olt b) || (a ogt b))
1211 // == ((a ord b) && (a une b))
1212 CondCode = AArch64CC::VC;
1213 CondCode2 = AArch64CC::NE;
1217 // == ((a uno b) || (a oeq b))
1218 // == ((a ule b) && (a uge b))
1219 CondCode = AArch64CC::PL;
1220 CondCode2 = AArch64CC::LE;
1225 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1226 /// CC usable with the vector instructions. Fewer operations are available
1227 /// without a real NZCV register, so we have to use less efficient combinations
1228 /// to get the same effect.
1229 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1230 AArch64CC::CondCode &CondCode,
1231 AArch64CC::CondCode &CondCode2,
1236 // Mostly the scalar mappings work fine.
1237 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1243 CondCode = AArch64CC::MI;
1244 CondCode2 = AArch64CC::GE;
1251 // All of the compare-mask comparisons are ordered, but we can switch
1252 // between the two by a double inversion. E.g. ULE == !OGT.
1254 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1259 static bool isLegalArithImmed(uint64_t C) {
1260 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1261 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1264 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1265 const SDLoc &dl, SelectionDAG &DAG) {
1266 EVT VT = LHS.getValueType();
1268 if (VT.isFloatingPoint()) {
1269 assert(VT != MVT::f128);
1270 if (VT == MVT::f16) {
1271 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1272 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1275 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1278 // The CMP instruction is just an alias for SUBS, and representing it as
1279 // SUBS means that it's possible to get CSE with subtract operations.
1280 // A later phase can perform the optimization of setting the destination
1281 // register to WZR/XZR if it ends up being unused.
1282 unsigned Opcode = AArch64ISD::SUBS;
1284 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1285 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1286 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1287 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1288 // can be set differently by this operation. It comes down to whether
1289 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1290 // everything is fine. If not then the optimization is wrong. Thus general
1291 // comparisons are only valid if op2 != 0.
1293 // So, finally, the only LLVM-native comparisons that don't mention C and V
1294 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1295 // the absence of information about op2.
1296 Opcode = AArch64ISD::ADDS;
1297 RHS = RHS.getOperand(1);
1298 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1299 !isUnsignedIntSetCC(CC)) {
1300 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1301 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1302 // of the signed comparisons.
1303 Opcode = AArch64ISD::ANDS;
1304 RHS = LHS.getOperand(1);
1305 LHS = LHS.getOperand(0);
1308 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1312 /// \defgroup AArch64CCMP CMP;CCMP matching
1314 /// These functions deal with the formation of CMP;CCMP;... sequences.
1315 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1316 /// a comparison. They set the NZCV flags to a predefined value if their
1317 /// predicate is false. This allows to express arbitrary conjunctions, for
1318 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1321 /// ccmp B, inv(CB), CA
1322 /// check for CB flags
1324 /// In general we can create code for arbitrary "... (and (and A B) C)"
1325 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1326 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1327 /// negation operations:
1328 /// We can negate the results of a single comparison by inverting the flags
1329 /// used when the predicate fails and inverting the flags tested in the next
1330 /// instruction; We can also negate the results of the whole previous
1331 /// conditional compare sequence by inverting the flags tested in the next
1332 /// instruction. However there is no way to negate the result of a partial
1335 /// Therefore on encountering an "or" expression we can negate the subtree on
1336 /// one side and have to be able to push the negate to the leafs of the subtree
1337 /// on the other side (see also the comments in code). As complete example:
1338 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1339 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1340 /// is transformed to
1341 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1342 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1343 /// and implemented as:
1345 /// ccmp D, inv(CD), CC
1346 /// ccmp A, CA, inv(CD)
1347 /// ccmp B, CB, inv(CA)
1348 /// check for CB flags
1349 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1350 /// by conditional compare sequences.
1353 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1354 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1355 ISD::CondCode CC, SDValue CCOp,
1356 AArch64CC::CondCode Predicate,
1357 AArch64CC::CondCode OutCC,
1358 const SDLoc &DL, SelectionDAG &DAG) {
1359 unsigned Opcode = 0;
1360 if (LHS.getValueType().isFloatingPoint()) {
1361 assert(LHS.getValueType() != MVT::f128);
1362 if (LHS.getValueType() == MVT::f16) {
1363 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1364 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1366 Opcode = AArch64ISD::FCCMP;
1367 } else if (RHS.getOpcode() == ISD::SUB) {
1368 SDValue SubOp0 = RHS.getOperand(0);
1369 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1370 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1371 Opcode = AArch64ISD::CCMN;
1372 RHS = RHS.getOperand(1);
1376 Opcode = AArch64ISD::CCMP;
1378 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1379 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1380 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1381 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1382 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1385 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1386 /// CanPushNegate is set to true if we can push a negate operation through
1387 /// the tree in a was that we are left with AND operations and negate operations
1388 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1389 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1390 /// brought into such a form.
1391 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1392 unsigned Depth = 0) {
1393 if (!Val.hasOneUse())
1395 unsigned Opcode = Val->getOpcode();
1396 if (Opcode == ISD::SETCC) {
1397 if (Val->getOperand(0).getValueType() == MVT::f128)
1402 // Protect against exponential runtime and stack overflow.
1405 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1406 SDValue O0 = Val->getOperand(0);
1407 SDValue O1 = Val->getOperand(1);
1409 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1412 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1415 if (Opcode == ISD::OR) {
1416 // For an OR expression we need to be able to negate at least one side or
1417 // we cannot do the transformation at all.
1418 if (!CanNegateL && !CanNegateR)
1420 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1421 // can negate the x and y subtrees.
1422 CanNegate = CanNegateL && CanNegateR;
1424 // If the operands are OR expressions then we finally need to negate their
1425 // outputs, we can only do that for the operand with emitted last by
1426 // negating OutCC, not for both operands.
1427 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1428 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1429 if (NeedsNegOutL && NeedsNegOutR)
1431 // We cannot negate an AND operation (it would become an OR),
1439 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1440 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1441 /// Tries to transform the given i1 producing node @p Val to a series compare
1442 /// and conditional compare operations. @returns an NZCV flags producing node
1443 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1444 /// transformation was not possible.
1445 /// On recursive invocations @p PushNegate may be set to true to have negation
1446 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1447 /// for the comparisons in the current subtree; @p Depth limits the search
1448 /// depth to avoid stack overflow.
1449 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1450 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1451 AArch64CC::CondCode Predicate) {
1452 // We're at a tree leaf, produce a conditional comparison operation.
1453 unsigned Opcode = Val->getOpcode();
1454 if (Opcode == ISD::SETCC) {
1455 SDValue LHS = Val->getOperand(0);
1456 SDValue RHS = Val->getOperand(1);
1457 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1458 bool isInteger = LHS.getValueType().isInteger();
1460 CC = getSetCCInverse(CC, isInteger);
1462 // Determine OutCC and handle FP special case.
1464 OutCC = changeIntCCToAArch64CC(CC);
1466 assert(LHS.getValueType().isFloatingPoint());
1467 AArch64CC::CondCode ExtraCC;
1468 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1469 // Some floating point conditions can't be tested with a single condition
1470 // code. Construct an additional comparison in this case.
1471 if (ExtraCC != AArch64CC::AL) {
1473 if (!CCOp.getNode())
1474 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1476 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1479 Predicate = ExtraCC;
1483 // Produce a normal comparison if we are first in the chain
1485 return emitComparison(LHS, RHS, CC, DL, DAG);
1486 // Otherwise produce a ccmp.
1487 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1490 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1491 "Valid conjunction/disjunction tree");
1493 // Check if both sides can be transformed.
1494 SDValue LHS = Val->getOperand(0);
1495 SDValue RHS = Val->getOperand(1);
1497 // In case of an OR we need to negate our operands and the result.
1498 // (A v B) <=> not(not(A) ^ not(B))
1499 bool NegateOpsAndResult = Opcode == ISD::OR;
1500 // We can negate the results of all previous operations by inverting the
1501 // predicate flags giving us a free negation for one side. The other side
1502 // must be negatable by itself.
1503 if (NegateOpsAndResult) {
1504 // See which side we can negate.
1506 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1507 assert(isValidL && "Valid conjunction/disjunction tree");
1512 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1513 assert(isValidR && "Valid conjunction/disjunction tree");
1514 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1517 // Order the side which we cannot negate to RHS so we can emit it first.
1519 std::swap(LHS, RHS);
1521 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1522 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1523 "Valid conjunction/disjunction tree");
1524 // Order the side where we need to negate the output flags to RHS so it
1525 // gets emitted first.
1527 std::swap(LHS, RHS);
1530 // Emit RHS. If we want to negate the tree we only need to push a negate
1531 // through if we are already in a PushNegate case, otherwise we can negate
1532 // the "flags to test" afterwards.
1533 AArch64CC::CondCode RHSCC;
1534 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1536 if (NegateOpsAndResult && !Negate)
1537 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1538 // Emit LHS. We may need to negate it.
1539 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1540 NegateOpsAndResult, CmpR,
1542 // If we transformed an OR to and AND then we have to negate the result
1543 // (or absorb the Negate parameter).
1544 if (NegateOpsAndResult && !Negate)
1545 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1549 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1550 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1551 /// \see emitConjunctionDisjunctionTreeRec().
1552 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1553 AArch64CC::CondCode &OutCC) {
1555 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1558 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1564 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1565 SDValue &AArch64cc, SelectionDAG &DAG,
1567 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1568 EVT VT = RHS.getValueType();
1569 uint64_t C = RHSC->getZExtValue();
1570 if (!isLegalArithImmed(C)) {
1571 // Constant does not fit, try adjusting it by one?
1577 if ((VT == MVT::i32 && C != 0x80000000 &&
1578 isLegalArithImmed((uint32_t)(C - 1))) ||
1579 (VT == MVT::i64 && C != 0x80000000ULL &&
1580 isLegalArithImmed(C - 1ULL))) {
1581 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1582 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1583 RHS = DAG.getConstant(C, dl, VT);
1588 if ((VT == MVT::i32 && C != 0 &&
1589 isLegalArithImmed((uint32_t)(C - 1))) ||
1590 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1591 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1592 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1593 RHS = DAG.getConstant(C, dl, VT);
1598 if ((VT == MVT::i32 && C != INT32_MAX &&
1599 isLegalArithImmed((uint32_t)(C + 1))) ||
1600 (VT == MVT::i64 && C != INT64_MAX &&
1601 isLegalArithImmed(C + 1ULL))) {
1602 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1603 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1604 RHS = DAG.getConstant(C, dl, VT);
1609 if ((VT == MVT::i32 && C != UINT32_MAX &&
1610 isLegalArithImmed((uint32_t)(C + 1))) ||
1611 (VT == MVT::i64 && C != UINT64_MAX &&
1612 isLegalArithImmed(C + 1ULL))) {
1613 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1614 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1615 RHS = DAG.getConstant(C, dl, VT);
1622 AArch64CC::CondCode AArch64CC;
1623 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1624 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1626 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1627 // For the i8 operand, the largest immediate is 255, so this can be easily
1628 // encoded in the compare instruction. For the i16 operand, however, the
1629 // largest immediate cannot be encoded in the compare.
1630 // Therefore, use a sign extending load and cmn to avoid materializing the
1631 // -1 constant. For example,
1633 // ldrh w0, [x0, #0]
1636 // ldrsh w0, [x0, #0]
1638 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1639 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1640 // ensure both the LHS and RHS are truly zero extended and to make sure the
1641 // transformation is profitable.
1642 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1643 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1644 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1645 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1646 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1647 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1649 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1650 DAG.getValueType(MVT::i16));
1651 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1652 RHS.getValueType()),
1654 AArch64CC = changeIntCCToAArch64CC(CC);
1658 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1659 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1660 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1661 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1667 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1668 AArch64CC = changeIntCCToAArch64CC(CC);
1670 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1674 static std::pair<SDValue, SDValue>
1675 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1676 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1677 "Unsupported value type");
1678 SDValue Value, Overflow;
1680 SDValue LHS = Op.getOperand(0);
1681 SDValue RHS = Op.getOperand(1);
1683 switch (Op.getOpcode()) {
1685 llvm_unreachable("Unknown overflow instruction!");
1687 Opc = AArch64ISD::ADDS;
1691 Opc = AArch64ISD::ADDS;
1695 Opc = AArch64ISD::SUBS;
1699 Opc = AArch64ISD::SUBS;
1702 // Multiply needs a little bit extra work.
1706 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1707 if (Op.getValueType() == MVT::i32) {
1708 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1709 // For a 32 bit multiply with overflow check we want the instruction
1710 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1711 // need to generate the following pattern:
1712 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1713 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1714 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1715 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1716 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1717 DAG.getConstant(0, DL, MVT::i64));
1718 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1719 // operation. We need to clear out the upper 32 bits, because we used a
1720 // widening multiply that wrote all 64 bits. In the end this should be a
1722 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1724 // The signed overflow check requires more than just a simple check for
1725 // any bit set in the upper 32 bits of the result. These bits could be
1726 // just the sign bits of a negative number. To perform the overflow
1727 // check we have to arithmetic shift right the 32nd bit of the result by
1728 // 31 bits. Then we compare the result to the upper 32 bits.
1729 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1730 DAG.getConstant(32, DL, MVT::i64));
1731 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1732 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1733 DAG.getConstant(31, DL, MVT::i64));
1734 // It is important that LowerBits is last, otherwise the arithmetic
1735 // shift will not be folded into the compare (SUBS).
1736 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1737 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1740 // The overflow check for unsigned multiply is easy. We only need to
1741 // check if any of the upper 32 bits are set. This can be done with a
1742 // CMP (shifted register). For that we need to generate the following
1744 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1745 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1746 DAG.getConstant(32, DL, MVT::i64));
1747 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1749 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1750 DAG.getConstant(0, DL, MVT::i64),
1751 UpperBits).getValue(1);
1755 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1756 // For the 64 bit multiply
1757 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1759 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1760 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1761 DAG.getConstant(63, DL, MVT::i64));
1762 // It is important that LowerBits is last, otherwise the arithmetic
1763 // shift will not be folded into the compare (SUBS).
1764 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1765 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1768 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1769 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1771 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1772 DAG.getConstant(0, DL, MVT::i64),
1773 UpperBits).getValue(1);
1780 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1782 // Emit the AArch64 operation with overflow check.
1783 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1784 Overflow = Value.getValue(1);
1786 return std::make_pair(Value, Overflow);
1789 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1790 RTLIB::Libcall Call) const {
1791 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1792 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1795 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1796 SDValue Sel = Op.getOperand(0);
1797 SDValue Other = Op.getOperand(1);
1799 // If neither operand is a SELECT_CC, give up.
1800 if (Sel.getOpcode() != ISD::SELECT_CC)
1801 std::swap(Sel, Other);
1802 if (Sel.getOpcode() != ISD::SELECT_CC)
1805 // The folding we want to perform is:
1806 // (xor x, (select_cc a, b, cc, 0, -1) )
1808 // (csel x, (xor x, -1), cc ...)
1810 // The latter will get matched to a CSINV instruction.
1812 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1813 SDValue LHS = Sel.getOperand(0);
1814 SDValue RHS = Sel.getOperand(1);
1815 SDValue TVal = Sel.getOperand(2);
1816 SDValue FVal = Sel.getOperand(3);
1819 // FIXME: This could be generalized to non-integer comparisons.
1820 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1823 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1824 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1826 // The values aren't constants, this isn't the pattern we're looking for.
1827 if (!CFVal || !CTVal)
1830 // We can commute the SELECT_CC by inverting the condition. This
1831 // might be needed to make this fit into a CSINV pattern.
1832 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1833 std::swap(TVal, FVal);
1834 std::swap(CTVal, CFVal);
1835 CC = ISD::getSetCCInverse(CC, true);
1838 // If the constants line up, perform the transform!
1839 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1841 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1844 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1845 DAG.getConstant(-1ULL, dl, Other.getValueType()));
1847 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1854 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1855 EVT VT = Op.getValueType();
1857 // Let legalize expand this if it isn't a legal type yet.
1858 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1861 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1864 bool ExtraOp = false;
1865 switch (Op.getOpcode()) {
1867 llvm_unreachable("Invalid code");
1869 Opc = AArch64ISD::ADDS;
1872 Opc = AArch64ISD::SUBS;
1875 Opc = AArch64ISD::ADCS;
1879 Opc = AArch64ISD::SBCS;
1885 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1886 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1890 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1891 // Let legalize expand this if it isn't a legal type yet.
1892 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1896 AArch64CC::CondCode CC;
1897 // The actual operation that sets the overflow or carry flag.
1898 SDValue Value, Overflow;
1899 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1901 // We use 0 and 1 as false and true values.
1902 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1903 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1905 // We use an inverted condition, because the conditional select is inverted
1906 // too. This will allow it to be selected to a single instruction:
1907 // CSINC Wd, WZR, WZR, invert(cond).
1908 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1909 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1912 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1913 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1916 // Prefetch operands are:
1917 // 1: Address to prefetch
1919 // 3: int locality (0 = no locality ... 3 = extreme locality)
1920 // 4: bool isDataCache
1921 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1923 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1924 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1925 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1927 bool IsStream = !Locality;
1928 // When the locality number is set
1930 // The front-end should have filtered out the out-of-range values
1931 assert(Locality <= 3 && "Prefetch locality out-of-range");
1932 // The locality degree is the opposite of the cache speed.
1933 // Put the number the other way around.
1934 // The encoding starts at 0 for level 1
1935 Locality = 3 - Locality;
1938 // built the mask value encoding the expected behavior.
1939 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1940 (!IsData << 3) | // IsDataCache bit
1941 (Locality << 1) | // Cache level bits
1942 (unsigned)IsStream; // Stream bit
1943 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1944 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1947 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1948 SelectionDAG &DAG) const {
1949 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1952 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1954 return LowerF128Call(Op, DAG, LC);
1957 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1958 SelectionDAG &DAG) const {
1959 if (Op.getOperand(0).getValueType() != MVT::f128) {
1960 // It's legal except when f128 is involved
1965 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1967 // FP_ROUND node has a second operand indicating whether it is known to be
1968 // precise. That doesn't take part in the LibCall so we can't directly use
1970 SDValue SrcVal = Op.getOperand(0);
1971 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1975 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1976 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1977 // Any additional optimization in this function should be recorded
1978 // in the cost tables.
1979 EVT InVT = Op.getOperand(0).getValueType();
1980 EVT VT = Op.getValueType();
1981 unsigned NumElts = InVT.getVectorNumElements();
1983 // f16 vectors are promoted to f32 before a conversion.
1984 if (InVT.getVectorElementType() == MVT::f16) {
1985 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1988 Op.getOpcode(), dl, Op.getValueType(),
1989 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1992 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1995 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1997 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2000 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2003 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2004 VT.getVectorNumElements());
2005 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2006 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2009 // Type changing conversions are illegal.
2013 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2014 SelectionDAG &DAG) const {
2015 if (Op.getOperand(0).getValueType().isVector())
2016 return LowerVectorFP_TO_INT(Op, DAG);
2018 // f16 conversions are promoted to f32.
2019 if (Op.getOperand(0).getValueType() == MVT::f16) {
2022 Op.getOpcode(), dl, Op.getValueType(),
2023 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2026 if (Op.getOperand(0).getValueType() != MVT::f128) {
2027 // It's legal except when f128 is involved
2032 if (Op.getOpcode() == ISD::FP_TO_SINT)
2033 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2035 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2037 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2038 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2041 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2042 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2043 // Any additional optimization in this function should be recorded
2044 // in the cost tables.
2045 EVT VT = Op.getValueType();
2047 SDValue In = Op.getOperand(0);
2048 EVT InVT = In.getValueType();
2050 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2052 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2053 InVT.getVectorNumElements());
2054 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2055 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2058 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2060 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2061 EVT CastVT = VT.changeVectorElementTypeToInteger();
2062 In = DAG.getNode(CastOpc, dl, CastVT, In);
2063 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2069 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2070 SelectionDAG &DAG) const {
2071 if (Op.getValueType().isVector())
2072 return LowerVectorINT_TO_FP(Op, DAG);
2074 // f16 conversions are promoted to f32.
2075 if (Op.getValueType() == MVT::f16) {
2078 ISD::FP_ROUND, dl, MVT::f16,
2079 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2080 DAG.getIntPtrConstant(0, dl));
2083 // i128 conversions are libcalls.
2084 if (Op.getOperand(0).getValueType() == MVT::i128)
2087 // Other conversions are legal, unless it's to the completely software-based
2089 if (Op.getValueType() != MVT::f128)
2093 if (Op.getOpcode() == ISD::SINT_TO_FP)
2094 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2096 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2098 return LowerF128Call(Op, DAG, LC);
2101 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2102 SelectionDAG &DAG) const {
2103 // For iOS, we want to call an alternative entry point: __sincos_stret,
2104 // which returns the values in two S / D registers.
2106 SDValue Arg = Op.getOperand(0);
2107 EVT ArgVT = Arg.getValueType();
2108 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2115 Entry.IsSExt = false;
2116 Entry.IsZExt = false;
2117 Args.push_back(Entry);
2119 const char *LibcallName =
2120 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2122 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2124 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2125 TargetLowering::CallLoweringInfo CLI(DAG);
2127 .setChain(DAG.getEntryNode())
2128 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2130 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2131 return CallResult.first;
2134 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2135 if (Op.getValueType() != MVT::f16)
2138 assert(Op.getOperand(0).getValueType() == MVT::i16);
2141 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2142 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2144 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2145 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2149 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2150 if (OrigVT.getSizeInBits() >= 64)
2153 assert(OrigVT.isSimple() && "Expecting a simple value type");
2155 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2156 switch (OrigSimpleTy) {
2157 default: llvm_unreachable("Unexpected Vector Type");
2166 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2169 unsigned ExtOpcode) {
2170 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2171 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2172 // 64-bits we need to insert a new extension so that it will be 64-bits.
2173 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2174 if (OrigTy.getSizeInBits() >= 64)
2177 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2178 EVT NewVT = getExtensionTo64Bits(OrigTy);
2180 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2183 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2185 EVT VT = N->getValueType(0);
2187 if (N->getOpcode() != ISD::BUILD_VECTOR)
2190 for (const SDValue &Elt : N->op_values()) {
2191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2192 unsigned EltSize = VT.getScalarSizeInBits();
2193 unsigned HalfSize = EltSize / 2;
2195 if (!isIntN(HalfSize, C->getSExtValue()))
2198 if (!isUIntN(HalfSize, C->getZExtValue()))
2209 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2210 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2211 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2212 N->getOperand(0)->getValueType(0),
2216 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2217 EVT VT = N->getValueType(0);
2219 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2220 unsigned NumElts = VT.getVectorNumElements();
2221 MVT TruncVT = MVT::getIntegerVT(EltSize);
2222 SmallVector<SDValue, 8> Ops;
2223 for (unsigned i = 0; i != NumElts; ++i) {
2224 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2225 const APInt &CInt = C->getAPIntValue();
2226 // Element types smaller than 32 bits are not legal, so use i32 elements.
2227 // The values are implicitly truncated so sext vs. zext doesn't matter.
2228 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2230 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2233 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2234 return N->getOpcode() == ISD::SIGN_EXTEND ||
2235 isExtendedBUILD_VECTOR(N, DAG, true);
2238 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2239 return N->getOpcode() == ISD::ZERO_EXTEND ||
2240 isExtendedBUILD_VECTOR(N, DAG, false);
2243 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2244 unsigned Opcode = N->getOpcode();
2245 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2246 SDNode *N0 = N->getOperand(0).getNode();
2247 SDNode *N1 = N->getOperand(1).getNode();
2248 return N0->hasOneUse() && N1->hasOneUse() &&
2249 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2254 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2255 unsigned Opcode = N->getOpcode();
2256 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2257 SDNode *N0 = N->getOperand(0).getNode();
2258 SDNode *N1 = N->getOperand(1).getNode();
2259 return N0->hasOneUse() && N1->hasOneUse() &&
2260 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2265 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2266 // Multiplications are only custom-lowered for 128-bit vectors so that
2267 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2268 EVT VT = Op.getValueType();
2269 assert(VT.is128BitVector() && VT.isInteger() &&
2270 "unexpected type for custom-lowering ISD::MUL");
2271 SDNode *N0 = Op.getOperand(0).getNode();
2272 SDNode *N1 = Op.getOperand(1).getNode();
2273 unsigned NewOpc = 0;
2275 bool isN0SExt = isSignExtended(N0, DAG);
2276 bool isN1SExt = isSignExtended(N1, DAG);
2277 if (isN0SExt && isN1SExt)
2278 NewOpc = AArch64ISD::SMULL;
2280 bool isN0ZExt = isZeroExtended(N0, DAG);
2281 bool isN1ZExt = isZeroExtended(N1, DAG);
2282 if (isN0ZExt && isN1ZExt)
2283 NewOpc = AArch64ISD::UMULL;
2284 else if (isN1SExt || isN1ZExt) {
2285 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2286 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2287 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2288 NewOpc = AArch64ISD::SMULL;
2290 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2291 NewOpc = AArch64ISD::UMULL;
2293 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2295 NewOpc = AArch64ISD::UMULL;
2301 if (VT == MVT::v2i64)
2302 // Fall through to expand this. It is not legal.
2305 // Other vector multiplications are legal.
2310 // Legalize to a S/UMULL instruction
2313 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2315 Op0 = skipExtensionForVectorMULL(N0, DAG);
2316 assert(Op0.getValueType().is64BitVector() &&
2317 Op1.getValueType().is64BitVector() &&
2318 "unexpected types for extended operands to VMULL");
2319 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2321 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2322 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2323 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2324 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2325 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2326 EVT Op1VT = Op1.getValueType();
2327 return DAG.getNode(N0->getOpcode(), DL, VT,
2328 DAG.getNode(NewOpc, DL, VT,
2329 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2330 DAG.getNode(NewOpc, DL, VT,
2331 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2334 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2335 SelectionDAG &DAG) const {
2336 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2339 default: return SDValue(); // Don't custom lower most intrinsics.
2340 case Intrinsic::thread_pointer: {
2341 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2342 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2344 case Intrinsic::aarch64_neon_smax:
2345 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2346 Op.getOperand(1), Op.getOperand(2));
2347 case Intrinsic::aarch64_neon_umax:
2348 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2349 Op.getOperand(1), Op.getOperand(2));
2350 case Intrinsic::aarch64_neon_smin:
2351 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2352 Op.getOperand(1), Op.getOperand(2));
2353 case Intrinsic::aarch64_neon_umin:
2354 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2355 Op.getOperand(1), Op.getOperand(2));
2359 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2360 SelectionDAG &DAG) const {
2361 switch (Op.getOpcode()) {
2363 llvm_unreachable("unimplemented operand");
2366 return LowerBITCAST(Op, DAG);
2367 case ISD::GlobalAddress:
2368 return LowerGlobalAddress(Op, DAG);
2369 case ISD::GlobalTLSAddress:
2370 return LowerGlobalTLSAddress(Op, DAG);
2372 return LowerSETCC(Op, DAG);
2374 return LowerBR_CC(Op, DAG);
2376 return LowerSELECT(Op, DAG);
2377 case ISD::SELECT_CC:
2378 return LowerSELECT_CC(Op, DAG);
2379 case ISD::JumpTable:
2380 return LowerJumpTable(Op, DAG);
2381 case ISD::ConstantPool:
2382 return LowerConstantPool(Op, DAG);
2383 case ISD::BlockAddress:
2384 return LowerBlockAddress(Op, DAG);
2386 return LowerVASTART(Op, DAG);
2388 return LowerVACOPY(Op, DAG);
2390 return LowerVAARG(Op, DAG);
2395 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2402 return LowerXALUO(Op, DAG);
2404 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2406 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2408 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2410 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2412 return LowerFP_ROUND(Op, DAG);
2413 case ISD::FP_EXTEND:
2414 return LowerFP_EXTEND(Op, DAG);
2415 case ISD::FRAMEADDR:
2416 return LowerFRAMEADDR(Op, DAG);
2417 case ISD::RETURNADDR:
2418 return LowerRETURNADDR(Op, DAG);
2419 case ISD::INSERT_VECTOR_ELT:
2420 return LowerINSERT_VECTOR_ELT(Op, DAG);
2421 case ISD::EXTRACT_VECTOR_ELT:
2422 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2423 case ISD::BUILD_VECTOR:
2424 return LowerBUILD_VECTOR(Op, DAG);
2425 case ISD::VECTOR_SHUFFLE:
2426 return LowerVECTOR_SHUFFLE(Op, DAG);
2427 case ISD::EXTRACT_SUBVECTOR:
2428 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2432 return LowerVectorSRA_SRL_SHL(Op, DAG);
2433 case ISD::SHL_PARTS:
2434 return LowerShiftLeftParts(Op, DAG);
2435 case ISD::SRL_PARTS:
2436 case ISD::SRA_PARTS:
2437 return LowerShiftRightParts(Op, DAG);
2439 return LowerCTPOP(Op, DAG);
2440 case ISD::FCOPYSIGN:
2441 return LowerFCOPYSIGN(Op, DAG);
2443 return LowerVectorAND(Op, DAG);
2445 return LowerVectorOR(Op, DAG);
2447 return LowerXOR(Op, DAG);
2449 return LowerPREFETCH(Op, DAG);
2450 case ISD::SINT_TO_FP:
2451 case ISD::UINT_TO_FP:
2452 return LowerINT_TO_FP(Op, DAG);
2453 case ISD::FP_TO_SINT:
2454 case ISD::FP_TO_UINT:
2455 return LowerFP_TO_INT(Op, DAG);
2457 return LowerFSINCOS(Op, DAG);
2459 return LowerMUL(Op, DAG);
2460 case ISD::INTRINSIC_WO_CHAIN:
2461 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2465 //===----------------------------------------------------------------------===//
2466 // Calling Convention Implementation
2467 //===----------------------------------------------------------------------===//
2469 #include "AArch64GenCallingConv.inc"
2471 /// Selects the correct CCAssignFn for a given CallingConvention value.
2472 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2473 bool IsVarArg) const {
2476 llvm_unreachable("Unsupported calling convention.");
2477 case CallingConv::WebKit_JS:
2478 return CC_AArch64_WebKit_JS;
2479 case CallingConv::GHC:
2480 return CC_AArch64_GHC;
2481 case CallingConv::C:
2482 case CallingConv::Fast:
2483 case CallingConv::PreserveMost:
2484 case CallingConv::CXX_FAST_TLS:
2485 case CallingConv::Swift:
2486 if (!Subtarget->isTargetDarwin())
2487 return CC_AArch64_AAPCS;
2488 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2493 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2494 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2495 : RetCC_AArch64_AAPCS;
2498 SDValue AArch64TargetLowering::LowerFormalArguments(
2499 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2500 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2501 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2502 MachineFunction &MF = DAG.getMachineFunction();
2503 MachineFrameInfo &MFI = MF.getFrameInfo();
2505 // Assign locations to all of the incoming arguments.
2506 SmallVector<CCValAssign, 16> ArgLocs;
2507 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2510 // At this point, Ins[].VT may already be promoted to i32. To correctly
2511 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2512 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2513 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2514 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2516 unsigned NumArgs = Ins.size();
2517 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2518 unsigned CurArgIdx = 0;
2519 for (unsigned i = 0; i != NumArgs; ++i) {
2520 MVT ValVT = Ins[i].VT;
2521 if (Ins[i].isOrigArg()) {
2522 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2523 CurArgIdx = Ins[i].getOrigArgIndex();
2525 // Get type of the original argument.
2526 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2527 /*AllowUnknown*/ true);
2528 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2529 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2530 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2532 else if (ActualMVT == MVT::i16)
2535 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2537 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2538 assert(!Res && "Call operand has unhandled type");
2541 assert(ArgLocs.size() == Ins.size());
2542 SmallVector<SDValue, 16> ArgValues;
2543 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2544 CCValAssign &VA = ArgLocs[i];
2546 if (Ins[i].Flags.isByVal()) {
2547 // Byval is used for HFAs in the PCS, but the system should work in a
2548 // non-compliant manner for larger structs.
2549 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2550 int Size = Ins[i].Flags.getByValSize();
2551 unsigned NumRegs = (Size + 7) / 8;
2553 // FIXME: This works on big-endian for composite byvals, which are the common
2554 // case. It should also work for fundamental types too.
2556 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2557 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2558 InVals.push_back(FrameIdxN);
2563 if (VA.isRegLoc()) {
2564 // Arguments stored in registers.
2565 EVT RegVT = VA.getLocVT();
2568 const TargetRegisterClass *RC;
2570 if (RegVT == MVT::i32)
2571 RC = &AArch64::GPR32RegClass;
2572 else if (RegVT == MVT::i64)
2573 RC = &AArch64::GPR64RegClass;
2574 else if (RegVT == MVT::f16)
2575 RC = &AArch64::FPR16RegClass;
2576 else if (RegVT == MVT::f32)
2577 RC = &AArch64::FPR32RegClass;
2578 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2579 RC = &AArch64::FPR64RegClass;
2580 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2581 RC = &AArch64::FPR128RegClass;
2583 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2585 // Transform the arguments in physical registers into virtual ones.
2586 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2587 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2589 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2590 // to 64 bits. Insert an assert[sz]ext to capture this, then
2591 // truncate to the right size.
2592 switch (VA.getLocInfo()) {
2594 llvm_unreachable("Unknown loc info!");
2595 case CCValAssign::Full:
2597 case CCValAssign::BCvt:
2598 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2600 case CCValAssign::AExt:
2601 case CCValAssign::SExt:
2602 case CCValAssign::ZExt:
2603 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2604 // nodes after our lowering.
2605 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2609 InVals.push_back(ArgValue);
2611 } else { // VA.isRegLoc()
2612 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2613 unsigned ArgOffset = VA.getLocMemOffset();
2614 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2616 uint32_t BEAlign = 0;
2617 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2618 !Ins[i].Flags.isInConsecutiveRegs())
2619 BEAlign = 8 - ArgSize;
2621 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2623 // Create load nodes to retrieve arguments from the stack.
2624 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2627 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2628 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2629 MVT MemVT = VA.getValVT();
2631 switch (VA.getLocInfo()) {
2634 case CCValAssign::BCvt:
2635 MemVT = VA.getLocVT();
2637 case CCValAssign::SExt:
2638 ExtType = ISD::SEXTLOAD;
2640 case CCValAssign::ZExt:
2641 ExtType = ISD::ZEXTLOAD;
2643 case CCValAssign::AExt:
2644 ExtType = ISD::EXTLOAD;
2648 ArgValue = DAG.getExtLoad(
2649 ExtType, DL, VA.getLocVT(), Chain, FIN,
2650 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2653 InVals.push_back(ArgValue);
2658 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2660 if (!Subtarget->isTargetDarwin()) {
2661 // The AAPCS variadic function ABI is identical to the non-variadic
2662 // one. As a result there may be more arguments in registers and we should
2663 // save them for future reference.
2664 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2667 // This will point to the next argument passed via stack.
2668 unsigned StackOffset = CCInfo.getNextStackOffset();
2669 // We currently pass all varargs at 8-byte alignment.
2670 StackOffset = ((StackOffset + 7) & ~7);
2671 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2674 unsigned StackArgSize = CCInfo.getNextStackOffset();
2675 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2676 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2677 // This is a non-standard ABI so by fiat I say we're allowed to make full
2678 // use of the stack area to be popped, which must be aligned to 16 bytes in
2680 StackArgSize = alignTo(StackArgSize, 16);
2682 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2683 // a multiple of 16.
2684 FuncInfo->setArgumentStackToRestore(StackArgSize);
2686 // This realignment carries over to the available bytes below. Our own
2687 // callers will guarantee the space is free by giving an aligned value to
2690 // Even if we're not expected to free up the space, it's useful to know how
2691 // much is there while considering tail calls (because we can reuse it).
2692 FuncInfo->setBytesInStackArgArea(StackArgSize);
2697 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2700 SDValue &Chain) const {
2701 MachineFunction &MF = DAG.getMachineFunction();
2702 MachineFrameInfo &MFI = MF.getFrameInfo();
2703 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2704 auto PtrVT = getPointerTy(DAG.getDataLayout());
2706 SmallVector<SDValue, 8> MemOps;
2708 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2709 AArch64::X3, AArch64::X4, AArch64::X5,
2710 AArch64::X6, AArch64::X7 };
2711 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2712 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2714 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2716 if (GPRSaveSize != 0) {
2717 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2719 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2721 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2722 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2723 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2724 SDValue Store = DAG.getStore(
2725 Val.getValue(1), DL, Val, FIN,
2726 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2727 MemOps.push_back(Store);
2729 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2732 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2733 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2735 if (Subtarget->hasFPARMv8()) {
2736 static const MCPhysReg FPRArgRegs[] = {
2737 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2738 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2739 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2740 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2742 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2744 if (FPRSaveSize != 0) {
2745 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2747 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2749 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2750 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2751 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2753 SDValue Store = DAG.getStore(
2754 Val.getValue(1), DL, Val, FIN,
2755 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2756 MemOps.push_back(Store);
2757 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2758 DAG.getConstant(16, DL, PtrVT));
2761 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2762 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2765 if (!MemOps.empty()) {
2766 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2770 /// LowerCallResult - Lower the result values of a call into the
2771 /// appropriate copies out of appropriate physical registers.
2772 SDValue AArch64TargetLowering::LowerCallResult(
2773 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2774 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2775 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2776 SDValue ThisVal) const {
2777 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2778 ? RetCC_AArch64_WebKit_JS
2779 : RetCC_AArch64_AAPCS;
2780 // Assign locations to each value returned by this call.
2781 SmallVector<CCValAssign, 16> RVLocs;
2782 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2784 CCInfo.AnalyzeCallResult(Ins, RetCC);
2786 // Copy all of the result registers out of their specified physreg.
2787 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2788 CCValAssign VA = RVLocs[i];
2790 // Pass 'this' value directly from the argument to return value, to avoid
2791 // reg unit interference
2792 if (i == 0 && isThisReturn) {
2793 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2794 "unexpected return calling convention register assignment");
2795 InVals.push_back(ThisVal);
2800 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2801 Chain = Val.getValue(1);
2802 InFlag = Val.getValue(2);
2804 switch (VA.getLocInfo()) {
2806 llvm_unreachable("Unknown loc info!");
2807 case CCValAssign::Full:
2809 case CCValAssign::BCvt:
2810 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2814 InVals.push_back(Val);
2820 /// Return true if the calling convention is one that we can guarantee TCO for.
2821 static bool canGuaranteeTCO(CallingConv::ID CC) {
2822 return CC == CallingConv::Fast;
2825 /// Return true if we might ever do TCO for calls with this calling convention.
2826 static bool mayTailCallThisCC(CallingConv::ID CC) {
2828 case CallingConv::C:
2829 case CallingConv::PreserveMost:
2830 case CallingConv::Swift:
2833 return canGuaranteeTCO(CC);
2837 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2838 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2839 const SmallVectorImpl<ISD::OutputArg> &Outs,
2840 const SmallVectorImpl<SDValue> &OutVals,
2841 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2842 if (!mayTailCallThisCC(CalleeCC))
2845 MachineFunction &MF = DAG.getMachineFunction();
2846 const Function *CallerF = MF.getFunction();
2847 CallingConv::ID CallerCC = CallerF->getCallingConv();
2848 bool CCMatch = CallerCC == CalleeCC;
2850 // Byval parameters hand the function a pointer directly into the stack area
2851 // we want to reuse during a tail call. Working around this *is* possible (see
2852 // X86) but less efficient and uglier in LowerCall.
2853 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2854 e = CallerF->arg_end();
2856 if (i->hasByValAttr())
2859 if (getTargetMachine().Options.GuaranteedTailCallOpt)
2860 return canGuaranteeTCO(CalleeCC) && CCMatch;
2862 // Externally-defined functions with weak linkage should not be
2863 // tail-called on AArch64 when the OS does not support dynamic
2864 // pre-emption of symbols, as the AAELF spec requires normal calls
2865 // to undefined weak functions to be replaced with a NOP or jump to the
2866 // next instruction. The behaviour of branch instructions in this
2867 // situation (as used for tail calls) is implementation-defined, so we
2868 // cannot rely on the linker replacing the tail call with a return.
2869 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2870 const GlobalValue *GV = G->getGlobal();
2871 const Triple &TT = getTargetMachine().getTargetTriple();
2872 if (GV->hasExternalWeakLinkage() &&
2873 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2877 // Now we search for cases where we can use a tail call without changing the
2878 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2881 // I want anyone implementing a new calling convention to think long and hard
2882 // about this assert.
2883 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2884 "Unexpected variadic calling convention");
2886 LLVMContext &C = *DAG.getContext();
2887 if (isVarArg && !Outs.empty()) {
2888 // At least two cases here: if caller is fastcc then we can't have any
2889 // memory arguments (we'd be expected to clean up the stack afterwards). If
2890 // caller is C then we could potentially use its argument area.
2892 // FIXME: for now we take the most conservative of these in both cases:
2893 // disallow all variadic memory operands.
2894 SmallVector<CCValAssign, 16> ArgLocs;
2895 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2897 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2898 for (const CCValAssign &ArgLoc : ArgLocs)
2899 if (!ArgLoc.isRegLoc())
2903 // Check that the call results are passed in the same way.
2904 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2905 CCAssignFnForCall(CalleeCC, isVarArg),
2906 CCAssignFnForCall(CallerCC, isVarArg)))
2908 // The callee has to preserve all registers the caller needs to preserve.
2909 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2910 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2912 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2913 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2917 // Nothing more to check if the callee is taking no arguments
2921 SmallVector<CCValAssign, 16> ArgLocs;
2922 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2924 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2926 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2928 // If the stack arguments for this call do not fit into our own save area then
2929 // the call cannot be made tail.
2930 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2933 const MachineRegisterInfo &MRI = MF.getRegInfo();
2934 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2940 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2942 MachineFrameInfo &MFI,
2943 int ClobberedFI) const {
2944 SmallVector<SDValue, 8> ArgChains;
2945 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2946 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
2948 // Include the original chain at the beginning of the list. When this is
2949 // used by target LowerCall hooks, this helps legalize find the
2950 // CALLSEQ_BEGIN node.
2951 ArgChains.push_back(Chain);
2953 // Add a chain value for each stack argument corresponding
2954 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2955 UE = DAG.getEntryNode().getNode()->use_end();
2957 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2958 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2959 if (FI->getIndex() < 0) {
2960 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
2961 int64_t InLastByte = InFirstByte;
2962 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
2964 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2965 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2966 ArgChains.push_back(SDValue(L, 1));
2969 // Build a tokenfactor for all the chains.
2970 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2973 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2974 bool TailCallOpt) const {
2975 return CallCC == CallingConv::Fast && TailCallOpt;
2978 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2979 /// and add input and output parameter nodes.
2981 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2982 SmallVectorImpl<SDValue> &InVals) const {
2983 SelectionDAG &DAG = CLI.DAG;
2985 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2986 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2987 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2988 SDValue Chain = CLI.Chain;
2989 SDValue Callee = CLI.Callee;
2990 bool &IsTailCall = CLI.IsTailCall;
2991 CallingConv::ID CallConv = CLI.CallConv;
2992 bool IsVarArg = CLI.IsVarArg;
2994 MachineFunction &MF = DAG.getMachineFunction();
2995 bool IsThisReturn = false;
2997 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2998 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2999 bool IsSibCall = false;
3002 // Check if it's really possible to do a tail call.
3003 IsTailCall = isEligibleForTailCallOptimization(
3004 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3005 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3006 report_fatal_error("failed to perform tail call elimination on a call "
3007 "site marked musttail");
3009 // A sibling call is one where we're under the usual C ABI and not planning
3010 // to change that but can still do a tail call:
3011 if (!TailCallOpt && IsTailCall)
3018 // Analyze operands of the call, assigning locations to each operand.
3019 SmallVector<CCValAssign, 16> ArgLocs;
3020 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3024 // Handle fixed and variable vector arguments differently.
3025 // Variable vector arguments always go into memory.
3026 unsigned NumArgs = Outs.size();
3028 for (unsigned i = 0; i != NumArgs; ++i) {
3029 MVT ArgVT = Outs[i].VT;
3030 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3031 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3032 /*IsVarArg=*/ !Outs[i].IsFixed);
3033 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3034 assert(!Res && "Call operand has unhandled type");
3038 // At this point, Outs[].VT may already be promoted to i32. To correctly
3039 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3040 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3041 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3042 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3044 unsigned NumArgs = Outs.size();
3045 for (unsigned i = 0; i != NumArgs; ++i) {
3046 MVT ValVT = Outs[i].VT;
3047 // Get type of the original argument.
3048 EVT ActualVT = getValueType(DAG.getDataLayout(),
3049 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3050 /*AllowUnknown*/ true);
3051 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3052 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3053 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3054 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3056 else if (ActualMVT == MVT::i16)
3059 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3060 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3061 assert(!Res && "Call operand has unhandled type");
3066 // Get a count of how many bytes are to be pushed on the stack.
3067 unsigned NumBytes = CCInfo.getNextStackOffset();
3070 // Since we're not changing the ABI to make this a tail call, the memory
3071 // operands are already available in the caller's incoming argument space.
3075 // FPDiff is the byte offset of the call's argument area from the callee's.
3076 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3077 // by this amount for a tail call. In a sibling call it must be 0 because the
3078 // caller will deallocate the entire stack and the callee still expects its
3079 // arguments to begin at SP+0. Completely unused for non-tail calls.
3082 if (IsTailCall && !IsSibCall) {
3083 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3085 // Since callee will pop argument stack as a tail call, we must keep the
3086 // popped size 16-byte aligned.
3087 NumBytes = alignTo(NumBytes, 16);
3089 // FPDiff will be negative if this tail call requires more space than we
3090 // would automatically have in our incoming argument space. Positive if we
3091 // can actually shrink the stack.
3092 FPDiff = NumReusableBytes - NumBytes;
3094 // The stack pointer must be 16-byte aligned at all times it's used for a
3095 // memory operation, which in practice means at *all* times and in
3096 // particular across call boundaries. Therefore our own arguments started at
3097 // a 16-byte aligned SP and the delta applied for the tail call should
3098 // satisfy the same constraint.
3099 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3102 // Adjust the stack pointer for the new arguments...
3103 // These operations are automatically eliminated by the prolog/epilog pass
3105 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3109 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3110 getPointerTy(DAG.getDataLayout()));
3112 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3113 SmallVector<SDValue, 8> MemOpChains;
3114 auto PtrVT = getPointerTy(DAG.getDataLayout());
3116 // Walk the register/memloc assignments, inserting copies/loads.
3117 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3118 ++i, ++realArgIdx) {
3119 CCValAssign &VA = ArgLocs[i];
3120 SDValue Arg = OutVals[realArgIdx];
3121 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3123 // Promote the value if needed.
3124 switch (VA.getLocInfo()) {
3126 llvm_unreachable("Unknown loc info!");
3127 case CCValAssign::Full:
3129 case CCValAssign::SExt:
3130 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3132 case CCValAssign::ZExt:
3133 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3135 case CCValAssign::AExt:
3136 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3137 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3138 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3139 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3141 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3143 case CCValAssign::BCvt:
3144 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3146 case CCValAssign::FPExt:
3147 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3151 if (VA.isRegLoc()) {
3152 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3153 Outs[0].VT == MVT::i64) {
3154 assert(VA.getLocVT() == MVT::i64 &&
3155 "unexpected calling convention register assignment");
3156 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3157 "unexpected use of 'returned'");
3158 IsThisReturn = true;
3160 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3162 assert(VA.isMemLoc());
3165 MachinePointerInfo DstInfo;
3167 // FIXME: This works on big-endian for composite byvals, which are the
3168 // common case. It should also work for fundamental types too.
3169 uint32_t BEAlign = 0;
3170 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3171 : VA.getValVT().getSizeInBits();
3172 OpSize = (OpSize + 7) / 8;
3173 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3174 !Flags.isInConsecutiveRegs()) {
3176 BEAlign = 8 - OpSize;
3178 unsigned LocMemOffset = VA.getLocMemOffset();
3179 int32_t Offset = LocMemOffset + BEAlign;
3180 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3181 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3184 Offset = Offset + FPDiff;
3185 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3187 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3189 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3191 // Make sure any stack arguments overlapping with where we're storing
3192 // are loaded before this eventual operation. Otherwise they'll be
3194 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3196 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3198 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3199 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3203 if (Outs[i].Flags.isByVal()) {
3205 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3206 SDValue Cpy = DAG.getMemcpy(
3207 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3208 /*isVol = */ false, /*AlwaysInline = */ false,
3209 /*isTailCall = */ false,
3210 DstInfo, MachinePointerInfo());
3212 MemOpChains.push_back(Cpy);
3214 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3215 // promoted to a legal register type i32, we should truncate Arg back to
3217 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3218 VA.getValVT() == MVT::i16)
3219 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3221 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3222 MemOpChains.push_back(Store);
3227 if (!MemOpChains.empty())
3228 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3230 // Build a sequence of copy-to-reg nodes chained together with token chain
3231 // and flag operands which copy the outgoing args into the appropriate regs.
3233 for (auto &RegToPass : RegsToPass) {
3234 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3235 RegToPass.second, InFlag);
3236 InFlag = Chain.getValue(1);
3239 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3240 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3241 // node so that legalize doesn't hack it.
3242 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3243 auto GV = G->getGlobal();
3244 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3245 AArch64II::MO_GOT) {
3246 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3247 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3249 const GlobalValue *GV = G->getGlobal();
3250 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3252 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3253 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3254 Subtarget->isTargetMachO()) {
3255 const char *Sym = S->getSymbol();
3256 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3257 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3259 const char *Sym = S->getSymbol();
3260 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3264 // We don't usually want to end the call-sequence here because we would tidy
3265 // the frame up *after* the call, however in the ABI-changing tail-call case
3266 // we've carefully laid out the parameters so that when sp is reset they'll be
3267 // in the correct location.
3268 if (IsTailCall && !IsSibCall) {
3269 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3270 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3271 InFlag = Chain.getValue(1);
3274 std::vector<SDValue> Ops;
3275 Ops.push_back(Chain);
3276 Ops.push_back(Callee);
3279 // Each tail call may have to adjust the stack by a different amount, so
3280 // this information must travel along with the operation for eventual
3281 // consumption by emitEpilogue.
3282 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3285 // Add argument registers to the end of the list so that they are known live
3287 for (auto &RegToPass : RegsToPass)
3288 Ops.push_back(DAG.getRegister(RegToPass.first,
3289 RegToPass.second.getValueType()));
3291 // Add a register mask operand representing the call-preserved registers.
3292 const uint32_t *Mask;
3293 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3295 // For 'this' returns, use the X0-preserving mask if applicable
3296 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3298 IsThisReturn = false;
3299 Mask = TRI->getCallPreservedMask(MF, CallConv);
3302 Mask = TRI->getCallPreservedMask(MF, CallConv);
3304 assert(Mask && "Missing call preserved mask for calling convention");
3305 Ops.push_back(DAG.getRegisterMask(Mask));
3307 if (InFlag.getNode())
3308 Ops.push_back(InFlag);
3310 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3312 // If we're doing a tall call, use a TC_RETURN here rather than an
3313 // actual call instruction.
3315 MF.getFrameInfo().setHasTailCall();
3316 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3319 // Returns a chain and a flag for retval copy to use.
3320 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3321 InFlag = Chain.getValue(1);
3323 uint64_t CalleePopBytes =
3324 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3326 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3327 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3330 InFlag = Chain.getValue(1);
3332 // Handle result values, copying them out of physregs into vregs that we
3334 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3335 InVals, IsThisReturn,
3336 IsThisReturn ? OutVals[0] : SDValue());
3339 bool AArch64TargetLowering::CanLowerReturn(
3340 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3341 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3342 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3343 ? RetCC_AArch64_WebKit_JS
3344 : RetCC_AArch64_AAPCS;
3345 SmallVector<CCValAssign, 16> RVLocs;
3346 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3347 return CCInfo.CheckReturn(Outs, RetCC);
3351 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3353 const SmallVectorImpl<ISD::OutputArg> &Outs,
3354 const SmallVectorImpl<SDValue> &OutVals,
3355 const SDLoc &DL, SelectionDAG &DAG) const {
3356 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3357 ? RetCC_AArch64_WebKit_JS
3358 : RetCC_AArch64_AAPCS;
3359 SmallVector<CCValAssign, 16> RVLocs;
3360 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3362 CCInfo.AnalyzeReturn(Outs, RetCC);
3364 // Copy the result values into the output registers.
3366 SmallVector<SDValue, 4> RetOps(1, Chain);
3367 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3368 ++i, ++realRVLocIdx) {
3369 CCValAssign &VA = RVLocs[i];
3370 assert(VA.isRegLoc() && "Can only return in registers!");
3371 SDValue Arg = OutVals[realRVLocIdx];
3373 switch (VA.getLocInfo()) {
3375 llvm_unreachable("Unknown loc info!");
3376 case CCValAssign::Full:
3377 if (Outs[i].ArgVT == MVT::i1) {
3378 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3379 // value. This is strictly redundant on Darwin (which uses "zeroext
3380 // i1"), but will be optimised out before ISel.
3381 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3382 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3385 case CCValAssign::BCvt:
3386 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3390 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3391 Flag = Chain.getValue(1);
3392 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3394 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3395 const MCPhysReg *I =
3396 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3399 if (AArch64::GPR64RegClass.contains(*I))
3400 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3401 else if (AArch64::FPR64RegClass.contains(*I))
3402 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3404 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3408 RetOps[0] = Chain; // Update chain.
3410 // Add the flag if we have it.
3412 RetOps.push_back(Flag);
3414 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3417 //===----------------------------------------------------------------------===//
3418 // Other Lowering Code
3419 //===----------------------------------------------------------------------===//
3421 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3422 SelectionDAG &DAG) const {
3423 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3425 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3426 const GlobalValue *GV = GN->getGlobal();
3427 unsigned char OpFlags =
3428 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3430 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3431 "unexpected offset in global node");
3433 // This also catched the large code model case for Darwin.
3434 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3435 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3436 // FIXME: Once remat is capable of dealing with instructions with register
3437 // operands, expand this into two nodes instead of using a wrapper node.
3438 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3441 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3442 const unsigned char MO_NC = AArch64II::MO_NC;
3444 AArch64ISD::WrapperLarge, DL, PtrVT,
3445 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3446 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3447 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3448 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3450 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3451 // the only correct model on Darwin.
3452 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3453 OpFlags | AArch64II::MO_PAGE);
3454 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3455 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3457 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3458 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3462 /// \brief Convert a TLS address reference into the correct sequence of loads
3463 /// and calls to compute the variable's address (for Darwin, currently) and
3464 /// return an SDValue containing the final node.
3466 /// Darwin only has one TLS scheme which must be capable of dealing with the
3467 /// fully general situation, in the worst case. This means:
3468 /// + "extern __thread" declaration.
3469 /// + Defined in a possibly unknown dynamic library.
3471 /// The general system is that each __thread variable has a [3 x i64] descriptor
3472 /// which contains information used by the runtime to calculate the address. The
3473 /// only part of this the compiler needs to know about is the first xword, which
3474 /// contains a function pointer that must be called with the address of the
3475 /// entire descriptor in "x0".
3477 /// Since this descriptor may be in a different unit, in general even the
3478 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3480 /// adrp x0, _var@TLVPPAGE
3481 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3482 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3483 /// ; the function pointer
3484 /// blr x1 ; Uses descriptor address in x0
3485 /// ; Address of _var is now in x0.
3487 /// If the address of _var's descriptor *is* known to the linker, then it can
3488 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3489 /// a slight efficiency gain.
3491 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3492 SelectionDAG &DAG) const {
3493 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3496 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3497 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3500 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3501 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3503 // The first entry in the descriptor is a function pointer that we must call
3504 // to obtain the address of the variable.
3505 SDValue Chain = DAG.getEntryNode();
3506 SDValue FuncTLVGet = DAG.getLoad(
3507 MVT::i64, DL, Chain, DescAddr,
3508 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3509 /* Alignment = */ 8,
3510 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3511 MachineMemOperand::MODereferenceable);
3512 Chain = FuncTLVGet.getValue(1);
3514 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3515 MFI.setAdjustsStack(true);
3517 // TLS calls preserve all registers except those that absolutely must be
3518 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3520 const uint32_t *Mask =
3521 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3523 // Finally, we can make the call. This is just a degenerate version of a
3524 // normal AArch64 call node: x0 takes the address of the descriptor, and
3525 // returns the address of the variable in this thread.
3526 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3528 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3529 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3530 DAG.getRegisterMask(Mask), Chain.getValue(1));
3531 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3534 /// When accessing thread-local variables under either the general-dynamic or
3535 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3536 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3537 /// is a function pointer to carry out the resolution.
3539 /// The sequence is:
3540 /// adrp x0, :tlsdesc:var
3541 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3542 /// add x0, x0, #:tlsdesc_lo12:var
3543 /// .tlsdesccall var
3545 /// (TPIDR_EL0 offset now in x0)
3547 /// The above sequence must be produced unscheduled, to enable the linker to
3548 /// optimize/relax this sequence.
3549 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3550 /// above sequence, and expanded really late in the compilation flow, to ensure
3551 /// the sequence is produced as per above.
3552 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3554 SelectionDAG &DAG) const {
3555 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3557 SDValue Chain = DAG.getEntryNode();
3558 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3561 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3562 SDValue Glue = Chain.getValue(1);
3564 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3568 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3569 SelectionDAG &DAG) const {
3570 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3571 assert(Subtarget->useSmallAddressing() &&
3572 "ELF TLS only supported in small memory model");
3573 // Different choices can be made for the maximum size of the TLS area for a
3574 // module. For the small address model, the default TLS size is 16MiB and the
3575 // maximum TLS size is 4GiB.
3576 // FIXME: add -mtls-size command line option and make it control the 16MiB
3577 // vs. 4GiB code sequence generation.
3578 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3580 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3582 if (DAG.getTarget().Options.EmulatedTLS)
3583 return LowerToTLSEmulatedModel(GA, DAG);
3585 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3586 if (Model == TLSModel::LocalDynamic)
3587 Model = TLSModel::GeneralDynamic;
3591 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3593 const GlobalValue *GV = GA->getGlobal();
3595 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3597 if (Model == TLSModel::LocalExec) {
3598 SDValue HiVar = DAG.getTargetGlobalAddress(
3599 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3600 SDValue LoVar = DAG.getTargetGlobalAddress(
3602 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3604 SDValue TPWithOff_lo =
3605 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3607 DAG.getTargetConstant(0, DL, MVT::i32)),
3610 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3612 DAG.getTargetConstant(0, DL, MVT::i32)),
3615 } else if (Model == TLSModel::InitialExec) {
3616 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3617 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3618 } else if (Model == TLSModel::LocalDynamic) {
3619 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3620 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3621 // the beginning of the module's TLS region, followed by a DTPREL offset
3624 // These accesses will need deduplicating if there's more than one.
3625 AArch64FunctionInfo *MFI =
3626 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3627 MFI->incNumLocalDynamicTLSAccesses();
3629 // The call needs a relocation too for linker relaxation. It doesn't make
3630 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3632 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3635 // Now we can calculate the offset from TPIDR_EL0 to this module's
3636 // thread-local area.
3637 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3639 // Now use :dtprel_whatever: operations to calculate this variable's offset
3640 // in its thread-storage area.
3641 SDValue HiVar = DAG.getTargetGlobalAddress(
3642 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3643 SDValue LoVar = DAG.getTargetGlobalAddress(
3644 GV, DL, MVT::i64, 0,
3645 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3647 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3648 DAG.getTargetConstant(0, DL, MVT::i32)),
3650 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3651 DAG.getTargetConstant(0, DL, MVT::i32)),
3653 } else if (Model == TLSModel::GeneralDynamic) {
3654 // The call needs a relocation too for linker relaxation. It doesn't make
3655 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3658 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3660 // Finally we can make a call to calculate the offset from tpidr_el0.
3661 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3663 llvm_unreachable("Unsupported ELF TLS access model");
3665 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3668 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3669 SelectionDAG &DAG) const {
3670 if (Subtarget->isTargetDarwin())
3671 return LowerDarwinGlobalTLSAddress(Op, DAG);
3672 if (Subtarget->isTargetELF())
3673 return LowerELFGlobalTLSAddress(Op, DAG);
3675 llvm_unreachable("Unexpected platform trying to use TLS");
3678 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3679 SDValue Chain = Op.getOperand(0);
3680 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3681 SDValue LHS = Op.getOperand(2);
3682 SDValue RHS = Op.getOperand(3);
3683 SDValue Dest = Op.getOperand(4);
3686 // Handle f128 first, since lowering it will result in comparing the return
3687 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3688 // is expecting to deal with.
3689 if (LHS.getValueType() == MVT::f128) {
3690 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3692 // If softenSetCCOperands returned a scalar, we need to compare the result
3693 // against zero to select between true and false values.
3694 if (!RHS.getNode()) {
3695 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3700 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3702 unsigned Opc = LHS.getOpcode();
3703 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3704 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3705 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3706 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3707 "Unexpected condition code.");
3708 // Only lower legal XALUO ops.
3709 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3712 // The actual operation with overflow check.
3713 AArch64CC::CondCode OFCC;
3714 SDValue Value, Overflow;
3715 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3717 if (CC == ISD::SETNE)
3718 OFCC = getInvertedCondCode(OFCC);
3719 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3721 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3725 if (LHS.getValueType().isInteger()) {
3726 assert((LHS.getValueType() == RHS.getValueType()) &&
3727 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3729 // If the RHS of the comparison is zero, we can potentially fold this
3730 // to a specialized branch.
3731 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3732 if (RHSC && RHSC->getZExtValue() == 0) {
3733 if (CC == ISD::SETEQ) {
3734 // See if we can use a TBZ to fold in an AND as well.
3735 // TBZ has a smaller branch displacement than CBZ. If the offset is
3736 // out of bounds, a late MI-layer pass rewrites branches.
3737 // 403.gcc is an example that hits this case.
3738 if (LHS.getOpcode() == ISD::AND &&
3739 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3740 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3741 SDValue Test = LHS.getOperand(0);
3742 uint64_t Mask = LHS.getConstantOperandVal(1);
3743 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3744 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3748 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3749 } else if (CC == ISD::SETNE) {
3750 // See if we can use a TBZ to fold in an AND as well.
3751 // TBZ has a smaller branch displacement than CBZ. If the offset is
3752 // out of bounds, a late MI-layer pass rewrites branches.
3753 // 403.gcc is an example that hits this case.
3754 if (LHS.getOpcode() == ISD::AND &&
3755 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3756 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3757 SDValue Test = LHS.getOperand(0);
3758 uint64_t Mask = LHS.getConstantOperandVal(1);
3759 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3760 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3764 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3765 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3766 // Don't combine AND since emitComparison converts the AND to an ANDS
3767 // (a.k.a. TST) and the test in the test bit and branch instruction
3768 // becomes redundant. This would also increase register pressure.
3769 uint64_t Mask = LHS.getValueSizeInBits() - 1;
3770 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3771 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3774 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3775 LHS.getOpcode() != ISD::AND) {
3776 // Don't combine AND since emitComparison converts the AND to an ANDS
3777 // (a.k.a. TST) and the test in the test bit and branch instruction
3778 // becomes redundant. This would also increase register pressure.
3779 uint64_t Mask = LHS.getValueSizeInBits() - 1;
3780 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3781 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3785 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3786 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3790 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3792 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3793 // clean. Some of them require two branches to implement.
3794 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3795 AArch64CC::CondCode CC1, CC2;
3796 changeFPCCToAArch64CC(CC, CC1, CC2);
3797 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3799 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3800 if (CC2 != AArch64CC::AL) {
3801 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3802 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3809 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3810 SelectionDAG &DAG) const {
3811 EVT VT = Op.getValueType();
3814 SDValue In1 = Op.getOperand(0);
3815 SDValue In2 = Op.getOperand(1);
3816 EVT SrcVT = In2.getValueType();
3818 if (SrcVT.bitsLT(VT))
3819 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3820 else if (SrcVT.bitsGT(VT))
3821 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3826 SDValue VecVal1, VecVal2;
3827 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3829 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3830 EltMask = 0x80000000ULL;
3832 if (!VT.isVector()) {
3833 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3834 DAG.getUNDEF(VecVT), In1);
3835 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3836 DAG.getUNDEF(VecVT), In2);
3838 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3839 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3841 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3845 // We want to materialize a mask with the high bit set, but the AdvSIMD
3846 // immediate moves cannot materialize that in a single instruction for
3847 // 64-bit elements. Instead, materialize zero and then negate it.
3850 if (!VT.isVector()) {
3851 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3852 DAG.getUNDEF(VecVT), In1);
3853 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3854 DAG.getUNDEF(VecVT), In2);
3856 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3857 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3860 llvm_unreachable("Invalid type for copysign!");
3863 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3865 // If we couldn't materialize the mask above, then the mask vector will be
3866 // the zero vector, and we need to negate it here.
3867 if (VT == MVT::f64 || VT == MVT::v2f64) {
3868 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3869 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3870 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3874 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3877 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3878 else if (VT == MVT::f64)
3879 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3881 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3884 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3885 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3886 Attribute::NoImplicitFloat))
3889 if (!Subtarget->hasNEON())
3892 // While there is no integer popcount instruction, it can
3893 // be more efficiently lowered to the following sequence that uses
3894 // AdvSIMD registers/instructions as long as the copies to/from
3895 // the AdvSIMD registers are cheap.
3896 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3897 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3898 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3899 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3900 SDValue Val = Op.getOperand(0);
3902 EVT VT = Op.getValueType();
3905 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3906 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3908 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3909 SDValue UaddLV = DAG.getNode(
3910 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3911 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3914 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3918 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3920 if (Op.getValueType().isVector())
3921 return LowerVSETCC(Op, DAG);
3923 SDValue LHS = Op.getOperand(0);
3924 SDValue RHS = Op.getOperand(1);
3925 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3928 // We chose ZeroOrOneBooleanContents, so use zero and one.
3929 EVT VT = Op.getValueType();
3930 SDValue TVal = DAG.getConstant(1, dl, VT);
3931 SDValue FVal = DAG.getConstant(0, dl, VT);
3933 // Handle f128 first, since one possible outcome is a normal integer
3934 // comparison which gets picked up by the next if statement.
3935 if (LHS.getValueType() == MVT::f128) {
3936 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3938 // If softenSetCCOperands returned a scalar, use it.
3939 if (!RHS.getNode()) {
3940 assert(LHS.getValueType() == Op.getValueType() &&
3941 "Unexpected setcc expansion!");
3946 if (LHS.getValueType().isInteger()) {
3949 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3951 // Note that we inverted the condition above, so we reverse the order of
3952 // the true and false operands here. This will allow the setcc to be
3953 // matched to a single CSINC instruction.
3954 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3957 // Now we know we're dealing with FP values.
3958 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3960 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3961 // and do the comparison.
3962 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3964 AArch64CC::CondCode CC1, CC2;
3965 changeFPCCToAArch64CC(CC, CC1, CC2);
3966 if (CC2 == AArch64CC::AL) {
3967 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3968 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3970 // Note that we inverted the condition above, so we reverse the order of
3971 // the true and false operands here. This will allow the setcc to be
3972 // matched to a single CSINC instruction.
3973 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3975 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3976 // totally clean. Some of them require two CSELs to implement. As is in
3977 // this case, we emit the first CSEL and then emit a second using the output
3978 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3980 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3981 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3983 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3985 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3986 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3990 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3991 SDValue RHS, SDValue TVal,
3992 SDValue FVal, const SDLoc &dl,
3993 SelectionDAG &DAG) const {
3994 // Handle f128 first, because it will result in a comparison of some RTLIB
3995 // call result against zero.
3996 if (LHS.getValueType() == MVT::f128) {
3997 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3999 // If softenSetCCOperands returned a scalar, we need to compare the result
4000 // against zero to select between true and false values.
4001 if (!RHS.getNode()) {
4002 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4007 // Also handle f16, for which we need to do a f32 comparison.
4008 if (LHS.getValueType() == MVT::f16) {
4009 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4010 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4013 // Next, handle integers.
4014 if (LHS.getValueType().isInteger()) {
4015 assert((LHS.getValueType() == RHS.getValueType()) &&
4016 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4018 unsigned Opcode = AArch64ISD::CSEL;
4020 // If both the TVal and the FVal are constants, see if we can swap them in
4021 // order to for a CSINV or CSINC out of them.
4022 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4023 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4025 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4026 std::swap(TVal, FVal);
4027 std::swap(CTVal, CFVal);
4028 CC = ISD::getSetCCInverse(CC, true);
4029 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4030 std::swap(TVal, FVal);
4031 std::swap(CTVal, CFVal);
4032 CC = ISD::getSetCCInverse(CC, true);
4033 } else if (TVal.getOpcode() == ISD::XOR) {
4034 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4035 // with a CSINV rather than a CSEL.
4036 if (isAllOnesConstant(TVal.getOperand(1))) {
4037 std::swap(TVal, FVal);
4038 std::swap(CTVal, CFVal);
4039 CC = ISD::getSetCCInverse(CC, true);
4041 } else if (TVal.getOpcode() == ISD::SUB) {
4042 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4043 // that we can match with a CSNEG rather than a CSEL.
4044 if (isNullConstant(TVal.getOperand(0))) {
4045 std::swap(TVal, FVal);
4046 std::swap(CTVal, CFVal);
4047 CC = ISD::getSetCCInverse(CC, true);
4049 } else if (CTVal && CFVal) {
4050 const int64_t TrueVal = CTVal->getSExtValue();
4051 const int64_t FalseVal = CFVal->getSExtValue();
4054 // If both TVal and FVal are constants, see if FVal is the
4055 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4056 // instead of a CSEL in that case.
4057 if (TrueVal == ~FalseVal) {
4058 Opcode = AArch64ISD::CSINV;
4059 } else if (TrueVal == -FalseVal) {
4060 Opcode = AArch64ISD::CSNEG;
4061 } else if (TVal.getValueType() == MVT::i32) {
4062 // If our operands are only 32-bit wide, make sure we use 32-bit
4063 // arithmetic for the check whether we can use CSINC. This ensures that
4064 // the addition in the check will wrap around properly in case there is
4065 // an overflow (which would not be the case if we do the check with
4066 // 64-bit arithmetic).
4067 const uint32_t TrueVal32 = CTVal->getZExtValue();
4068 const uint32_t FalseVal32 = CFVal->getZExtValue();
4070 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4071 Opcode = AArch64ISD::CSINC;
4073 if (TrueVal32 > FalseVal32) {
4077 // 64-bit check whether we can use CSINC.
4078 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4079 Opcode = AArch64ISD::CSINC;
4081 if (TrueVal > FalseVal) {
4086 // Swap TVal and FVal if necessary.
4088 std::swap(TVal, FVal);
4089 std::swap(CTVal, CFVal);
4090 CC = ISD::getSetCCInverse(CC, true);
4093 if (Opcode != AArch64ISD::CSEL) {
4094 // Drop FVal since we can get its value by simply inverting/negating
4100 // Avoid materializing a constant when possible by reusing a known value in
4101 // a register. However, don't perform this optimization if the known value
4102 // is one, zero or negative one in the case of a CSEL. We can always
4103 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4104 // FVal, respectively.
4105 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4106 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4107 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4108 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4109 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4110 // "a != C ? x : a" to avoid materializing C.
4111 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4113 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4115 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4116 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4117 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4118 // avoid materializing C.
4119 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4120 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4121 Opcode = AArch64ISD::CSINV;
4123 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4128 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4130 EVT VT = TVal.getValueType();
4131 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4134 // Now we know we're dealing with FP values.
4135 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4136 assert(LHS.getValueType() == RHS.getValueType());
4137 EVT VT = TVal.getValueType();
4138 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4140 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4141 // clean. Some of them require two CSELs to implement.
4142 AArch64CC::CondCode CC1, CC2;
4143 changeFPCCToAArch64CC(CC, CC1, CC2);
4145 if (DAG.getTarget().Options.UnsafeFPMath) {
4146 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4147 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4148 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4149 if (RHSVal && RHSVal->isZero()) {
4150 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4151 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4153 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4154 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4156 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4157 CFVal && CFVal->isZero() &&
4158 FVal.getValueType() == LHS.getValueType())
4163 // Emit first, and possibly only, CSEL.
4164 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4165 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4167 // If we need a second CSEL, emit it, using the output of the first as the
4168 // RHS. We're effectively OR'ing the two CC's together.
4169 if (CC2 != AArch64CC::AL) {
4170 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4171 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4174 // Otherwise, return the output of the first CSEL.
4178 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4179 SelectionDAG &DAG) const {
4180 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4181 SDValue LHS = Op.getOperand(0);
4182 SDValue RHS = Op.getOperand(1);
4183 SDValue TVal = Op.getOperand(2);
4184 SDValue FVal = Op.getOperand(3);
4186 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4189 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4190 SelectionDAG &DAG) const {
4191 SDValue CCVal = Op->getOperand(0);
4192 SDValue TVal = Op->getOperand(1);
4193 SDValue FVal = Op->getOperand(2);
4196 unsigned Opc = CCVal.getOpcode();
4197 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4199 if (CCVal.getResNo() == 1 &&
4200 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4201 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4202 // Only lower legal XALUO ops.
4203 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4206 AArch64CC::CondCode OFCC;
4207 SDValue Value, Overflow;
4208 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4209 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4211 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4215 // Lower it the same way as we would lower a SELECT_CC node.
4218 if (CCVal.getOpcode() == ISD::SETCC) {
4219 LHS = CCVal.getOperand(0);
4220 RHS = CCVal.getOperand(1);
4221 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4224 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4227 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4230 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4231 SelectionDAG &DAG) const {
4232 // Jump table entries as PC relative offsets. No additional tweaking
4233 // is necessary here. Just get the address of the jump table.
4234 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4235 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4238 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4239 !Subtarget->isTargetMachO()) {
4240 const unsigned char MO_NC = AArch64II::MO_NC;
4242 AArch64ISD::WrapperLarge, DL, PtrVT,
4243 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4244 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4245 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4246 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4247 AArch64II::MO_G0 | MO_NC));
4251 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4252 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4253 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4254 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4255 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4258 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4259 SelectionDAG &DAG) const {
4260 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4261 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4264 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4265 // Use the GOT for the large code model on iOS.
4266 if (Subtarget->isTargetMachO()) {
4267 SDValue GotAddr = DAG.getTargetConstantPool(
4268 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4270 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4273 const unsigned char MO_NC = AArch64II::MO_NC;
4275 AArch64ISD::WrapperLarge, DL, PtrVT,
4276 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4277 CP->getOffset(), AArch64II::MO_G3),
4278 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4279 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4280 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4281 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4282 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4283 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4285 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4286 // ELF, the only valid one on Darwin.
4288 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4289 CP->getOffset(), AArch64II::MO_PAGE);
4290 SDValue Lo = DAG.getTargetConstantPool(
4291 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4292 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4294 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4295 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4299 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4300 SelectionDAG &DAG) const {
4301 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4302 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4304 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4305 !Subtarget->isTargetMachO()) {
4306 const unsigned char MO_NC = AArch64II::MO_NC;
4308 AArch64ISD::WrapperLarge, DL, PtrVT,
4309 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4310 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4311 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4312 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4314 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4315 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4317 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4318 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4322 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4323 SelectionDAG &DAG) const {
4324 AArch64FunctionInfo *FuncInfo =
4325 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4328 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4329 getPointerTy(DAG.getDataLayout()));
4330 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4331 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4332 MachinePointerInfo(SV));
4335 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4336 SelectionDAG &DAG) const {
4337 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4338 // Standard, section B.3.
4339 MachineFunction &MF = DAG.getMachineFunction();
4340 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4341 auto PtrVT = getPointerTy(DAG.getDataLayout());
4344 SDValue Chain = Op.getOperand(0);
4345 SDValue VAList = Op.getOperand(1);
4346 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4347 SmallVector<SDValue, 4> MemOps;
4349 // void *__stack at offset 0
4350 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4351 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4352 MachinePointerInfo(SV), /* Alignment = */ 8));
4354 // void *__gr_top at offset 8
4355 int GPRSize = FuncInfo->getVarArgsGPRSize();
4357 SDValue GRTop, GRTopAddr;
4360 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4362 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4363 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4364 DAG.getConstant(GPRSize, DL, PtrVT));
4366 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4367 MachinePointerInfo(SV, 8),
4368 /* Alignment = */ 8));
4371 // void *__vr_top at offset 16
4372 int FPRSize = FuncInfo->getVarArgsFPRSize();
4374 SDValue VRTop, VRTopAddr;
4375 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4376 DAG.getConstant(16, DL, PtrVT));
4378 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4379 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4380 DAG.getConstant(FPRSize, DL, PtrVT));
4382 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4383 MachinePointerInfo(SV, 16),
4384 /* Alignment = */ 8));
4387 // int __gr_offs at offset 24
4388 SDValue GROffsAddr =
4389 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4390 MemOps.push_back(DAG.getStore(
4391 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4392 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4394 // int __vr_offs at offset 28
4395 SDValue VROffsAddr =
4396 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4397 MemOps.push_back(DAG.getStore(
4398 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4399 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4401 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4404 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4405 SelectionDAG &DAG) const {
4406 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4407 : LowerAAPCS_VASTART(Op, DAG);
4410 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4411 SelectionDAG &DAG) const {
4412 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4415 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4416 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4417 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4419 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4421 DAG.getConstant(VaListSize, DL, MVT::i32),
4422 8, false, false, false, MachinePointerInfo(DestSV),
4423 MachinePointerInfo(SrcSV));
4426 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4427 assert(Subtarget->isTargetDarwin() &&
4428 "automatic va_arg instruction only works on Darwin");
4430 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4431 EVT VT = Op.getValueType();
4433 SDValue Chain = Op.getOperand(0);
4434 SDValue Addr = Op.getOperand(1);
4435 unsigned Align = Op.getConstantOperandVal(3);
4436 auto PtrVT = getPointerTy(DAG.getDataLayout());
4438 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4439 Chain = VAList.getValue(1);
4442 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4443 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4444 DAG.getConstant(Align - 1, DL, PtrVT));
4445 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4446 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4449 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4450 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4452 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4453 // up to 64 bits. At the very least, we have to increase the striding of the
4454 // vaargs list to match this, and for FP values we need to introduce
4455 // FP_ROUND nodes as well.
4456 if (VT.isInteger() && !VT.isVector())
4458 bool NeedFPTrunc = false;
4459 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4464 // Increment the pointer, VAList, to the next vaarg
4465 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4466 DAG.getConstant(ArgSize, DL, PtrVT));
4467 // Store the incremented VAList to the legalized pointer
4469 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4471 // Load the actual argument out of the pointer VAList
4473 // Load the value as an f64.
4475 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4476 // Round the value down to an f32.
4477 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4478 DAG.getIntPtrConstant(1, DL));
4479 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4480 // Merge the rounded value with the chain output of the load.
4481 return DAG.getMergeValues(Ops, DL);
4484 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4487 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4488 SelectionDAG &DAG) const {
4489 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4490 MFI.setFrameAddressIsTaken(true);
4492 EVT VT = Op.getValueType();
4494 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4496 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4498 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4499 MachinePointerInfo());
4503 // FIXME? Maybe this could be a TableGen attribute on some registers and
4504 // this table could be generated automatically from RegInfo.
4505 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4506 SelectionDAG &DAG) const {
4507 unsigned Reg = StringSwitch<unsigned>(RegName)
4508 .Case("sp", AArch64::SP)
4509 .Case("x18", AArch64::X18)
4510 .Case("w18", AArch64::W18)
4512 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4513 !Subtarget->isX18Reserved())
4517 report_fatal_error(Twine("Invalid register name \""
4518 + StringRef(RegName) + "\"."));
4521 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4522 SelectionDAG &DAG) const {
4523 MachineFunction &MF = DAG.getMachineFunction();
4524 MachineFrameInfo &MFI = MF.getFrameInfo();
4525 MFI.setReturnAddressIsTaken(true);
4527 EVT VT = Op.getValueType();
4529 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4531 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4532 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4533 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4534 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4535 MachinePointerInfo());
4538 // Return LR, which contains the return address. Mark it an implicit live-in.
4539 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4540 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4543 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4544 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4545 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4546 SelectionDAG &DAG) const {
4547 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4548 EVT VT = Op.getValueType();
4549 unsigned VTBits = VT.getSizeInBits();
4551 SDValue ShOpLo = Op.getOperand(0);
4552 SDValue ShOpHi = Op.getOperand(1);
4553 SDValue ShAmt = Op.getOperand(2);
4554 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4556 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4558 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4559 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4560 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4562 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4563 // is "undef". We wanted 0, so CSEL it directly.
4564 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4565 ISD::SETEQ, dl, DAG);
4566 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4568 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4569 HiBitsForLo, CCVal, Cmp);
4571 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4572 DAG.getConstant(VTBits, dl, MVT::i64));
4574 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4575 SDValue LoForNormalShift =
4576 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4578 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4580 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4581 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4582 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4583 LoForNormalShift, CCVal, Cmp);
4585 // AArch64 shifts larger than the register width are wrapped rather than
4586 // clamped, so we can't just emit "hi >> x".
4587 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4588 SDValue HiForBigShift =
4590 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4591 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4592 : DAG.getConstant(0, dl, VT);
4593 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4594 HiForNormalShift, CCVal, Cmp);
4596 SDValue Ops[2] = { Lo, Hi };
4597 return DAG.getMergeValues(Ops, dl);
4600 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4601 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4602 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4603 SelectionDAG &DAG) const {
4604 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4605 EVT VT = Op.getValueType();
4606 unsigned VTBits = VT.getSizeInBits();
4608 SDValue ShOpLo = Op.getOperand(0);
4609 SDValue ShOpHi = Op.getOperand(1);
4610 SDValue ShAmt = Op.getOperand(2);
4612 assert(Op.getOpcode() == ISD::SHL_PARTS);
4613 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4614 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4615 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4617 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4618 // is "undef". We wanted 0, so CSEL it directly.
4619 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4620 ISD::SETEQ, dl, DAG);
4621 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4623 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4624 LoBitsForHi, CCVal, Cmp);
4626 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4627 DAG.getConstant(VTBits, dl, MVT::i64));
4628 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4629 SDValue HiForNormalShift =
4630 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4632 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4634 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4636 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4637 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4638 HiForNormalShift, CCVal, Cmp);
4640 // AArch64 shifts of larger than register sizes are wrapped rather than
4641 // clamped, so we can't just emit "lo << a" if a is too big.
4642 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4643 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4644 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4645 LoForNormalShift, CCVal, Cmp);
4647 SDValue Ops[2] = { Lo, Hi };
4648 return DAG.getMergeValues(Ops, dl);
4651 bool AArch64TargetLowering::isOffsetFoldingLegal(
4652 const GlobalAddressSDNode *GA) const {
4653 // The AArch64 target doesn't support folding offsets into global addresses.
4657 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4658 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4659 // FIXME: We should be able to handle f128 as well with a clever lowering.
4660 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4664 return AArch64_AM::getFP64Imm(Imm) != -1;
4665 else if (VT == MVT::f32)
4666 return AArch64_AM::getFP32Imm(Imm) != -1;
4670 //===----------------------------------------------------------------------===//
4671 // AArch64 Optimization Hooks
4672 //===----------------------------------------------------------------------===//
4674 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4675 SDValue Operand, SelectionDAG &DAG,
4677 EVT VT = Operand.getValueType();
4678 if (ST->hasNEON() &&
4679 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4680 VT == MVT::f32 || VT == MVT::v1f32 ||
4681 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4682 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4683 // For the reciprocal estimates, convergence is quadratic, so the number
4684 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4685 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4686 // the result for float (23 mantissa bits) is 2 and for double (52
4687 // mantissa bits) is 3.
4688 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4690 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4696 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4697 SelectionDAG &DAG, int Enabled,
4700 bool Reciprocal) const {
4701 if (Enabled == ReciprocalEstimate::Enabled ||
4702 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4703 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4706 EVT VT = Operand.getValueType();
4709 Flags.setUnsafeAlgebra(true);
4711 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4712 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4713 for (int i = ExtraSteps; i > 0; --i) {
4714 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4716 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4717 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4721 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4723 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4724 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4726 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4727 // Correct the result if the operand is 0.0.
4728 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4729 VT, Eq, Operand, Estimate);
4739 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4740 SelectionDAG &DAG, int Enabled,
4741 int &ExtraSteps) const {
4742 if (Enabled == ReciprocalEstimate::Enabled)
4743 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4746 EVT VT = Operand.getValueType();
4749 Flags.setUnsafeAlgebra(true);
4751 // Newton reciprocal iteration: E * (2 - X * E)
4752 // AArch64 reciprocal iteration instruction: (2 - M * N)
4753 for (int i = ExtraSteps; i > 0; --i) {
4754 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4756 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4766 //===----------------------------------------------------------------------===//
4767 // AArch64 Inline Assembly Support
4768 //===----------------------------------------------------------------------===//
4770 // Table of Constraints
4771 // TODO: This is the current set of constraints supported by ARM for the
4772 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4774 // r - A general register
4775 // w - An FP/SIMD register of some size in the range v0-v31
4776 // x - An FP/SIMD register of some size in the range v0-v15
4777 // I - Constant that can be used with an ADD instruction
4778 // J - Constant that can be used with a SUB instruction
4779 // K - Constant that can be used with a 32-bit logical instruction
4780 // L - Constant that can be used with a 64-bit logical instruction
4781 // M - Constant that can be used as a 32-bit MOV immediate
4782 // N - Constant that can be used as a 64-bit MOV immediate
4783 // Q - A memory reference with base register and no offset
4784 // S - A symbolic address
4785 // Y - Floating point constant zero
4786 // Z - Integer constant zero
4788 // Note that general register operands will be output using their 64-bit x
4789 // register name, whatever the size of the variable, unless the asm operand
4790 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4791 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4793 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4794 // At this point, we have to lower this constraint to something else, so we
4795 // lower it to an "r" or "w". However, by doing this we will force the result
4796 // to be in register, while the X constraint is much more permissive.
4798 // Although we are correct (we are free to emit anything, without
4799 // constraints), we might break use cases that would expect us to be more
4800 // efficient and emit something else.
4801 if (!Subtarget->hasFPARMv8())
4804 if (ConstraintVT.isFloatingPoint())
4807 if (ConstraintVT.isVector() &&
4808 (ConstraintVT.getSizeInBits() == 64 ||
4809 ConstraintVT.getSizeInBits() == 128))
4815 /// getConstraintType - Given a constraint letter, return the type of
4816 /// constraint it is for this target.
4817 AArch64TargetLowering::ConstraintType
4818 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4819 if (Constraint.size() == 1) {
4820 switch (Constraint[0]) {
4827 return C_RegisterClass;
4828 // An address with a single base register. Due to the way we
4829 // currently handle addresses it is the same as 'r'.
4834 return TargetLowering::getConstraintType(Constraint);
4837 /// Examine constraint type and operand type and determine a weight value.
4838 /// This object must already have been set up with the operand type
4839 /// and the current alternative constraint selected.
4840 TargetLowering::ConstraintWeight
4841 AArch64TargetLowering::getSingleConstraintMatchWeight(
4842 AsmOperandInfo &info, const char *constraint) const {
4843 ConstraintWeight weight = CW_Invalid;
4844 Value *CallOperandVal = info.CallOperandVal;
4845 // If we don't have a value, we can't do a match,
4846 // but allow it at the lowest weight.
4847 if (!CallOperandVal)
4849 Type *type = CallOperandVal->getType();
4850 // Look at the constraint type.
4851 switch (*constraint) {
4853 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4857 if (type->isFloatingPointTy() || type->isVectorTy())
4858 weight = CW_Register;
4861 weight = CW_Constant;
4867 std::pair<unsigned, const TargetRegisterClass *>
4868 AArch64TargetLowering::getRegForInlineAsmConstraint(
4869 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4870 if (Constraint.size() == 1) {
4871 switch (Constraint[0]) {
4873 if (VT.getSizeInBits() == 64)
4874 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4875 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4877 if (VT.getSizeInBits() == 16)
4878 return std::make_pair(0U, &AArch64::FPR16RegClass);
4879 if (VT.getSizeInBits() == 32)
4880 return std::make_pair(0U, &AArch64::FPR32RegClass);
4881 if (VT.getSizeInBits() == 64)
4882 return std::make_pair(0U, &AArch64::FPR64RegClass);
4883 if (VT.getSizeInBits() == 128)
4884 return std::make_pair(0U, &AArch64::FPR128RegClass);
4886 // The instructions that this constraint is designed for can
4887 // only take 128-bit registers so just use that regclass.
4889 if (VT.getSizeInBits() == 128)
4890 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4894 if (StringRef("{cc}").equals_lower(Constraint))
4895 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4897 // Use the default implementation in TargetLowering to convert the register
4898 // constraint into a member of a register class.
4899 std::pair<unsigned, const TargetRegisterClass *> Res;
4900 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4902 // Not found as a standard register?
4904 unsigned Size = Constraint.size();
4905 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4906 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4908 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4909 if (!Failed && RegNo >= 0 && RegNo <= 31) {
4910 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
4911 // By default we'll emit v0-v31 for this unless there's a modifier where
4912 // we'll emit the correct register as well.
4913 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4914 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4915 Res.second = &AArch64::FPR64RegClass;
4917 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4918 Res.second = &AArch64::FPR128RegClass;
4927 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4928 /// vector. If it is invalid, don't add anything to Ops.
4929 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4930 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4931 SelectionDAG &DAG) const {
4934 // Currently only support length 1 constraints.
4935 if (Constraint.length() != 1)
4938 char ConstraintLetter = Constraint[0];
4939 switch (ConstraintLetter) {
4943 // This set of constraints deal with valid constants for various instructions.
4944 // Validate and return a target constant for them if we can.
4946 // 'z' maps to xzr or wzr so it needs an input of 0.
4947 if (!isNullConstant(Op))
4950 if (Op.getValueType() == MVT::i64)
4951 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4953 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4963 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4967 // Grab the value and do some validation.
4968 uint64_t CVal = C->getZExtValue();
4969 switch (ConstraintLetter) {
4970 // The I constraint applies only to simple ADD or SUB immediate operands:
4971 // i.e. 0 to 4095 with optional shift by 12
4972 // The J constraint applies only to ADD or SUB immediates that would be
4973 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4974 // instruction [or vice versa], in other words -1 to -4095 with optional
4975 // left shift by 12.
4977 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4981 uint64_t NVal = -C->getSExtValue();
4982 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4983 CVal = C->getSExtValue();
4988 // The K and L constraints apply *only* to logical immediates, including
4989 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4990 // been removed and MOV should be used). So these constraints have to
4991 // distinguish between bit patterns that are valid 32-bit or 64-bit
4992 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4993 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4996 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5000 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5003 // The M and N constraints are a superset of K and L respectively, for use
5004 // with the MOV (immediate) alias. As well as the logical immediates they
5005 // also match 32 or 64-bit immediates that can be loaded either using a
5006 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5007 // (M) or 64-bit 0x1234000000000000 (N) etc.
5008 // As a note some of this code is liberally stolen from the asm parser.
5010 if (!isUInt<32>(CVal))
5012 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5014 if ((CVal & 0xFFFF) == CVal)
5016 if ((CVal & 0xFFFF0000ULL) == CVal)
5018 uint64_t NCVal = ~(uint32_t)CVal;
5019 if ((NCVal & 0xFFFFULL) == NCVal)
5021 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5026 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5028 if ((CVal & 0xFFFFULL) == CVal)
5030 if ((CVal & 0xFFFF0000ULL) == CVal)
5032 if ((CVal & 0xFFFF00000000ULL) == CVal)
5034 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5036 uint64_t NCVal = ~CVal;
5037 if ((NCVal & 0xFFFFULL) == NCVal)
5039 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5041 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5043 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5051 // All assembler immediates are 64-bit integers.
5052 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5056 if (Result.getNode()) {
5057 Ops.push_back(Result);
5061 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5064 //===----------------------------------------------------------------------===//
5065 // AArch64 Advanced SIMD Support
5066 //===----------------------------------------------------------------------===//
5068 /// WidenVector - Given a value in the V64 register class, produce the
5069 /// equivalent value in the V128 register class.
5070 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5071 EVT VT = V64Reg.getValueType();
5072 unsigned NarrowSize = VT.getVectorNumElements();
5073 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5074 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5077 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5078 V64Reg, DAG.getConstant(0, DL, MVT::i32));
5081 /// getExtFactor - Determine the adjustment factor for the position when
5082 /// generating an "extract from vector registers" instruction.
5083 static unsigned getExtFactor(SDValue &V) {
5084 EVT EltType = V.getValueType().getVectorElementType();
5085 return EltType.getSizeInBits() / 8;
5088 /// NarrowVector - Given a value in the V128 register class, produce the
5089 /// equivalent value in the V64 register class.
5090 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5091 EVT VT = V128Reg.getValueType();
5092 unsigned WideSize = VT.getVectorNumElements();
5093 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5094 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5097 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5100 // Gather data to see if the operation can be modelled as a
5101 // shuffle in combination with VEXTs.
5102 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5103 SelectionDAG &DAG) const {
5104 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5106 EVT VT = Op.getValueType();
5107 unsigned NumElts = VT.getVectorNumElements();
5109 struct ShuffleSourceInfo {
5114 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5115 // be compatible with the shuffle we intend to construct. As a result
5116 // ShuffleVec will be some sliding window into the original Vec.
5119 // Code should guarantee that element i in Vec starts at element "WindowBase
5120 // + i * WindowScale in ShuffleVec".
5124 ShuffleSourceInfo(SDValue Vec)
5125 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5126 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5128 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5131 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5133 SmallVector<ShuffleSourceInfo, 2> Sources;
5134 for (unsigned i = 0; i < NumElts; ++i) {
5135 SDValue V = Op.getOperand(i);
5138 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5139 !isa<ConstantSDNode>(V.getOperand(1))) {
5140 // A shuffle can only come from building a vector from various
5141 // elements of other vectors, provided their indices are constant.
5145 // Add this element source to the list if it's not already there.
5146 SDValue SourceVec = V.getOperand(0);
5147 auto Source = find(Sources, SourceVec);
5148 if (Source == Sources.end())
5149 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5151 // Update the minimum and maximum lane number seen.
5152 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5153 Source->MinElt = std::min(Source->MinElt, EltNo);
5154 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5157 // Currently only do something sane when at most two source vectors
5159 if (Sources.size() > 2)
5162 // Find out the smallest element size among result and two sources, and use
5163 // it as element size to build the shuffle_vector.
5164 EVT SmallestEltTy = VT.getVectorElementType();
5165 for (auto &Source : Sources) {
5166 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5167 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5168 SmallestEltTy = SrcEltTy;
5171 unsigned ResMultiplier =
5172 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5173 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5174 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5176 // If the source vector is too wide or too narrow, we may nevertheless be able
5177 // to construct a compatible shuffle either by concatenating it with UNDEF or
5178 // extracting a suitable range of elements.
5179 for (auto &Src : Sources) {
5180 EVT SrcVT = Src.ShuffleVec.getValueType();
5182 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5185 // This stage of the search produces a source with the same element type as
5186 // the original, but with a total width matching the BUILD_VECTOR output.
5187 EVT EltVT = SrcVT.getVectorElementType();
5188 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5189 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5191 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5192 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5193 // We can pad out the smaller vector for free, so if it's part of a
5196 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5197 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5201 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5203 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5204 // Span too large for a VEXT to cope
5208 if (Src.MinElt >= NumSrcElts) {
5209 // The extraction can just take the second half
5211 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5212 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5213 Src.WindowBase = -NumSrcElts;
5214 } else if (Src.MaxElt < NumSrcElts) {
5215 // The extraction can just take the first half
5217 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5218 DAG.getConstant(0, dl, MVT::i64));
5220 // An actual VEXT is needed
5222 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5223 DAG.getConstant(0, dl, MVT::i64));
5225 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5226 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5227 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5229 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5231 DAG.getConstant(Imm, dl, MVT::i32));
5232 Src.WindowBase = -Src.MinElt;
5236 // Another possible incompatibility occurs from the vector element types. We
5237 // can fix this by bitcasting the source vectors to the same type we intend
5239 for (auto &Src : Sources) {
5240 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5241 if (SrcEltTy == SmallestEltTy)
5243 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5244 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5245 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5246 Src.WindowBase *= Src.WindowScale;
5249 // Final sanity check before we try to actually produce a shuffle.
5251 for (auto Src : Sources)
5252 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5255 // The stars all align, our next step is to produce the mask for the shuffle.
5256 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5257 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5258 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5259 SDValue Entry = Op.getOperand(i);
5260 if (Entry.isUndef())
5263 auto Src = find(Sources, Entry.getOperand(0));
5264 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5266 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5267 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5269 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5271 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5272 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5274 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5275 // starting at the appropriate offset.
5276 int *LaneMask = &Mask[i * ResMultiplier];
5278 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5279 ExtractBase += NumElts * (Src - Sources.begin());
5280 for (int j = 0; j < LanesDefined; ++j)
5281 LaneMask[j] = ExtractBase + j;
5284 // Final check before we try to produce nonsense...
5285 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5288 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5289 for (unsigned i = 0; i < Sources.size(); ++i)
5290 ShuffleOps[i] = Sources[i].ShuffleVec;
5292 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5293 ShuffleOps[1], Mask);
5294 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5297 // check if an EXT instruction can handle the shuffle mask when the
5298 // vector sources of the shuffle are the same.
5299 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5300 unsigned NumElts = VT.getVectorNumElements();
5302 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5308 // If this is a VEXT shuffle, the immediate value is the index of the first
5309 // element. The other shuffle indices must be the successive elements after
5311 unsigned ExpectedElt = Imm;
5312 for (unsigned i = 1; i < NumElts; ++i) {
5313 // Increment the expected index. If it wraps around, just follow it
5314 // back to index zero and keep going.
5316 if (ExpectedElt == NumElts)
5320 continue; // ignore UNDEF indices
5321 if (ExpectedElt != static_cast<unsigned>(M[i]))
5328 // check if an EXT instruction can handle the shuffle mask when the
5329 // vector sources of the shuffle are different.
5330 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5332 // Look for the first non-undef element.
5333 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5335 // Benefit form APInt to handle overflow when calculating expected element.
5336 unsigned NumElts = VT.getVectorNumElements();
5337 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5338 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5339 // The following shuffle indices must be the successive elements after the
5340 // first real element.
5341 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5342 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5343 if (FirstWrongElt != M.end())
5346 // The index of an EXT is the first element if it is not UNDEF.
5347 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5348 // value of the first element. E.g.
5349 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5350 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5351 // ExpectedElt is the last mask index plus 1.
5352 Imm = ExpectedElt.getZExtValue();
5354 // There are two difference cases requiring to reverse input vectors.
5355 // For example, for vector <4 x i32> we have the following cases,
5356 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5357 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5358 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5359 // to reverse two input vectors.
5368 /// isREVMask - Check if a vector shuffle corresponds to a REV
5369 /// instruction with the specified blocksize. (The order of the elements
5370 /// within each block of the vector is reversed.)
5371 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5372 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5373 "Only possible block sizes for REV are: 16, 32, 64");
5375 unsigned EltSz = VT.getScalarSizeInBits();
5379 unsigned NumElts = VT.getVectorNumElements();
5380 unsigned BlockElts = M[0] + 1;
5381 // If the first shuffle index is UNDEF, be optimistic.
5383 BlockElts = BlockSize / EltSz;
5385 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5388 for (unsigned i = 0; i < NumElts; ++i) {
5390 continue; // ignore UNDEF indices
5391 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5398 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5399 unsigned NumElts = VT.getVectorNumElements();
5400 WhichResult = (M[0] == 0 ? 0 : 1);
5401 unsigned Idx = WhichResult * NumElts / 2;
5402 for (unsigned i = 0; i != NumElts; i += 2) {
5403 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5404 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5412 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5413 unsigned NumElts = VT.getVectorNumElements();
5414 WhichResult = (M[0] == 0 ? 0 : 1);
5415 for (unsigned i = 0; i != NumElts; ++i) {
5417 continue; // ignore UNDEF indices
5418 if ((unsigned)M[i] != 2 * i + WhichResult)
5425 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5426 unsigned NumElts = VT.getVectorNumElements();
5427 WhichResult = (M[0] == 0 ? 0 : 1);
5428 for (unsigned i = 0; i < NumElts; i += 2) {
5429 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5430 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5436 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5437 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5438 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5439 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5440 unsigned NumElts = VT.getVectorNumElements();
5441 WhichResult = (M[0] == 0 ? 0 : 1);
5442 unsigned Idx = WhichResult * NumElts / 2;
5443 for (unsigned i = 0; i != NumElts; i += 2) {
5444 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5445 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5453 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5454 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5455 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5456 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5457 unsigned Half = VT.getVectorNumElements() / 2;
5458 WhichResult = (M[0] == 0 ? 0 : 1);
5459 for (unsigned j = 0; j != 2; ++j) {
5460 unsigned Idx = WhichResult;
5461 for (unsigned i = 0; i != Half; ++i) {
5462 int MIdx = M[i + j * Half];
5463 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5472 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5473 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5474 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5475 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5476 unsigned NumElts = VT.getVectorNumElements();
5477 WhichResult = (M[0] == 0 ? 0 : 1);
5478 for (unsigned i = 0; i < NumElts; i += 2) {
5479 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5480 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5486 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5487 bool &DstIsLeft, int &Anomaly) {
5488 if (M.size() != static_cast<size_t>(NumInputElements))
5491 int NumLHSMatch = 0, NumRHSMatch = 0;
5492 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5494 for (int i = 0; i < NumInputElements; ++i) {
5504 LastLHSMismatch = i;
5506 if (M[i] == i + NumInputElements)
5509 LastRHSMismatch = i;
5512 if (NumLHSMatch == NumInputElements - 1) {
5514 Anomaly = LastLHSMismatch;
5516 } else if (NumRHSMatch == NumInputElements - 1) {
5518 Anomaly = LastRHSMismatch;
5525 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5526 if (VT.getSizeInBits() != 128)
5529 unsigned NumElts = VT.getVectorNumElements();
5531 for (int I = 0, E = NumElts / 2; I != E; I++) {
5536 int Offset = NumElts / 2;
5537 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5538 if (Mask[I] != I + SplitLHS * Offset)
5545 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5547 EVT VT = Op.getValueType();
5548 SDValue V0 = Op.getOperand(0);
5549 SDValue V1 = Op.getOperand(1);
5550 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5552 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5553 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5556 bool SplitV0 = V0.getValueSizeInBits() == 128;
5558 if (!isConcatMask(Mask, VT, SplitV0))
5561 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5562 VT.getVectorNumElements() / 2);
5564 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5565 DAG.getConstant(0, DL, MVT::i64));
5567 if (V1.getValueSizeInBits() == 128) {
5568 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5569 DAG.getConstant(0, DL, MVT::i64));
5571 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5574 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5575 /// the specified operations to build the shuffle.
5576 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5577 SDValue RHS, SelectionDAG &DAG,
5579 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5580 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5581 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5584 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5593 OP_VUZPL, // VUZP, left result
5594 OP_VUZPR, // VUZP, right result
5595 OP_VZIPL, // VZIP, left result
5596 OP_VZIPR, // VZIP, right result
5597 OP_VTRNL, // VTRN, left result
5598 OP_VTRNR // VTRN, right result
5601 if (OpNum == OP_COPY) {
5602 if (LHSID == (1 * 9 + 2) * 9 + 3)
5604 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5608 SDValue OpLHS, OpRHS;
5609 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5610 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5611 EVT VT = OpLHS.getValueType();
5615 llvm_unreachable("Unknown shuffle opcode!");
5617 // VREV divides the vector in half and swaps within the half.
5618 if (VT.getVectorElementType() == MVT::i32 ||
5619 VT.getVectorElementType() == MVT::f32)
5620 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5621 // vrev <4 x i16> -> REV32
5622 if (VT.getVectorElementType() == MVT::i16 ||
5623 VT.getVectorElementType() == MVT::f16)
5624 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5625 // vrev <4 x i8> -> REV16
5626 assert(VT.getVectorElementType() == MVT::i8);
5627 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5632 EVT EltTy = VT.getVectorElementType();
5634 if (EltTy == MVT::i8)
5635 Opcode = AArch64ISD::DUPLANE8;
5636 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5637 Opcode = AArch64ISD::DUPLANE16;
5638 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5639 Opcode = AArch64ISD::DUPLANE32;
5640 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5641 Opcode = AArch64ISD::DUPLANE64;
5643 llvm_unreachable("Invalid vector element type?");
5645 if (VT.getSizeInBits() == 64)
5646 OpLHS = WidenVector(OpLHS, DAG);
5647 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5648 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5653 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5654 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5655 DAG.getConstant(Imm, dl, MVT::i32));
5658 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5661 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5664 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5667 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5670 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5673 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5678 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5679 SelectionDAG &DAG) {
5680 // Check to see if we can use the TBL instruction.
5681 SDValue V1 = Op.getOperand(0);
5682 SDValue V2 = Op.getOperand(1);
5685 EVT EltVT = Op.getValueType().getVectorElementType();
5686 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5688 SmallVector<SDValue, 8> TBLMask;
5689 for (int Val : ShuffleMask) {
5690 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5691 unsigned Offset = Byte + Val * BytesPerElt;
5692 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5696 MVT IndexVT = MVT::v8i8;
5697 unsigned IndexLen = 8;
5698 if (Op.getValueSizeInBits() == 128) {
5699 IndexVT = MVT::v16i8;
5703 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5704 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5707 if (V2.getNode()->isUndef()) {
5709 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5710 Shuffle = DAG.getNode(
5711 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5712 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5713 DAG.getBuildVector(IndexVT, DL,
5714 makeArrayRef(TBLMask.data(), IndexLen)));
5716 if (IndexLen == 8) {
5717 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5718 Shuffle = DAG.getNode(
5719 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5720 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5721 DAG.getBuildVector(IndexVT, DL,
5722 makeArrayRef(TBLMask.data(), IndexLen)));
5724 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5725 // cannot currently represent the register constraints on the input
5727 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5728 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5730 Shuffle = DAG.getNode(
5731 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5732 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5733 V2Cst, DAG.getBuildVector(IndexVT, DL,
5734 makeArrayRef(TBLMask.data(), IndexLen)));
5737 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5740 static unsigned getDUPLANEOp(EVT EltType) {
5741 if (EltType == MVT::i8)
5742 return AArch64ISD::DUPLANE8;
5743 if (EltType == MVT::i16 || EltType == MVT::f16)
5744 return AArch64ISD::DUPLANE16;
5745 if (EltType == MVT::i32 || EltType == MVT::f32)
5746 return AArch64ISD::DUPLANE32;
5747 if (EltType == MVT::i64 || EltType == MVT::f64)
5748 return AArch64ISD::DUPLANE64;
5750 llvm_unreachable("Invalid vector element type?");
5753 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5754 SelectionDAG &DAG) const {
5756 EVT VT = Op.getValueType();
5758 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5760 // Convert shuffles that are directly supported on NEON to target-specific
5761 // DAG nodes, instead of keeping them as shuffles and matching them again
5762 // during code selection. This is more efficient and avoids the possibility
5763 // of inconsistencies between legalization and selection.
5764 ArrayRef<int> ShuffleMask = SVN->getMask();
5766 SDValue V1 = Op.getOperand(0);
5767 SDValue V2 = Op.getOperand(1);
5769 if (SVN->isSplat()) {
5770 int Lane = SVN->getSplatIndex();
5771 // If this is undef splat, generate it via "just" vdup, if possible.
5775 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5776 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5778 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5779 // constant. If so, we can just reference the lane's definition directly.
5780 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5781 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5782 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5784 // Otherwise, duplicate from the lane of the input vector.
5785 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5787 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5788 // to make a vector of the same size as this SHUFFLE. We can ignore the
5789 // extract entirely, and canonicalise the concat using WidenVector.
5790 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5791 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5792 V1 = V1.getOperand(0);
5793 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5794 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5795 Lane -= Idx * VT.getVectorNumElements() / 2;
5796 V1 = WidenVector(V1.getOperand(Idx), DAG);
5797 } else if (VT.getSizeInBits() == 64)
5798 V1 = WidenVector(V1, DAG);
5800 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5803 if (isREVMask(ShuffleMask, VT, 64))
5804 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5805 if (isREVMask(ShuffleMask, VT, 32))
5806 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5807 if (isREVMask(ShuffleMask, VT, 16))
5808 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5810 bool ReverseEXT = false;
5812 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5815 Imm *= getExtFactor(V1);
5816 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5817 DAG.getConstant(Imm, dl, MVT::i32));
5818 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5819 Imm *= getExtFactor(V1);
5820 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5821 DAG.getConstant(Imm, dl, MVT::i32));
5824 unsigned WhichResult;
5825 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5826 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5827 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5829 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5830 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5831 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5833 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5834 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5835 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5838 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5839 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5840 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5842 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5843 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5844 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5846 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5847 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5848 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5851 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5856 int NumInputElements = V1.getValueType().getVectorNumElements();
5857 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5858 SDValue DstVec = DstIsLeft ? V1 : V2;
5859 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5861 SDValue SrcVec = V1;
5862 int SrcLane = ShuffleMask[Anomaly];
5863 if (SrcLane >= NumInputElements) {
5865 SrcLane -= VT.getVectorNumElements();
5867 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5869 EVT ScalarVT = VT.getVectorElementType();
5871 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5872 ScalarVT = MVT::i32;
5875 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5876 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5880 // If the shuffle is not directly supported and it has 4 elements, use
5881 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5882 unsigned NumElts = VT.getVectorNumElements();
5884 unsigned PFIndexes[4];
5885 for (unsigned i = 0; i != 4; ++i) {
5886 if (ShuffleMask[i] < 0)
5889 PFIndexes[i] = ShuffleMask[i];
5892 // Compute the index in the perfect shuffle table.
5893 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5894 PFIndexes[2] * 9 + PFIndexes[3];
5895 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5896 unsigned Cost = (PFEntry >> 30);
5899 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5902 return GenerateTBL(Op, ShuffleMask, DAG);
5905 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5907 EVT VT = BVN->getValueType(0);
5908 APInt SplatBits, SplatUndef;
5909 unsigned SplatBitSize;
5911 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5912 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5914 for (unsigned i = 0; i < NumSplats; ++i) {
5915 CnstBits <<= SplatBitSize;
5916 UndefBits <<= SplatBitSize;
5917 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5918 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5927 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5928 SelectionDAG &DAG) const {
5929 BuildVectorSDNode *BVN =
5930 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5931 SDValue LHS = Op.getOperand(0);
5933 EVT VT = Op.getValueType();
5938 APInt CnstBits(VT.getSizeInBits(), 0);
5939 APInt UndefBits(VT.getSizeInBits(), 0);
5940 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5941 // We only have BIC vector immediate instruction, which is and-not.
5942 CnstBits = ~CnstBits;
5944 // We make use of a little bit of goto ickiness in order to avoid having to
5945 // duplicate the immediate matching logic for the undef toggled case.
5946 bool SecondTry = false;
5949 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5950 CnstBits = CnstBits.zextOrTrunc(64);
5951 uint64_t CnstVal = CnstBits.getZExtValue();
5953 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5954 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5955 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5956 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5957 DAG.getConstant(CnstVal, dl, MVT::i32),
5958 DAG.getConstant(0, dl, MVT::i32));
5959 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5962 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5963 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5964 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5965 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5966 DAG.getConstant(CnstVal, dl, MVT::i32),
5967 DAG.getConstant(8, dl, MVT::i32));
5968 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5971 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5972 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5973 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5974 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5975 DAG.getConstant(CnstVal, dl, MVT::i32),
5976 DAG.getConstant(16, dl, MVT::i32));
5977 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5980 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5981 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5982 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5983 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5984 DAG.getConstant(CnstVal, dl, MVT::i32),
5985 DAG.getConstant(24, dl, MVT::i32));
5986 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5989 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5990 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5991 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5992 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5993 DAG.getConstant(CnstVal, dl, MVT::i32),
5994 DAG.getConstant(0, dl, MVT::i32));
5995 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5998 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5999 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6000 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6001 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6002 DAG.getConstant(CnstVal, dl, MVT::i32),
6003 DAG.getConstant(8, dl, MVT::i32));
6004 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6011 CnstBits = ~UndefBits;
6015 // We can always fall back to a non-immediate AND.
6020 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6021 // consists of only the same constant int value, returned in reference arg
6023 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6024 uint64_t &ConstVal) {
6025 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6028 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6031 EVT VT = Bvec->getValueType(0);
6032 unsigned NumElts = VT.getVectorNumElements();
6033 for (unsigned i = 1; i < NumElts; ++i)
6034 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6036 ConstVal = FirstElt->getZExtValue();
6040 static unsigned getIntrinsicID(const SDNode *N) {
6041 unsigned Opcode = N->getOpcode();
6044 return Intrinsic::not_intrinsic;
6045 case ISD::INTRINSIC_WO_CHAIN: {
6046 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6047 if (IID < Intrinsic::num_intrinsics)
6049 return Intrinsic::not_intrinsic;
6054 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6055 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6056 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6057 // Also, logical shift right -> sri, with the same structure.
6058 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6059 EVT VT = N->getValueType(0);
6066 // Is the first op an AND?
6067 const SDValue And = N->getOperand(0);
6068 if (And.getOpcode() != ISD::AND)
6071 // Is the second op an shl or lshr?
6072 SDValue Shift = N->getOperand(1);
6073 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6074 // or AArch64ISD::VLSHR vector, #shift
6075 unsigned ShiftOpc = Shift.getOpcode();
6076 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6078 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6080 // Is the shift amount constant?
6081 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6085 // Is the and mask vector all constant?
6087 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6090 // Is C1 == ~C2, taking into account how much one can shift elements of a
6092 uint64_t C2 = C2node->getZExtValue();
6093 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6094 if (C2 > ElemSizeInBits)
6096 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6097 if ((C1 & ElemMask) != (~C2 & ElemMask))
6100 SDValue X = And.getOperand(0);
6101 SDValue Y = Shift.getOperand(0);
6104 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6106 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6107 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6108 Shift.getOperand(1));
6110 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6111 DEBUG(N->dump(&DAG));
6112 DEBUG(dbgs() << "into: \n");
6113 DEBUG(ResultSLI->dump(&DAG));
6119 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6120 SelectionDAG &DAG) const {
6121 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6122 if (EnableAArch64SlrGeneration) {
6123 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6127 BuildVectorSDNode *BVN =
6128 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6129 SDValue LHS = Op.getOperand(1);
6131 EVT VT = Op.getValueType();
6133 // OR commutes, so try swapping the operands.
6135 LHS = Op.getOperand(0);
6136 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6141 APInt CnstBits(VT.getSizeInBits(), 0);
6142 APInt UndefBits(VT.getSizeInBits(), 0);
6143 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6144 // We make use of a little bit of goto ickiness in order to avoid having to
6145 // duplicate the immediate matching logic for the undef toggled case.
6146 bool SecondTry = false;
6149 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6150 CnstBits = CnstBits.zextOrTrunc(64);
6151 uint64_t CnstVal = CnstBits.getZExtValue();
6153 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6154 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6155 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6156 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6157 DAG.getConstant(CnstVal, dl, MVT::i32),
6158 DAG.getConstant(0, dl, MVT::i32));
6159 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6162 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6163 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6164 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6165 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6166 DAG.getConstant(CnstVal, dl, MVT::i32),
6167 DAG.getConstant(8, dl, MVT::i32));
6168 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6171 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6172 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6173 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6174 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6175 DAG.getConstant(CnstVal, dl, MVT::i32),
6176 DAG.getConstant(16, dl, MVT::i32));
6177 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6180 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6181 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6182 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6183 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6184 DAG.getConstant(CnstVal, dl, MVT::i32),
6185 DAG.getConstant(24, dl, MVT::i32));
6186 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6189 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6190 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6191 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6192 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6193 DAG.getConstant(CnstVal, dl, MVT::i32),
6194 DAG.getConstant(0, dl, MVT::i32));
6195 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6198 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6199 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6200 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6201 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6202 DAG.getConstant(CnstVal, dl, MVT::i32),
6203 DAG.getConstant(8, dl, MVT::i32));
6204 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6211 CnstBits = UndefBits;
6215 // We can always fall back to a non-immediate OR.
6220 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6221 // be truncated to fit element width.
6222 static SDValue NormalizeBuildVector(SDValue Op,
6223 SelectionDAG &DAG) {
6224 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6226 EVT VT = Op.getValueType();
6227 EVT EltTy= VT.getVectorElementType();
6229 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6232 SmallVector<SDValue, 16> Ops;
6233 for (SDValue Lane : Op->ops()) {
6234 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6235 APInt LowBits(EltTy.getSizeInBits(),
6236 CstLane->getZExtValue());
6237 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6239 Ops.push_back(Lane);
6241 return DAG.getBuildVector(VT, dl, Ops);
6244 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6245 SelectionDAG &DAG) const {
6247 EVT VT = Op.getValueType();
6248 Op = NormalizeBuildVector(Op, DAG);
6249 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6251 APInt CnstBits(VT.getSizeInBits(), 0);
6252 APInt UndefBits(VT.getSizeInBits(), 0);
6253 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6254 // We make use of a little bit of goto ickiness in order to avoid having to
6255 // duplicate the immediate matching logic for the undef toggled case.
6256 bool SecondTry = false;
6259 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6260 CnstBits = CnstBits.zextOrTrunc(64);
6261 uint64_t CnstVal = CnstBits.getZExtValue();
6263 // Certain magic vector constants (used to express things like NOT
6264 // and NEG) are passed through unmodified. This allows codegen patterns
6265 // for these operations to match. Special-purpose patterns will lower
6266 // these immediates to MOVIs if it proves necessary.
6267 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6270 // The many faces of MOVI...
6271 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6272 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6273 if (VT.getSizeInBits() == 128) {
6274 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6275 DAG.getConstant(CnstVal, dl, MVT::i32));
6276 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6279 // Support the V64 version via subregister insertion.
6280 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6281 DAG.getConstant(CnstVal, dl, MVT::i32));
6282 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6285 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6286 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6287 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6288 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6289 DAG.getConstant(CnstVal, dl, MVT::i32),
6290 DAG.getConstant(0, dl, MVT::i32));
6291 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6294 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6295 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6296 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6297 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6298 DAG.getConstant(CnstVal, dl, MVT::i32),
6299 DAG.getConstant(8, dl, MVT::i32));
6300 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6303 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6304 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6305 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6306 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6307 DAG.getConstant(CnstVal, dl, MVT::i32),
6308 DAG.getConstant(16, dl, MVT::i32));
6309 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6312 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6313 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6314 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6315 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6316 DAG.getConstant(CnstVal, dl, MVT::i32),
6317 DAG.getConstant(24, dl, MVT::i32));
6318 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6321 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6322 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6323 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6324 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6325 DAG.getConstant(CnstVal, dl, MVT::i32),
6326 DAG.getConstant(0, dl, MVT::i32));
6327 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6330 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6331 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6332 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6333 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6334 DAG.getConstant(CnstVal, dl, MVT::i32),
6335 DAG.getConstant(8, dl, MVT::i32));
6336 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6339 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6340 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6341 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6342 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6343 DAG.getConstant(CnstVal, dl, MVT::i32),
6344 DAG.getConstant(264, dl, MVT::i32));
6345 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6348 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6349 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6350 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6351 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6352 DAG.getConstant(CnstVal, dl, MVT::i32),
6353 DAG.getConstant(272, dl, MVT::i32));
6354 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6357 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6358 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6359 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6360 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6361 DAG.getConstant(CnstVal, dl, MVT::i32));
6362 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6365 // The few faces of FMOV...
6366 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6367 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6368 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6369 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6370 DAG.getConstant(CnstVal, dl, MVT::i32));
6371 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6374 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6375 VT.getSizeInBits() == 128) {
6376 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6377 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6378 DAG.getConstant(CnstVal, dl, MVT::i32));
6379 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6382 // The many faces of MVNI...
6384 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6385 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6386 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6387 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6388 DAG.getConstant(CnstVal, dl, MVT::i32),
6389 DAG.getConstant(0, dl, MVT::i32));
6390 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6393 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6394 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6395 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6396 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6397 DAG.getConstant(CnstVal, dl, MVT::i32),
6398 DAG.getConstant(8, dl, MVT::i32));
6399 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6402 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6403 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6404 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6405 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6406 DAG.getConstant(CnstVal, dl, MVT::i32),
6407 DAG.getConstant(16, dl, MVT::i32));
6408 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6411 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6412 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6413 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6414 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6415 DAG.getConstant(CnstVal, dl, MVT::i32),
6416 DAG.getConstant(24, dl, MVT::i32));
6417 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6420 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6421 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6422 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6423 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6424 DAG.getConstant(CnstVal, dl, MVT::i32),
6425 DAG.getConstant(0, dl, MVT::i32));
6426 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6429 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6430 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6431 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6432 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6433 DAG.getConstant(CnstVal, dl, MVT::i32),
6434 DAG.getConstant(8, dl, MVT::i32));
6435 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6438 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6439 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6440 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6441 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6442 DAG.getConstant(CnstVal, dl, MVT::i32),
6443 DAG.getConstant(264, dl, MVT::i32));
6444 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6447 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6448 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6449 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6450 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6451 DAG.getConstant(CnstVal, dl, MVT::i32),
6452 DAG.getConstant(272, dl, MVT::i32));
6453 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6460 CnstBits = UndefBits;
6465 // Scan through the operands to find some interesting properties we can
6467 // 1) If only one value is used, we can use a DUP, or
6468 // 2) if only the low element is not undef, we can just insert that, or
6469 // 3) if only one constant value is used (w/ some non-constant lanes),
6470 // we can splat the constant value into the whole vector then fill
6471 // in the non-constant lanes.
6472 // 4) FIXME: If different constant values are used, but we can intelligently
6473 // select the values we'll be overwriting for the non-constant
6474 // lanes such that we can directly materialize the vector
6475 // some other way (MOVI, e.g.), we can be sneaky.
6476 unsigned NumElts = VT.getVectorNumElements();
6477 bool isOnlyLowElement = true;
6478 bool usesOnlyOneValue = true;
6479 bool usesOnlyOneConstantValue = true;
6480 bool isConstant = true;
6481 unsigned NumConstantLanes = 0;
6483 SDValue ConstantValue;
6484 for (unsigned i = 0; i < NumElts; ++i) {
6485 SDValue V = Op.getOperand(i);
6489 isOnlyLowElement = false;
6490 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6493 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6495 if (!ConstantValue.getNode())
6497 else if (ConstantValue != V)
6498 usesOnlyOneConstantValue = false;
6501 if (!Value.getNode())
6503 else if (V != Value)
6504 usesOnlyOneValue = false;
6507 if (!Value.getNode())
6508 return DAG.getUNDEF(VT);
6510 if (isOnlyLowElement)
6511 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6513 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6514 // i32 and try again.
6515 if (usesOnlyOneValue) {
6517 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6518 Value.getValueType() != VT)
6519 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6521 // This is actually a DUPLANExx operation, which keeps everything vectory.
6523 // DUPLANE works on 128-bit vectors, widen it if necessary.
6524 SDValue Lane = Value.getOperand(1);
6525 Value = Value.getOperand(0);
6526 if (Value.getValueSizeInBits() == 64)
6527 Value = WidenVector(Value, DAG);
6529 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6530 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6533 if (VT.getVectorElementType().isFloatingPoint()) {
6534 SmallVector<SDValue, 8> Ops;
6535 EVT EltTy = VT.getVectorElementType();
6536 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6537 "Unsupported floating-point vector type");
6538 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6539 for (unsigned i = 0; i < NumElts; ++i)
6540 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6541 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6542 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6543 Val = LowerBUILD_VECTOR(Val, DAG);
6545 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6549 // If there was only one constant value used and for more than one lane,
6550 // start by splatting that value, then replace the non-constant lanes. This
6551 // is better than the default, which will perform a separate initialization
6553 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6554 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6555 // Now insert the non-constant lanes.
6556 for (unsigned i = 0; i < NumElts; ++i) {
6557 SDValue V = Op.getOperand(i);
6558 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6559 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6560 // Note that type legalization likely mucked about with the VT of the
6561 // source operand, so we may have to convert it here before inserting.
6562 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6568 // If all elements are constants and the case above didn't get hit, fall back
6569 // to the default expansion, which will generate a load from the constant
6574 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6576 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6580 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6581 // know the default expansion would otherwise fall back on something even
6582 // worse. For a vector with one or two non-undef values, that's
6583 // scalar_to_vector for the elements followed by a shuffle (provided the
6584 // shuffle is valid for the target) and materialization element by element
6585 // on the stack followed by a load for everything else.
6586 if (!isConstant && !usesOnlyOneValue) {
6587 SDValue Vec = DAG.getUNDEF(VT);
6588 SDValue Op0 = Op.getOperand(0);
6591 // Use SCALAR_TO_VECTOR for lane zero to
6592 // a) Avoid a RMW dependency on the full vector register, and
6593 // b) Allow the register coalescer to fold away the copy if the
6594 // value is already in an S or D register, and we're forced to emit an
6595 // INSERT_SUBREG that we can't fold anywhere.
6597 // We also allow types like i8 and i16 which are illegal scalar but legal
6598 // vector element types. After type-legalization the inserted value is
6599 // extended (i32) and it is safe to cast them to the vector type by ignoring
6600 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6601 if (!Op0.isUndef()) {
6602 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
6605 for (; i < NumElts; ++i) {
6606 SDValue V = Op.getOperand(i);
6609 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6610 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6615 // Just use the default expansion. We failed to find a better alternative.
6619 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6620 SelectionDAG &DAG) const {
6621 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6623 // Check for non-constant or out of range lane.
6624 EVT VT = Op.getOperand(0).getValueType();
6625 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6626 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6630 // Insertion/extraction are legal for V128 types.
6631 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6632 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6636 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6637 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6640 // For V64 types, we perform insertion by expanding the value
6641 // to a V128 type and perform the insertion on that.
6643 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6644 EVT WideTy = WideVec.getValueType();
6646 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6647 Op.getOperand(1), Op.getOperand(2));
6648 // Re-narrow the resultant vector.
6649 return NarrowVector(Node, DAG);
6653 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6654 SelectionDAG &DAG) const {
6655 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6657 // Check for non-constant or out of range lane.
6658 EVT VT = Op.getOperand(0).getValueType();
6659 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6660 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6664 // Insertion/extraction are legal for V128 types.
6665 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6666 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6670 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6671 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6674 // For V64 types, we perform extraction by expanding the value
6675 // to a V128 type and perform the extraction on that.
6677 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6678 EVT WideTy = WideVec.getValueType();
6680 EVT ExtrTy = WideTy.getVectorElementType();
6681 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6684 // For extractions, we just return the result directly.
6685 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6689 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6690 SelectionDAG &DAG) const {
6691 EVT VT = Op.getOperand(0).getValueType();
6697 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6700 unsigned Val = Cst->getZExtValue();
6702 unsigned Size = Op.getValueSizeInBits();
6704 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6708 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6710 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6716 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6718 if (VT.getVectorNumElements() == 4 &&
6719 (VT.is128BitVector() || VT.is64BitVector())) {
6720 unsigned PFIndexes[4];
6721 for (unsigned i = 0; i != 4; ++i) {
6725 PFIndexes[i] = M[i];
6728 // Compute the index in the perfect shuffle table.
6729 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6730 PFIndexes[2] * 9 + PFIndexes[3];
6731 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6732 unsigned Cost = (PFEntry >> 30);
6740 unsigned DummyUnsigned;
6742 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6743 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6744 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6745 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6746 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6747 isZIPMask(M, VT, DummyUnsigned) ||
6748 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6749 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6750 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6751 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6752 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6755 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6756 /// operand of a vector shift operation, where all the elements of the
6757 /// build_vector must have the same constant integer value.
6758 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6759 // Ignore bit_converts.
6760 while (Op.getOpcode() == ISD::BITCAST)
6761 Op = Op.getOperand(0);
6762 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6763 APInt SplatBits, SplatUndef;
6764 unsigned SplatBitSize;
6766 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6767 HasAnyUndefs, ElementBits) ||
6768 SplatBitSize > ElementBits)
6770 Cnt = SplatBits.getSExtValue();
6774 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6775 /// operand of a vector shift left operation. That value must be in the range:
6776 /// 0 <= Value < ElementBits for a left shift; or
6777 /// 0 <= Value <= ElementBits for a long left shift.
6778 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6779 assert(VT.isVector() && "vector shift count is not a vector type");
6780 int64_t ElementBits = VT.getScalarSizeInBits();
6781 if (!getVShiftImm(Op, ElementBits, Cnt))
6783 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6786 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6787 /// operand of a vector shift right operation. The value must be in the range:
6788 /// 1 <= Value <= ElementBits for a right shift; or
6789 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6790 assert(VT.isVector() && "vector shift count is not a vector type");
6791 int64_t ElementBits = VT.getScalarSizeInBits();
6792 if (!getVShiftImm(Op, ElementBits, Cnt))
6794 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6797 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6798 SelectionDAG &DAG) const {
6799 EVT VT = Op.getValueType();
6803 if (!Op.getOperand(1).getValueType().isVector())
6805 unsigned EltSize = VT.getScalarSizeInBits();
6807 switch (Op.getOpcode()) {
6809 llvm_unreachable("unexpected shift opcode");
6812 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6813 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6814 DAG.getConstant(Cnt, DL, MVT::i32));
6815 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6816 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6818 Op.getOperand(0), Op.getOperand(1));
6821 // Right shift immediate
6822 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6824 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6825 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6826 DAG.getConstant(Cnt, DL, MVT::i32));
6829 // Right shift register. Note, there is not a shift right register
6830 // instruction, but the shift left register instruction takes a signed
6831 // value, where negative numbers specify a right shift.
6832 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6833 : Intrinsic::aarch64_neon_ushl;
6834 // negate the shift amount
6835 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6836 SDValue NegShiftLeft =
6837 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6838 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6840 return NegShiftLeft;
6846 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6847 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6848 const SDLoc &dl, SelectionDAG &DAG) {
6849 EVT SrcVT = LHS.getValueType();
6850 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6851 "function only supposed to emit natural comparisons");
6853 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6854 APInt CnstBits(VT.getSizeInBits(), 0);
6855 APInt UndefBits(VT.getSizeInBits(), 0);
6856 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6857 bool IsZero = IsCnst && (CnstBits == 0);
6859 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6863 case AArch64CC::NE: {
6866 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6868 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6869 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6873 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6874 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6877 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6878 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6881 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6882 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6885 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6886 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6890 // If we ignore NaNs then we can use to the MI implementation.
6894 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6895 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6902 case AArch64CC::NE: {
6905 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6907 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6908 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6912 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6913 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6916 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6917 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6920 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6921 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6924 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6925 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6927 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6929 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6932 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6933 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6935 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6937 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6941 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6942 SelectionDAG &DAG) const {
6943 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6944 SDValue LHS = Op.getOperand(0);
6945 SDValue RHS = Op.getOperand(1);
6946 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6949 if (LHS.getValueType().getVectorElementType().isInteger()) {
6950 assert(LHS.getValueType() == RHS.getValueType());
6951 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6953 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6954 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6957 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6960 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6961 LHS.getValueType().getVectorElementType() == MVT::f64);
6963 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6964 // clean. Some of them require two branches to implement.
6965 AArch64CC::CondCode CC1, CC2;
6967 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6969 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6971 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6975 if (CC2 != AArch64CC::AL) {
6977 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6978 if (!Cmp2.getNode())
6981 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6984 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6987 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6992 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6993 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6994 /// specified in the intrinsic calls.
6995 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6997 unsigned Intrinsic) const {
6998 auto &DL = I.getModule()->getDataLayout();
6999 switch (Intrinsic) {
7000 case Intrinsic::aarch64_neon_ld2:
7001 case Intrinsic::aarch64_neon_ld3:
7002 case Intrinsic::aarch64_neon_ld4:
7003 case Intrinsic::aarch64_neon_ld1x2:
7004 case Intrinsic::aarch64_neon_ld1x3:
7005 case Intrinsic::aarch64_neon_ld1x4:
7006 case Intrinsic::aarch64_neon_ld2lane:
7007 case Intrinsic::aarch64_neon_ld3lane:
7008 case Intrinsic::aarch64_neon_ld4lane:
7009 case Intrinsic::aarch64_neon_ld2r:
7010 case Intrinsic::aarch64_neon_ld3r:
7011 case Intrinsic::aarch64_neon_ld4r: {
7012 Info.opc = ISD::INTRINSIC_W_CHAIN;
7013 // Conservatively set memVT to the entire set of vectors loaded.
7014 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7015 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7016 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7019 Info.vol = false; // volatile loads with NEON intrinsics not supported
7020 Info.readMem = true;
7021 Info.writeMem = false;
7024 case Intrinsic::aarch64_neon_st2:
7025 case Intrinsic::aarch64_neon_st3:
7026 case Intrinsic::aarch64_neon_st4:
7027 case Intrinsic::aarch64_neon_st1x2:
7028 case Intrinsic::aarch64_neon_st1x3:
7029 case Intrinsic::aarch64_neon_st1x4:
7030 case Intrinsic::aarch64_neon_st2lane:
7031 case Intrinsic::aarch64_neon_st3lane:
7032 case Intrinsic::aarch64_neon_st4lane: {
7033 Info.opc = ISD::INTRINSIC_VOID;
7034 // Conservatively set memVT to the entire set of vectors stored.
7035 unsigned NumElts = 0;
7036 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7037 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7038 if (!ArgTy->isVectorTy())
7040 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7042 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7043 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7046 Info.vol = false; // volatile stores with NEON intrinsics not supported
7047 Info.readMem = false;
7048 Info.writeMem = true;
7051 case Intrinsic::aarch64_ldaxr:
7052 case Intrinsic::aarch64_ldxr: {
7053 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7054 Info.opc = ISD::INTRINSIC_W_CHAIN;
7055 Info.memVT = MVT::getVT(PtrTy->getElementType());
7056 Info.ptrVal = I.getArgOperand(0);
7058 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7060 Info.readMem = true;
7061 Info.writeMem = false;
7064 case Intrinsic::aarch64_stlxr:
7065 case Intrinsic::aarch64_stxr: {
7066 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7067 Info.opc = ISD::INTRINSIC_W_CHAIN;
7068 Info.memVT = MVT::getVT(PtrTy->getElementType());
7069 Info.ptrVal = I.getArgOperand(1);
7071 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7073 Info.readMem = false;
7074 Info.writeMem = true;
7077 case Intrinsic::aarch64_ldaxp:
7078 case Intrinsic::aarch64_ldxp:
7079 Info.opc = ISD::INTRINSIC_W_CHAIN;
7080 Info.memVT = MVT::i128;
7081 Info.ptrVal = I.getArgOperand(0);
7085 Info.readMem = true;
7086 Info.writeMem = false;
7088 case Intrinsic::aarch64_stlxp:
7089 case Intrinsic::aarch64_stxp:
7090 Info.opc = ISD::INTRINSIC_W_CHAIN;
7091 Info.memVT = MVT::i128;
7092 Info.ptrVal = I.getArgOperand(2);
7096 Info.readMem = false;
7097 Info.writeMem = true;
7106 // Truncations from 64-bit GPR to 32-bit GPR is free.
7107 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7108 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7110 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7111 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7112 return NumBits1 > NumBits2;
7114 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7115 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7117 unsigned NumBits1 = VT1.getSizeInBits();
7118 unsigned NumBits2 = VT2.getSizeInBits();
7119 return NumBits1 > NumBits2;
7122 /// Check if it is profitable to hoist instruction in then/else to if.
7123 /// Not profitable if I and it's user can form a FMA instruction
7124 /// because we prefer FMSUB/FMADD.
7125 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7126 if (I->getOpcode() != Instruction::FMul)
7129 if (!I->hasOneUse())
7132 Instruction *User = I->user_back();
7135 !(User->getOpcode() == Instruction::FSub ||
7136 User->getOpcode() == Instruction::FAdd))
7139 const TargetOptions &Options = getTargetMachine().Options;
7140 const DataLayout &DL = I->getModule()->getDataLayout();
7141 EVT VT = getValueType(DL, User->getOperand(0)->getType());
7143 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7144 isOperationLegalOrCustom(ISD::FMA, VT) &&
7145 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7146 Options.UnsafeFPMath));
7149 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7151 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7152 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7154 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7155 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7156 return NumBits1 == 32 && NumBits2 == 64;
7158 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7159 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7161 unsigned NumBits1 = VT1.getSizeInBits();
7162 unsigned NumBits2 = VT2.getSizeInBits();
7163 return NumBits1 == 32 && NumBits2 == 64;
7166 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7167 EVT VT1 = Val.getValueType();
7168 if (isZExtFree(VT1, VT2)) {
7172 if (Val.getOpcode() != ISD::LOAD)
7175 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7176 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7177 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7178 VT1.getSizeInBits() <= 32);
7181 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7182 if (isa<FPExtInst>(Ext))
7185 // Vector types are next free.
7186 if (Ext->getType()->isVectorTy())
7189 for (const Use &U : Ext->uses()) {
7190 // The extension is free if we can fold it with a left shift in an
7191 // addressing mode or an arithmetic operation: add, sub, and cmp.
7193 // Is there a shift?
7194 const Instruction *Instr = cast<Instruction>(U.getUser());
7196 // Is this a constant shift?
7197 switch (Instr->getOpcode()) {
7198 case Instruction::Shl:
7199 if (!isa<ConstantInt>(Instr->getOperand(1)))
7202 case Instruction::GetElementPtr: {
7203 gep_type_iterator GTI = gep_type_begin(Instr);
7204 auto &DL = Ext->getModule()->getDataLayout();
7205 std::advance(GTI, U.getOperandNo()-1);
7206 Type *IdxTy = GTI.getIndexedType();
7207 // This extension will end up with a shift because of the scaling factor.
7208 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7209 // Get the shift amount based on the scaling factor:
7210 // log2(sizeof(IdxTy)) - log2(8).
7212 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7213 // Is the constant foldable in the shift of the addressing mode?
7214 // I.e., shift amount is between 1 and 4 inclusive.
7215 if (ShiftAmt == 0 || ShiftAmt > 4)
7219 case Instruction::Trunc:
7220 // Check if this is a noop.
7221 // trunc(sext ty1 to ty2) to ty1.
7222 if (Instr->getType() == Ext->getOperand(0)->getType())
7229 // At this point we can use the bfm family, so this extension is free
7235 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7236 unsigned &RequiredAligment) const {
7237 if (!LoadedType.isSimple() ||
7238 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7240 // Cyclone supports unaligned accesses.
7241 RequiredAligment = 0;
7242 unsigned NumBits = LoadedType.getSizeInBits();
7243 return NumBits == 32 || NumBits == 64;
7246 /// A helper function for determining the number of interleaved accesses we
7247 /// will generate when lowering accesses of the given type.
7249 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7250 const DataLayout &DL) const {
7251 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7254 bool AArch64TargetLowering::isLegalInterleavedAccessType(
7255 VectorType *VecTy, const DataLayout &DL) const {
7257 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7258 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7260 // Ensure the number of vector elements is greater than 1.
7261 if (VecTy->getNumElements() < 2)
7264 // Ensure the element type is legal.
7265 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7268 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7269 // 128 will be split into multiple interleaved accesses.
7270 return VecSize == 64 || VecSize % 128 == 0;
7273 /// \brief Lower an interleaved load into a ldN intrinsic.
7275 /// E.g. Lower an interleaved load (Factor = 2):
7276 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7277 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7278 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7281 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7282 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7283 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7284 bool AArch64TargetLowering::lowerInterleavedLoad(
7285 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7286 ArrayRef<unsigned> Indices, unsigned Factor) const {
7287 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7288 "Invalid interleave factor");
7289 assert(!Shuffles.empty() && "Empty shufflevector input");
7290 assert(Shuffles.size() == Indices.size() &&
7291 "Unmatched number of shufflevectors and indices");
7293 const DataLayout &DL = LI->getModule()->getDataLayout();
7295 VectorType *VecTy = Shuffles[0]->getType();
7297 // Skip if we do not have NEON and skip illegal vector types. We can
7298 // "legalize" wide vector types into multiple interleaved accesses as long as
7299 // the vector types are divisible by 128.
7300 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
7303 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7305 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7306 // load integer vectors first and then convert to pointer vectors.
7307 Type *EltTy = VecTy->getVectorElementType();
7308 if (EltTy->isPointerTy())
7310 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7312 IRBuilder<> Builder(LI);
7314 // The base address of the load.
7315 Value *BaseAddr = LI->getPointerOperand();
7318 // If we're going to generate more than one load, reset the sub-vector type
7319 // to something legal.
7320 VecTy = VectorType::get(VecTy->getVectorElementType(),
7321 VecTy->getVectorNumElements() / NumLoads);
7323 // We will compute the pointer operand of each load from the original base
7324 // address using GEPs. Cast the base address to a pointer to the scalar
7326 BaseAddr = Builder.CreateBitCast(
7327 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7328 LI->getPointerAddressSpace()));
7331 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7332 Type *Tys[2] = {VecTy, PtrTy};
7333 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7334 Intrinsic::aarch64_neon_ld3,
7335 Intrinsic::aarch64_neon_ld4};
7337 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7339 // Holds sub-vectors extracted from the load intrinsic return values. The
7340 // sub-vectors are associated with the shufflevector instructions they will
7342 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
7344 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
7346 // If we're generating more than one load, compute the base address of
7347 // subsequent loads as an offset from the previous.
7349 BaseAddr = Builder.CreateConstGEP1_32(
7350 BaseAddr, VecTy->getVectorNumElements() * Factor);
7352 CallInst *LdN = Builder.CreateCall(
7353 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
7355 // Extract and store the sub-vectors returned by the load intrinsic.
7356 for (unsigned i = 0; i < Shuffles.size(); i++) {
7357 ShuffleVectorInst *SVI = Shuffles[i];
7358 unsigned Index = Indices[i];
7360 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7362 // Convert the integer vector to pointer vector if the element is pointer.
7363 if (EltTy->isPointerTy())
7364 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7366 SubVecs[SVI].push_back(SubVec);
7370 // Replace uses of the shufflevector instructions with the sub-vectors
7371 // returned by the load intrinsic. If a shufflevector instruction is
7372 // associated with more than one sub-vector, those sub-vectors will be
7373 // concatenated into a single wide vector.
7374 for (ShuffleVectorInst *SVI : Shuffles) {
7375 auto &SubVec = SubVecs[SVI];
7377 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7378 SVI->replaceAllUsesWith(WideVec);
7384 /// \brief Lower an interleaved store into a stN intrinsic.
7386 /// E.g. Lower an interleaved store (Factor = 3):
7387 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7388 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7389 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7392 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7393 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7394 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7395 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7397 /// Note that the new shufflevectors will be removed and we'll only generate one
7398 /// st3 instruction in CodeGen.
7400 /// Example for a more general valid mask (Factor 3). Lower:
7401 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7402 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7403 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7406 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7407 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7408 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7409 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7410 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7411 ShuffleVectorInst *SVI,
7412 unsigned Factor) const {
7413 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7414 "Invalid interleave factor");
7416 VectorType *VecTy = SVI->getType();
7417 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7418 "Invalid interleaved store");
7420 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7421 Type *EltTy = VecTy->getVectorElementType();
7422 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7424 const DataLayout &DL = SI->getModule()->getDataLayout();
7426 // Skip if we do not have NEON and skip illegal vector types. We can
7427 // "legalize" wide vector types into multiple interleaved accesses as long as
7428 // the vector types are divisible by 128.
7429 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
7432 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7434 Value *Op0 = SVI->getOperand(0);
7435 Value *Op1 = SVI->getOperand(1);
7436 IRBuilder<> Builder(SI);
7438 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7439 // vectors to integer vectors.
7440 if (EltTy->isPointerTy()) {
7441 Type *IntTy = DL.getIntPtrType(EltTy);
7442 unsigned NumOpElts =
7443 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7445 // Convert to the corresponding integer vector.
7446 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7447 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7448 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7450 SubVecTy = VectorType::get(IntTy, LaneLen);
7453 // The base address of the store.
7454 Value *BaseAddr = SI->getPointerOperand();
7456 if (NumStores > 1) {
7457 // If we're going to generate more than one store, reset the lane length
7458 // and sub-vector type to something legal.
7459 LaneLen /= NumStores;
7460 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7462 // We will compute the pointer operand of each store from the original base
7463 // address using GEPs. Cast the base address to a pointer to the scalar
7465 BaseAddr = Builder.CreateBitCast(
7466 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7467 SI->getPointerAddressSpace()));
7470 auto Mask = SVI->getShuffleMask();
7472 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7473 Type *Tys[2] = {SubVecTy, PtrTy};
7474 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7475 Intrinsic::aarch64_neon_st3,
7476 Intrinsic::aarch64_neon_st4};
7478 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7480 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
7482 SmallVector<Value *, 5> Ops;
7484 // Split the shufflevector operands into sub vectors for the new stN call.
7485 for (unsigned i = 0; i < Factor; i++) {
7486 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7487 if (Mask[IdxI] >= 0) {
7488 Ops.push_back(Builder.CreateShuffleVector(
7489 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7491 unsigned StartMask = 0;
7492 for (unsigned j = 1; j < LaneLen; j++) {
7493 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7494 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7495 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7499 // Note: Filling undef gaps with random elements is ok, since
7500 // those elements were being written anyway (with undefs).
7501 // In the case of all undefs we're defaulting to using elems from 0
7502 // Note: StartMask cannot be negative, it's checked in
7503 // isReInterleaveMask
7504 Ops.push_back(Builder.CreateShuffleVector(
7505 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7509 // If we generating more than one store, we compute the base address of
7510 // subsequent stores as an offset from the previous.
7512 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7514 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7515 Builder.CreateCall(StNFunc, Ops);
7520 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7521 unsigned AlignCheck) {
7522 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7523 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7526 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7527 unsigned SrcAlign, bool IsMemset,
7530 MachineFunction &MF) const {
7531 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7532 // instruction to materialize the v2i64 zero and one store (with restrictive
7533 // addressing mode). Just do two i64 store of zero-registers.
7535 const Function *F = MF.getFunction();
7536 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7537 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7538 (memOpAlign(SrcAlign, DstAlign, 16) ||
7539 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7543 (memOpAlign(SrcAlign, DstAlign, 8) ||
7544 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7548 (memOpAlign(SrcAlign, DstAlign, 4) ||
7549 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7555 // 12-bit optionally shifted immediates are legal for adds.
7556 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7557 // Avoid UB for INT64_MIN.
7558 if (Immed == std::numeric_limits<int64_t>::min())
7560 // Same encoding for add/sub, just flip the sign.
7561 Immed = std::abs(Immed);
7562 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7565 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7566 // immediates is the same as for an add or a sub.
7567 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7568 return isLegalAddImmediate(Immed);
7571 /// isLegalAddressingMode - Return true if the addressing mode represented
7572 /// by AM is legal for this target, for a load/store of the specified type.
7573 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7574 const AddrMode &AM, Type *Ty,
7575 unsigned AS) const {
7576 // AArch64 has five basic addressing modes:
7578 // reg + 9-bit signed offset
7579 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7581 // reg + SIZE_IN_BYTES * reg
7583 // No global is ever allowed as a base.
7587 // No reg+reg+imm addressing.
7588 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7591 // check reg + imm case:
7592 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7593 uint64_t NumBytes = 0;
7594 if (Ty->isSized()) {
7595 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7596 NumBytes = NumBits / 8;
7597 if (!isPowerOf2_64(NumBits))
7602 int64_t Offset = AM.BaseOffs;
7604 // 9-bit signed offset
7605 if (isInt<9>(Offset))
7608 // 12-bit unsigned offset
7609 unsigned shift = Log2_64(NumBytes);
7610 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7611 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7612 (Offset >> shift) << shift == Offset)
7617 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7619 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7622 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7623 const AddrMode &AM, Type *Ty,
7624 unsigned AS) const {
7625 // Scaling factors are not free at all.
7626 // Operands | Rt Latency
7627 // -------------------------------------------
7629 // -------------------------------------------
7630 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7631 // Rt, [Xn, Wm, <extend> #imm] |
7632 if (isLegalAddressingMode(DL, AM, Ty, AS))
7633 // Scale represents reg2 * scale, thus account for 1 if
7634 // it is not equal to 0 or 1.
7635 return AM.Scale != 0 && AM.Scale != 1;
7639 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7640 VT = VT.getScalarType();
7645 switch (VT.getSimpleVT().SimpleTy) {
7657 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7658 // LR is a callee-save register, but we must treat it as clobbered by any call
7659 // site. Hence we include LR in the scratch registers, which are in turn added
7660 // as implicit-defs for stackmaps and patchpoints.
7661 static const MCPhysReg ScratchRegs[] = {
7662 AArch64::X16, AArch64::X17, AArch64::LR, 0
7668 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7669 EVT VT = N->getValueType(0);
7670 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7671 // it with shift to let it be lowered to UBFX.
7672 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7673 isa<ConstantSDNode>(N->getOperand(1))) {
7674 uint64_t TruncMask = N->getConstantOperandVal(1);
7675 if (isMask_64(TruncMask) &&
7676 N->getOperand(0).getOpcode() == ISD::SRL &&
7677 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7683 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7685 assert(Ty->isIntegerTy());
7687 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7691 int64_t Val = Imm.getSExtValue();
7692 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7695 if ((int64_t)Val < 0)
7698 Val &= (1LL << 32) - 1;
7700 unsigned LZ = countLeadingZeros((uint64_t)Val);
7701 unsigned Shift = (63 - LZ) / 16;
7702 // MOVZ is free so return true for one or fewer MOVK.
7706 /// Turn vector tests of the signbit in the form of:
7707 /// xor (sra X, elt_size(X)-1), -1
7710 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7711 const AArch64Subtarget *Subtarget) {
7712 EVT VT = N->getValueType(0);
7713 if (!Subtarget->hasNEON() || !VT.isVector())
7716 // There must be a shift right algebraic before the xor, and the xor must be a
7718 SDValue Shift = N->getOperand(0);
7719 SDValue Ones = N->getOperand(1);
7720 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7721 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7724 // The shift should be smearing the sign bit across each vector element.
7725 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7726 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7727 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7730 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7733 // Generate SUBS and CSEL for integer abs.
7734 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7735 EVT VT = N->getValueType(0);
7737 SDValue N0 = N->getOperand(0);
7738 SDValue N1 = N->getOperand(1);
7741 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7742 // and change it to SUB and CSEL.
7743 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7744 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7745 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7746 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7747 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7748 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7750 // Generate SUBS & CSEL.
7752 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7753 N0.getOperand(0), DAG.getConstant(0, DL, VT));
7754 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7755 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7756 SDValue(Cmp.getNode(), 1));
7761 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7762 TargetLowering::DAGCombinerInfo &DCI,
7763 const AArch64Subtarget *Subtarget) {
7764 if (DCI.isBeforeLegalizeOps())
7767 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7770 return performIntegerAbsCombine(N, DAG);
7774 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7776 std::vector<SDNode *> *Created) const {
7777 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7778 if (isIntDivCheap(N->getValueType(0), Attr))
7779 return SDValue(N,0); // Lower SDIV as SDIV
7781 // fold (sdiv X, pow2)
7782 EVT VT = N->getValueType(0);
7783 if ((VT != MVT::i32 && VT != MVT::i64) ||
7784 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7788 SDValue N0 = N->getOperand(0);
7789 unsigned Lg2 = Divisor.countTrailingZeros();
7790 SDValue Zero = DAG.getConstant(0, DL, VT);
7791 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7793 // Add (N0 < 0) ? Pow2 - 1 : 0;
7795 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7796 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7797 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7800 Created->push_back(Cmp.getNode());
7801 Created->push_back(Add.getNode());
7802 Created->push_back(CSel.getNode());
7807 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7809 // If we're dividing by a positive value, we're done. Otherwise, we must
7810 // negate the result.
7811 if (Divisor.isNonNegative())
7815 Created->push_back(SRA.getNode());
7816 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7819 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7820 TargetLowering::DAGCombinerInfo &DCI,
7821 const AArch64Subtarget *Subtarget) {
7822 if (DCI.isBeforeLegalizeOps())
7825 // The below optimizations require a constant RHS.
7826 if (!isa<ConstantSDNode>(N->getOperand(1)))
7829 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7830 const APInt &ConstValue = C->getAPIntValue();
7832 // Multiplication of a power of two plus/minus one can be done more
7833 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7834 // future CPUs have a cheaper MADD instruction, this may need to be
7835 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7836 // 64-bit is 5 cycles, so this is always a win.
7837 // More aggressively, some multiplications N0 * C can be lowered to
7838 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7839 // e.g. 6=3*2=(2+1)*2.
7840 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7841 // which equals to (1+2)*16-(1+2).
7842 SDValue N0 = N->getOperand(0);
7843 // TrailingZeroes is used to test if the mul can be lowered to
7845 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7846 if (TrailingZeroes) {
7847 // Conservatively do not lower to shift+add+shift if the mul might be
7848 // folded into smul or umul.
7849 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7850 isZeroExtended(N0.getNode(), DAG)))
7852 // Conservatively do not lower to shift+add+shift if the mul might be
7853 // folded into madd or msub.
7854 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7855 N->use_begin()->getOpcode() == ISD::SUB))
7858 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7859 // and shift+add+shift.
7860 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7862 unsigned ShiftAmt, AddSubOpc;
7863 // Is the shifted value the LHS operand of the add/sub?
7864 bool ShiftValUseIsN0 = true;
7865 // Do we need to negate the result?
7866 bool NegateResult = false;
7868 if (ConstValue.isNonNegative()) {
7869 // (mul x, 2^N + 1) => (add (shl x, N), x)
7870 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7871 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7872 APInt SCVMinus1 = ShiftedConstValue - 1;
7873 APInt CVPlus1 = ConstValue + 1;
7874 if (SCVMinus1.isPowerOf2()) {
7875 ShiftAmt = SCVMinus1.logBase2();
7876 AddSubOpc = ISD::ADD;
7877 } else if (CVPlus1.isPowerOf2()) {
7878 ShiftAmt = CVPlus1.logBase2();
7879 AddSubOpc = ISD::SUB;
7883 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7884 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7885 APInt CVNegPlus1 = -ConstValue + 1;
7886 APInt CVNegMinus1 = -ConstValue - 1;
7887 if (CVNegPlus1.isPowerOf2()) {
7888 ShiftAmt = CVNegPlus1.logBase2();
7889 AddSubOpc = ISD::SUB;
7890 ShiftValUseIsN0 = false;
7891 } else if (CVNegMinus1.isPowerOf2()) {
7892 ShiftAmt = CVNegMinus1.logBase2();
7893 AddSubOpc = ISD::ADD;
7894 NegateResult = true;
7900 EVT VT = N->getValueType(0);
7901 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
7902 DAG.getConstant(ShiftAmt, DL, MVT::i64));
7904 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7905 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7906 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
7907 assert(!(NegateResult && TrailingZeroes) &&
7908 "NegateResult and TrailingZeroes cannot both be true for now.");
7909 // Negate the result.
7911 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7912 // Shift the result.
7914 return DAG.getNode(ISD::SHL, DL, VT, Res,
7915 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7919 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7920 SelectionDAG &DAG) {
7921 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7922 // optimize away operation when it's from a constant.
7924 // The general transformation is:
7925 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7926 // AND(VECTOR_CMP(x,y), constant2)
7927 // constant2 = UNARYOP(constant)
7929 // Early exit if this isn't a vector operation, the operand of the
7930 // unary operation isn't a bitwise AND, or if the sizes of the operations
7932 EVT VT = N->getValueType(0);
7933 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7934 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7935 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7938 // Now check that the other operand of the AND is a constant. We could
7939 // make the transformation for non-constant splats as well, but it's unclear
7940 // that would be a benefit as it would not eliminate any operations, just
7941 // perform one more step in scalar code before moving to the vector unit.
7942 if (BuildVectorSDNode *BV =
7943 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7944 // Bail out if the vector isn't a constant.
7945 if (!BV->isConstant())
7948 // Everything checks out. Build up the new and improved node.
7950 EVT IntVT = BV->getValueType(0);
7951 // Create a new constant of the appropriate type for the transformed
7953 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7954 // The AND node needs bitcasts to/from an integer vector type around it.
7955 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7956 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7957 N->getOperand(0)->getOperand(0), MaskConst);
7958 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7965 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7966 const AArch64Subtarget *Subtarget) {
7967 // First try to optimize away the conversion when it's conditionally from
7968 // a constant. Vectors only.
7969 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7972 EVT VT = N->getValueType(0);
7973 if (VT != MVT::f32 && VT != MVT::f64)
7976 // Only optimize when the source and destination types have the same width.
7977 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
7980 // If the result of an integer load is only used by an integer-to-float
7981 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7982 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7983 SDValue N0 = N->getOperand(0);
7984 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7985 // Do not change the width of a volatile load.
7986 !cast<LoadSDNode>(N0)->isVolatile()) {
7987 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7988 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7989 LN0->getPointerInfo(), LN0->getAlignment(),
7990 LN0->getMemOperand()->getFlags());
7992 // Make sure successors of the original load stay after it by updating them
7993 // to use the new Chain.
7994 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7997 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7998 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8004 /// Fold a floating-point multiply by power of two into floating-point to
8005 /// fixed-point conversion.
8006 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8007 TargetLowering::DAGCombinerInfo &DCI,
8008 const AArch64Subtarget *Subtarget) {
8009 if (!Subtarget->hasNEON())
8012 SDValue Op = N->getOperand(0);
8013 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8014 Op.getOpcode() != ISD::FMUL)
8017 SDValue ConstVec = Op->getOperand(1);
8018 if (!isa<BuildVectorSDNode>(ConstVec))
8021 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8022 uint32_t FloatBits = FloatTy.getSizeInBits();
8023 if (FloatBits != 32 && FloatBits != 64)
8026 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8027 uint32_t IntBits = IntTy.getSizeInBits();
8028 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8031 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8032 if (IntBits > FloatBits)
8035 BitVector UndefElements;
8036 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8037 int32_t Bits = IntBits == 64 ? 64 : 32;
8038 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8039 if (C == -1 || C == 0 || C > Bits)
8043 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8048 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8051 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8055 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8058 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8059 "Illegal vector type after legalization");
8062 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8063 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8064 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8066 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8067 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8068 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8069 // We can handle smaller integers by generating an extra trunc.
8070 if (IntBits < FloatBits)
8071 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8076 /// Fold a floating-point divide by power of two into fixed-point to
8077 /// floating-point conversion.
8078 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
8079 TargetLowering::DAGCombinerInfo &DCI,
8080 const AArch64Subtarget *Subtarget) {
8081 if (!Subtarget->hasNEON())
8084 SDValue Op = N->getOperand(0);
8085 unsigned Opc = Op->getOpcode();
8086 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8087 !Op.getOperand(0).getValueType().isSimple() ||
8088 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8091 SDValue ConstVec = N->getOperand(1);
8092 if (!isa<BuildVectorSDNode>(ConstVec))
8095 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8096 int32_t IntBits = IntTy.getSizeInBits();
8097 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8100 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8101 int32_t FloatBits = FloatTy.getSizeInBits();
8102 if (FloatBits != 32 && FloatBits != 64)
8105 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8106 if (IntBits > FloatBits)
8109 BitVector UndefElements;
8110 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8111 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8112 if (C == -1 || C == 0 || C > FloatBits)
8116 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8121 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8124 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8128 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8132 SDValue ConvInput = Op.getOperand(0);
8133 bool IsSigned = Opc == ISD::SINT_TO_FP;
8134 if (IntBits < FloatBits)
8135 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8138 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8139 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8140 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8141 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8142 DAG.getConstant(C, DL, MVT::i32));
8145 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8146 /// searches for and classifies those shifts.
8147 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8149 if (N.getOpcode() == ISD::SHL)
8151 else if (N.getOpcode() == ISD::SRL)
8156 if (!isa<ConstantSDNode>(N.getOperand(1)))
8159 ShiftAmount = N->getConstantOperandVal(1);
8160 Src = N->getOperand(0);
8164 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8165 /// registers viewed as a high/low pair. This function looks for the pattern:
8166 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8167 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
8169 static SDValue tryCombineToEXTR(SDNode *N,
8170 TargetLowering::DAGCombinerInfo &DCI) {
8171 SelectionDAG &DAG = DCI.DAG;
8173 EVT VT = N->getValueType(0);
8175 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8177 if (VT != MVT::i32 && VT != MVT::i64)
8181 uint32_t ShiftLHS = 0;
8182 bool LHSFromHi = false;
8183 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8187 uint32_t ShiftRHS = 0;
8188 bool RHSFromHi = false;
8189 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8192 // If they're both trying to come from the high part of the register, they're
8193 // not really an EXTR.
8194 if (LHSFromHi == RHSFromHi)
8197 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8201 std::swap(LHS, RHS);
8202 std::swap(ShiftLHS, ShiftRHS);
8205 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8206 DAG.getConstant(ShiftRHS, DL, MVT::i64));
8209 static SDValue tryCombineToBSL(SDNode *N,
8210 TargetLowering::DAGCombinerInfo &DCI) {
8211 EVT VT = N->getValueType(0);
8212 SelectionDAG &DAG = DCI.DAG;
8218 SDValue N0 = N->getOperand(0);
8219 if (N0.getOpcode() != ISD::AND)
8222 SDValue N1 = N->getOperand(1);
8223 if (N1.getOpcode() != ISD::AND)
8226 // We only have to look for constant vectors here since the general, variable
8227 // case can be handled in TableGen.
8228 unsigned Bits = VT.getScalarSizeInBits();
8229 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8230 for (int i = 1; i >= 0; --i)
8231 for (int j = 1; j >= 0; --j) {
8232 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8233 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8237 bool FoundMatch = true;
8238 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8239 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8240 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8242 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8249 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8250 N0->getOperand(1 - i), N1->getOperand(1 - j));
8256 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8257 const AArch64Subtarget *Subtarget) {
8258 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8259 SelectionDAG &DAG = DCI.DAG;
8260 EVT VT = N->getValueType(0);
8262 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8265 if (SDValue Res = tryCombineToEXTR(N, DCI))
8268 if (SDValue Res = tryCombineToBSL(N, DCI))
8274 static SDValue performSRLCombine(SDNode *N,
8275 TargetLowering::DAGCombinerInfo &DCI) {
8276 SelectionDAG &DAG = DCI.DAG;
8277 EVT VT = N->getValueType(0);
8278 if (VT != MVT::i32 && VT != MVT::i64)
8281 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8282 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8283 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8284 SDValue N0 = N->getOperand(0);
8285 if (N0.getOpcode() == ISD::BSWAP) {
8287 SDValue N1 = N->getOperand(1);
8288 SDValue N00 = N0.getOperand(0);
8289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8290 uint64_t ShiftAmt = C->getZExtValue();
8291 if (VT == MVT::i32 && ShiftAmt == 16 &&
8292 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8293 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8294 if (VT == MVT::i64 && ShiftAmt == 32 &&
8295 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8296 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8302 static SDValue performBitcastCombine(SDNode *N,
8303 TargetLowering::DAGCombinerInfo &DCI,
8304 SelectionDAG &DAG) {
8305 // Wait 'til after everything is legalized to try this. That way we have
8306 // legal vector types and such.
8307 if (DCI.isBeforeLegalizeOps())
8310 // Remove extraneous bitcasts around an extract_subvector.
8312 // (v4i16 (bitconvert
8313 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8315 // (extract_subvector ((v8i16 ...), (i64 4)))
8317 // Only interested in 64-bit vectors as the ultimate result.
8318 EVT VT = N->getValueType(0);
8321 if (VT.getSimpleVT().getSizeInBits() != 64)
8323 // Is the operand an extract_subvector starting at the beginning or halfway
8324 // point of the vector? A low half may also come through as an
8325 // EXTRACT_SUBREG, so look for that, too.
8326 SDValue Op0 = N->getOperand(0);
8327 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8328 !(Op0->isMachineOpcode() &&
8329 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8331 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8332 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8333 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8335 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8336 if (idx != AArch64::dsub)
8338 // The dsub reference is equivalent to a lane zero subvector reference.
8341 // Look through the bitcast of the input to the extract.
8342 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8344 SDValue Source = Op0->getOperand(0)->getOperand(0);
8345 // If the source type has twice the number of elements as our destination
8346 // type, we know this is an extract of the high or low half of the vector.
8347 EVT SVT = Source->getValueType(0);
8348 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8351 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8353 // Create the simplified form to just extract the low or high half of the
8354 // vector directly rather than bothering with the bitcasts.
8356 unsigned NumElements = VT.getVectorNumElements();
8358 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8359 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8361 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8362 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8368 static SDValue performConcatVectorsCombine(SDNode *N,
8369 TargetLowering::DAGCombinerInfo &DCI,
8370 SelectionDAG &DAG) {
8372 EVT VT = N->getValueType(0);
8373 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8375 // Optimize concat_vectors of truncated vectors, where the intermediate
8376 // type is illegal, to avoid said illegality, e.g.,
8377 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8378 // (v2i16 (truncate (v2i64)))))
8380 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8381 // (v4i32 (bitcast (v2i64))),
8383 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8384 // on both input and result type, so we might generate worse code.
8385 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8386 if (N->getNumOperands() == 2 &&
8387 N0->getOpcode() == ISD::TRUNCATE &&
8388 N1->getOpcode() == ISD::TRUNCATE) {
8389 SDValue N00 = N0->getOperand(0);
8390 SDValue N10 = N1->getOperand(0);
8391 EVT N00VT = N00.getValueType();
8393 if (N00VT == N10.getValueType() &&
8394 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8395 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8396 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8397 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8398 for (size_t i = 0; i < Mask.size(); ++i)
8400 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8401 DAG.getVectorShuffle(
8403 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8404 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8408 // Wait 'til after everything is legalized to try this. That way we have
8409 // legal vector types and such.
8410 if (DCI.isBeforeLegalizeOps())
8413 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8414 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8415 // canonicalise to that.
8416 if (N0 == N1 && VT.getVectorNumElements() == 2) {
8417 assert(VT.getScalarSizeInBits() == 64);
8418 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8419 DAG.getConstant(0, dl, MVT::i64));
8422 // Canonicalise concat_vectors so that the right-hand vector has as few
8423 // bit-casts as possible before its real operation. The primary matching
8424 // destination for these operations will be the narrowing "2" instructions,
8425 // which depend on the operation being performed on this right-hand vector.
8427 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8429 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8431 if (N1->getOpcode() != ISD::BITCAST)
8433 SDValue RHS = N1->getOperand(0);
8434 MVT RHSTy = RHS.getValueType().getSimpleVT();
8435 // If the RHS is not a vector, this is not the pattern we're looking for.
8436 if (!RHSTy.isVector())
8439 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8441 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8442 RHSTy.getVectorNumElements() * 2);
8443 return DAG.getNode(ISD::BITCAST, dl, VT,
8444 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8445 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8449 static SDValue tryCombineFixedPointConvert(SDNode *N,
8450 TargetLowering::DAGCombinerInfo &DCI,
8451 SelectionDAG &DAG) {
8452 // Wait 'til after everything is legalized to try this. That way we have
8453 // legal vector types and such.
8454 if (DCI.isBeforeLegalizeOps())
8456 // Transform a scalar conversion of a value from a lane extract into a
8457 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8458 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8459 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8461 // The second form interacts better with instruction selection and the
8462 // register allocator to avoid cross-class register copies that aren't
8463 // coalescable due to a lane reference.
8465 // Check the operand and see if it originates from a lane extract.
8466 SDValue Op1 = N->getOperand(1);
8467 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8468 // Yep, no additional predication needed. Perform the transform.
8469 SDValue IID = N->getOperand(0);
8470 SDValue Shift = N->getOperand(2);
8471 SDValue Vec = Op1.getOperand(0);
8472 SDValue Lane = Op1.getOperand(1);
8473 EVT ResTy = N->getValueType(0);
8477 // The vector width should be 128 bits by the time we get here, even
8478 // if it started as 64 bits (the extract_vector handling will have
8480 assert(Vec.getValueSizeInBits() == 128 &&
8481 "unexpected vector size on extract_vector_elt!");
8482 if (Vec.getValueType() == MVT::v4i32)
8483 VecResTy = MVT::v4f32;
8484 else if (Vec.getValueType() == MVT::v2i64)
8485 VecResTy = MVT::v2f64;
8487 llvm_unreachable("unexpected vector type!");
8490 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8491 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8496 // AArch64 high-vector "long" operations are formed by performing the non-high
8497 // version on an extract_subvector of each operand which gets the high half:
8499 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8501 // However, there are cases which don't have an extract_high explicitly, but
8502 // have another operation that can be made compatible with one for free. For
8505 // (dupv64 scalar) --> (extract_high (dup128 scalar))
8507 // This routine does the actual conversion of such DUPs, once outer routines
8508 // have determined that everything else is in order.
8509 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8511 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8512 switch (N.getOpcode()) {
8513 case AArch64ISD::DUP:
8514 case AArch64ISD::DUPLANE8:
8515 case AArch64ISD::DUPLANE16:
8516 case AArch64ISD::DUPLANE32:
8517 case AArch64ISD::DUPLANE64:
8518 case AArch64ISD::MOVI:
8519 case AArch64ISD::MOVIshift:
8520 case AArch64ISD::MOVIedit:
8521 case AArch64ISD::MOVImsl:
8522 case AArch64ISD::MVNIshift:
8523 case AArch64ISD::MVNImsl:
8526 // FMOV could be supported, but isn't very useful, as it would only occur
8527 // if you passed a bitcast' floating point immediate to an eligible long
8528 // integer op (addl, smull, ...).
8532 MVT NarrowTy = N.getSimpleValueType();
8533 if (!NarrowTy.is64BitVector())
8536 MVT ElementTy = NarrowTy.getVectorElementType();
8537 unsigned NumElems = NarrowTy.getVectorNumElements();
8538 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8541 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8542 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8543 DAG.getConstant(NumElems, dl, MVT::i64));
8546 static bool isEssentiallyExtractSubvector(SDValue N) {
8547 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8550 return N.getOpcode() == ISD::BITCAST &&
8551 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8554 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8555 struct GenericSetCCInfo {
8556 const SDValue *Opnd0;
8557 const SDValue *Opnd1;
8561 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8562 struct AArch64SetCCInfo {
8564 AArch64CC::CondCode CC;
8567 /// \brief Helper structure to keep track of SetCC information.
8569 GenericSetCCInfo Generic;
8570 AArch64SetCCInfo AArch64;
8573 /// \brief Helper structure to be able to read SetCC information. If set to
8574 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8575 /// GenericSetCCInfo.
8576 struct SetCCInfoAndKind {
8581 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8583 /// AArch64 lowered one.
8584 /// \p SetCCInfo is filled accordingly.
8585 /// \post SetCCInfo is meanginfull only when this function returns true.
8586 /// \return True when Op is a kind of SET_CC operation.
8587 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8588 // If this is a setcc, this is straight forward.
8589 if (Op.getOpcode() == ISD::SETCC) {
8590 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8591 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8592 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8593 SetCCInfo.IsAArch64 = false;
8596 // Otherwise, check if this is a matching csel instruction.
8600 if (Op.getOpcode() != AArch64ISD::CSEL)
8602 // Set the information about the operands.
8603 // TODO: we want the operands of the Cmp not the csel
8604 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8605 SetCCInfo.IsAArch64 = true;
8606 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8607 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8609 // Check that the operands matches the constraints:
8610 // (1) Both operands must be constants.
8611 // (2) One must be 1 and the other must be 0.
8612 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8613 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8616 if (!TValue || !FValue)
8620 if (!TValue->isOne()) {
8621 // Update the comparison when we are interested in !cc.
8622 std::swap(TValue, FValue);
8623 SetCCInfo.Info.AArch64.CC =
8624 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8626 return TValue->isOne() && FValue->isNullValue();
8629 // Returns true if Op is setcc or zext of setcc.
8630 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8631 if (isSetCC(Op, Info))
8633 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8634 isSetCC(Op->getOperand(0), Info));
8637 // The folding we want to perform is:
8638 // (add x, [zext] (setcc cc ...) )
8640 // (csel x, (add x, 1), !cc ...)
8642 // The latter will get matched to a CSINC instruction.
8643 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8644 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8645 SDValue LHS = Op->getOperand(0);
8646 SDValue RHS = Op->getOperand(1);
8647 SetCCInfoAndKind InfoAndKind;
8649 // If neither operand is a SET_CC, give up.
8650 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8651 std::swap(LHS, RHS);
8652 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8656 // FIXME: This could be generatized to work for FP comparisons.
8657 EVT CmpVT = InfoAndKind.IsAArch64
8658 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8659 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8660 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8666 if (InfoAndKind.IsAArch64) {
8667 CCVal = DAG.getConstant(
8668 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8670 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8672 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8673 *InfoAndKind.Info.Generic.Opnd1,
8674 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8677 EVT VT = Op->getValueType(0);
8678 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8679 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8682 // The basic add/sub long vector instructions have variants with "2" on the end
8683 // which act on the high-half of their inputs. They are normally matched by
8686 // (add (zeroext (extract_high LHS)),
8687 // (zeroext (extract_high RHS)))
8688 // -> uaddl2 vD, vN, vM
8690 // However, if one of the extracts is something like a duplicate, this
8691 // instruction can still be used profitably. This function puts the DAG into a
8692 // more appropriate form for those patterns to trigger.
8693 static SDValue performAddSubLongCombine(SDNode *N,
8694 TargetLowering::DAGCombinerInfo &DCI,
8695 SelectionDAG &DAG) {
8696 if (DCI.isBeforeLegalizeOps())
8699 MVT VT = N->getSimpleValueType(0);
8700 if (!VT.is128BitVector()) {
8701 if (N->getOpcode() == ISD::ADD)
8702 return performSetccAddFolding(N, DAG);
8706 // Make sure both branches are extended in the same way.
8707 SDValue LHS = N->getOperand(0);
8708 SDValue RHS = N->getOperand(1);
8709 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8710 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8711 LHS.getOpcode() != RHS.getOpcode())
8714 unsigned ExtType = LHS.getOpcode();
8716 // It's not worth doing if at least one of the inputs isn't already an
8717 // extract, but we don't know which it'll be so we have to try both.
8718 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8719 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8723 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8724 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8725 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8729 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8732 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8735 // Massage DAGs which we can use the high-half "long" operations on into
8736 // something isel will recognize better. E.g.
8738 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8739 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8740 // (extract_high (v2i64 (dup128 scalar)))))
8742 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8743 TargetLowering::DAGCombinerInfo &DCI,
8744 SelectionDAG &DAG) {
8745 if (DCI.isBeforeLegalizeOps())
8748 SDValue LHS = N->getOperand(1);
8749 SDValue RHS = N->getOperand(2);
8750 assert(LHS.getValueType().is64BitVector() &&
8751 RHS.getValueType().is64BitVector() &&
8752 "unexpected shape for long operation");
8754 // Either node could be a DUP, but it's not worth doing both of them (you'd
8755 // just as well use the non-high version) so look for a corresponding extract
8756 // operation on the other "wing".
8757 if (isEssentiallyExtractSubvector(LHS)) {
8758 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8761 } else if (isEssentiallyExtractSubvector(RHS)) {
8762 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8767 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8768 N->getOperand(0), LHS, RHS);
8771 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8772 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8773 unsigned ElemBits = ElemTy.getSizeInBits();
8775 int64_t ShiftAmount;
8776 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8777 APInt SplatValue, SplatUndef;
8778 unsigned SplatBitSize;
8780 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8781 HasAnyUndefs, ElemBits) ||
8782 SplatBitSize != ElemBits)
8785 ShiftAmount = SplatValue.getSExtValue();
8786 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8787 ShiftAmount = CVN->getSExtValue();
8795 llvm_unreachable("Unknown shift intrinsic");
8796 case Intrinsic::aarch64_neon_sqshl:
8797 Opcode = AArch64ISD::SQSHL_I;
8798 IsRightShift = false;
8800 case Intrinsic::aarch64_neon_uqshl:
8801 Opcode = AArch64ISD::UQSHL_I;
8802 IsRightShift = false;
8804 case Intrinsic::aarch64_neon_srshl:
8805 Opcode = AArch64ISD::SRSHR_I;
8806 IsRightShift = true;
8808 case Intrinsic::aarch64_neon_urshl:
8809 Opcode = AArch64ISD::URSHR_I;
8810 IsRightShift = true;
8812 case Intrinsic::aarch64_neon_sqshlu:
8813 Opcode = AArch64ISD::SQSHLU_I;
8814 IsRightShift = false;
8818 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8820 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8821 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8822 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8824 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8825 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8831 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8832 // the intrinsics must be legal and take an i32, this means there's almost
8833 // certainly going to be a zext in the DAG which we can eliminate.
8834 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8835 SDValue AndN = N->getOperand(2);
8836 if (AndN.getOpcode() != ISD::AND)
8839 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8840 if (!CMask || CMask->getZExtValue() != Mask)
8843 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8844 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8847 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8848 SelectionDAG &DAG) {
8850 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8851 DAG.getNode(Opc, dl,
8852 N->getOperand(1).getSimpleValueType(),
8854 DAG.getConstant(0, dl, MVT::i64));
8857 static SDValue performIntrinsicCombine(SDNode *N,
8858 TargetLowering::DAGCombinerInfo &DCI,
8859 const AArch64Subtarget *Subtarget) {
8860 SelectionDAG &DAG = DCI.DAG;
8861 unsigned IID = getIntrinsicID(N);
8865 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8866 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8867 return tryCombineFixedPointConvert(N, DCI, DAG);
8868 case Intrinsic::aarch64_neon_saddv:
8869 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8870 case Intrinsic::aarch64_neon_uaddv:
8871 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8872 case Intrinsic::aarch64_neon_sminv:
8873 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8874 case Intrinsic::aarch64_neon_uminv:
8875 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8876 case Intrinsic::aarch64_neon_smaxv:
8877 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8878 case Intrinsic::aarch64_neon_umaxv:
8879 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8880 case Intrinsic::aarch64_neon_fmax:
8881 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8882 N->getOperand(1), N->getOperand(2));
8883 case Intrinsic::aarch64_neon_fmin:
8884 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8885 N->getOperand(1), N->getOperand(2));
8886 case Intrinsic::aarch64_neon_fmaxnm:
8887 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8888 N->getOperand(1), N->getOperand(2));
8889 case Intrinsic::aarch64_neon_fminnm:
8890 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8891 N->getOperand(1), N->getOperand(2));
8892 case Intrinsic::aarch64_neon_smull:
8893 case Intrinsic::aarch64_neon_umull:
8894 case Intrinsic::aarch64_neon_pmull:
8895 case Intrinsic::aarch64_neon_sqdmull:
8896 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8897 case Intrinsic::aarch64_neon_sqshl:
8898 case Intrinsic::aarch64_neon_uqshl:
8899 case Intrinsic::aarch64_neon_sqshlu:
8900 case Intrinsic::aarch64_neon_srshl:
8901 case Intrinsic::aarch64_neon_urshl:
8902 return tryCombineShiftImm(IID, N, DAG);
8903 case Intrinsic::aarch64_crc32b:
8904 case Intrinsic::aarch64_crc32cb:
8905 return tryCombineCRC32(0xff, N, DAG);
8906 case Intrinsic::aarch64_crc32h:
8907 case Intrinsic::aarch64_crc32ch:
8908 return tryCombineCRC32(0xffff, N, DAG);
8913 static SDValue performExtendCombine(SDNode *N,
8914 TargetLowering::DAGCombinerInfo &DCI,
8915 SelectionDAG &DAG) {
8916 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8917 // we can convert that DUP into another extract_high (of a bigger DUP), which
8918 // helps the backend to decide that an sabdl2 would be useful, saving a real
8919 // extract_high operation.
8920 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8921 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8922 SDNode *ABDNode = N->getOperand(0).getNode();
8923 unsigned IID = getIntrinsicID(ABDNode);
8924 if (IID == Intrinsic::aarch64_neon_sabd ||
8925 IID == Intrinsic::aarch64_neon_uabd) {
8926 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8927 if (!NewABD.getNode())
8930 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8935 // This is effectively a custom type legalization for AArch64.
8937 // Type legalization will split an extend of a small, legal, type to a larger
8938 // illegal type by first splitting the destination type, often creating
8939 // illegal source types, which then get legalized in isel-confusing ways,
8940 // leading to really terrible codegen. E.g.,
8941 // %result = v8i32 sext v8i8 %value
8943 // %losrc = extract_subreg %value, ...
8944 // %hisrc = extract_subreg %value, ...
8945 // %lo = v4i32 sext v4i8 %losrc
8946 // %hi = v4i32 sext v4i8 %hisrc
8947 // Things go rapidly downhill from there.
8949 // For AArch64, the [sz]ext vector instructions can only go up one element
8950 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8951 // take two instructions.
8953 // This implies that the most efficient way to do the extend from v8i8
8954 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8955 // the normal splitting to happen for the v8i16->v8i32.
8957 // This is pre-legalization to catch some cases where the default
8958 // type legalization will create ill-tempered code.
8959 if (!DCI.isBeforeLegalizeOps())
8962 // We're only interested in cleaning things up for non-legal vector types
8963 // here. If both the source and destination are legal, things will just
8964 // work naturally without any fiddling.
8965 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8966 EVT ResVT = N->getValueType(0);
8967 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8969 // If the vector type isn't a simple VT, it's beyond the scope of what
8970 // we're worried about here. Let legalization do its thing and hope for
8972 SDValue Src = N->getOperand(0);
8973 EVT SrcVT = Src->getValueType(0);
8974 if (!ResVT.isSimple() || !SrcVT.isSimple())
8977 // If the source VT is a 64-bit vector, we can play games and get the
8978 // better results we want.
8979 if (SrcVT.getSizeInBits() != 64)
8982 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
8983 unsigned ElementCount = SrcVT.getVectorNumElements();
8984 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8986 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8988 // Now split the rest of the operation into two halves, each with a 64
8992 unsigned NumElements = ResVT.getVectorNumElements();
8993 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8994 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8995 ResVT.getVectorElementType(), NumElements / 2);
8997 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8998 LoVT.getVectorNumElements());
8999 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9000 DAG.getConstant(0, DL, MVT::i64));
9001 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9002 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9003 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9004 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9006 // Now combine the parts back together so we still have a single result
9007 // like the combiner expects.
9008 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9011 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9012 SDValue SplatVal, unsigned NumVecElts) {
9013 unsigned OrigAlignment = St.getAlignment();
9014 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
9016 // Create scalar stores. This is at least as good as the code sequence for a
9017 // split unaligned store which is a dup.s, ext.b, and two stores.
9018 // Most of the time the three stores should be replaced by store pair
9019 // instructions (stp).
9021 SDValue BasePtr = St.getBasePtr();
9022 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
9024 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
9025 OrigAlignment, St.getMemOperand()->getFlags());
9027 unsigned Offset = EltOffset;
9028 while (--NumVecElts) {
9029 unsigned Alignment = MinAlign(OrigAlignment, Offset);
9030 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9031 DAG.getConstant(Offset, DL, MVT::i64));
9032 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
9033 PtrInfo.getWithOffset(Offset), Alignment,
9034 St.getMemOperand()->getFlags());
9035 Offset += EltOffset;
9040 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9041 /// load store optimizer pass will merge them to store pair stores. This should
9042 /// be better than a movi to create the vector zero followed by a vector store
9043 /// if the zero constant is not re-used, since one instructions and one register
9044 /// live range will be removed.
9046 /// For example, the final generated code should be:
9048 /// stp xzr, xzr, [x0]
9055 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9056 SDValue StVal = St.getValue();
9057 EVT VT = StVal.getValueType();
9059 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9060 // 2, 3 or 4 i32 elements.
9061 int NumVecElts = VT.getVectorNumElements();
9062 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9063 VT.getVectorElementType().getSizeInBits() == 64) ||
9064 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9065 VT.getVectorElementType().getSizeInBits() == 32)))
9068 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9071 // If the zero constant has more than one use then the vector store could be
9072 // better since the constant mov will be amortized and stp q instructions
9073 // should be able to be formed.
9074 if (!StVal.hasOneUse())
9077 // If the immediate offset of the address operand is too large for the stp
9078 // instruction, then bail out.
9079 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9080 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
9081 if (Offset < -512 || Offset > 504)
9085 for (int I = 0; I < NumVecElts; ++I) {
9086 SDValue EltVal = StVal.getOperand(I);
9087 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9091 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9092 // undoing this transformation.
9093 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9094 ? DAG.getRegister(AArch64::WZR, MVT::i32)
9095 : DAG.getRegister(AArch64::XZR, MVT::i64);
9096 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9099 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9100 /// value. The load store optimizer pass will merge them to store pair stores.
9101 /// This has better performance than a splat of the scalar followed by a split
9102 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9103 /// followed by an ext.b and two stores.
9104 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9105 SDValue StVal = St.getValue();
9106 EVT VT = StVal.getValueType();
9108 // Don't replace floating point stores, they possibly won't be transformed to
9109 // stp because of the store pair suppress pass.
9110 if (VT.isFloatingPoint())
9113 // We can express a splat as store pair(s) for 2 or 4 elements.
9114 unsigned NumVecElts = VT.getVectorNumElements();
9115 if (NumVecElts != 4 && NumVecElts != 2)
9118 // Check that this is a splat.
9119 // Make sure that each of the relevant vector element locations are inserted
9120 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9121 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9123 for (unsigned I = 0; I < NumVecElts; ++I) {
9124 // Check for insert vector elements.
9125 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9128 // Check that same value is inserted at each vector element.
9130 SplatVal = StVal.getOperand(1);
9131 else if (StVal.getOperand(1) != SplatVal)
9134 // Check insert element index.
9135 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9138 uint64_t IndexVal = CIndex->getZExtValue();
9139 if (IndexVal >= NumVecElts)
9141 IndexNotInserted.reset(IndexVal);
9143 StVal = StVal.getOperand(0);
9145 // Check that all vector element locations were inserted to.
9146 if (IndexNotInserted.any())
9149 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9152 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9154 const AArch64Subtarget *Subtarget) {
9155 if (!DCI.isBeforeLegalize())
9158 StoreSDNode *S = cast<StoreSDNode>(N);
9159 if (S->isVolatile())
9162 SDValue StVal = S->getValue();
9163 EVT VT = StVal.getValueType();
9167 // If we get a splat of zeros, convert this vector store to a store of
9168 // scalars. They will be merged into store pairs of xzr thereby removing one
9169 // instruction and one register.
9170 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9171 return ReplacedZeroSplat;
9173 // FIXME: The logic for deciding if an unaligned store should be split should
9174 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9175 // a call to that function here.
9177 if (!Subtarget->isMisaligned128StoreSlow())
9180 // Don't split at -Oz.
9181 if (DAG.getMachineFunction().getFunction()->optForMinSize())
9184 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9185 // those up regresses performance on micro-benchmarks and olden/bh.
9186 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9189 // Split unaligned 16B stores. They are terrible for performance.
9190 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9191 // extensions can use this to mark that it does not want splitting to happen
9192 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9193 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9194 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9195 S->getAlignment() <= 2)
9198 // If we get a splat of a scalar convert this vector store to a store of
9199 // scalars. They will be merged into store pairs thereby removing two
9201 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9202 return ReplacedSplat;
9205 unsigned NumElts = VT.getVectorNumElements() / 2;
9206 // Split VT into two.
9208 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9209 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9210 DAG.getConstant(0, DL, MVT::i64));
9211 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9212 DAG.getConstant(NumElts, DL, MVT::i64));
9213 SDValue BasePtr = S->getBasePtr();
9215 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9216 S->getAlignment(), S->getMemOperand()->getFlags());
9217 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9218 DAG.getConstant(8, DL, MVT::i64));
9219 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9220 S->getPointerInfo(), S->getAlignment(),
9221 S->getMemOperand()->getFlags());
9224 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9225 /// post-increment LD1R.
9226 static SDValue performPostLD1Combine(SDNode *N,
9227 TargetLowering::DAGCombinerInfo &DCI,
9229 if (DCI.isBeforeLegalizeOps())
9232 SelectionDAG &DAG = DCI.DAG;
9233 EVT VT = N->getValueType(0);
9235 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9236 SDNode *LD = N->getOperand(LoadIdx).getNode();
9237 // If it is not LOAD, can not do such combine.
9238 if (LD->getOpcode() != ISD::LOAD)
9241 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9242 EVT MemVT = LoadSDN->getMemoryVT();
9243 // Check if memory operand is the same type as the vector element.
9244 if (MemVT != VT.getVectorElementType())
9247 // Check if there are other uses. If so, do not combine as it will introduce
9249 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9251 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9257 SDValue Addr = LD->getOperand(1);
9258 SDValue Vector = N->getOperand(0);
9259 // Search for a use of the address operand that is an increment.
9260 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9261 Addr.getNode()->use_end(); UI != UE; ++UI) {
9263 if (User->getOpcode() != ISD::ADD
9264 || UI.getUse().getResNo() != Addr.getResNo())
9267 // Check that the add is independent of the load. Otherwise, folding it
9268 // would create a cycle.
9269 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9271 // Also check that add is not used in the vector operand. This would also
9273 if (User->isPredecessorOf(Vector.getNode()))
9276 // If the increment is a constant, it must match the memory ref size.
9277 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9278 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9279 uint32_t IncVal = CInc->getZExtValue();
9280 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9281 if (IncVal != NumBytes)
9283 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9286 // Finally, check that the vector doesn't depend on the load.
9287 // Again, this would create a cycle.
9288 // The load depending on the vector is fine, as that's the case for the
9289 // LD1*post we'll eventually generate anyway.
9290 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9293 SmallVector<SDValue, 8> Ops;
9294 Ops.push_back(LD->getOperand(0)); // Chain
9296 Ops.push_back(Vector); // The vector to be inserted
9297 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9299 Ops.push_back(Addr);
9302 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9303 SDVTList SDTys = DAG.getVTList(Tys);
9304 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9305 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9307 LoadSDN->getMemOperand());
9310 SDValue NewResults[] = {
9311 SDValue(LD, 0), // The result of load
9312 SDValue(UpdN.getNode(), 2) // Chain
9314 DCI.CombineTo(LD, NewResults);
9315 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9316 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9323 /// Simplify \Addr given that the top byte of it is ignored by HW during
9324 /// address translation.
9325 static bool performTBISimplification(SDValue Addr,
9326 TargetLowering::DAGCombinerInfo &DCI,
9327 SelectionDAG &DAG) {
9328 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9329 APInt KnownZero, KnownOne;
9330 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9331 DCI.isBeforeLegalizeOps());
9332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9333 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9334 DCI.CommitTargetLoweringOpt(TLO);
9340 static SDValue performSTORECombine(SDNode *N,
9341 TargetLowering::DAGCombinerInfo &DCI,
9343 const AArch64Subtarget *Subtarget) {
9344 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9347 if (Subtarget->supportsAddressTopByteIgnored() &&
9348 performTBISimplification(N->getOperand(2), DCI, DAG))
9349 return SDValue(N, 0);
9354 /// This function handles the log2-shuffle pattern produced by the
9355 /// LoopVectorizer for the across vector reduction. It consists of
9356 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9357 /// are reduced, where s is an induction variable from 0 to
9358 /// log2(NumVectorElements).
9359 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9361 SelectionDAG &DAG) {
9362 EVT VTy = OpV->getOperand(0).getValueType();
9363 if (!VTy.isVector())
9366 int NumVecElts = VTy.getVectorNumElements();
9367 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9368 if (NumVecElts != 4)
9371 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9375 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
9376 SDValue PreOp = OpV;
9377 // Iterate over each step of the across vector reduction.
9378 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
9379 SDValue CurOp = PreOp.getOperand(0);
9380 SDValue Shuffle = PreOp.getOperand(1);
9381 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
9382 // Try to swap the 1st and 2nd operand as add and min/max instructions
9384 CurOp = PreOp.getOperand(1);
9385 Shuffle = PreOp.getOperand(0);
9386 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9390 // Check if the input vector is fed by the operator we want to handle,
9391 // except the last step; the very first input vector is not necessarily
9392 // the same operator we are handling.
9393 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9396 // Check if it forms one step of the across vector reduction.
9398 // %cur = add %1, %0
9399 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9400 // %pre = add %cur, %shuffle
9401 if (Shuffle.getOperand(0) != CurOp)
9404 int NumMaskElts = 1 << CurStep;
9405 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9406 // Check mask values in each step.
9407 // We expect the shuffle mask in each step follows a specific pattern
9408 // denoted here by the <M, U> form, where M is a sequence of integers
9409 // starting from NumMaskElts, increasing by 1, and the number integers
9410 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9411 // of undef in U should be NumVecElts - NumMaskElts.
9412 // E.g., for <8 x i16>, mask values in each step should be :
9413 // step 0 : <1,u,u,u,u,u,u,u>
9414 // step 1 : <2,3,u,u,u,u,u,u>
9415 // step 2 : <4,5,6,7,u,u,u,u>
9416 for (int i = 0; i < NumVecElts; ++i)
9417 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9418 (i >= NumMaskElts && !(Mask[i] < 0)))
9424 bool IsIntrinsic = false;
9428 llvm_unreachable("Unexpected operator for across vector reduction");
9430 Opcode = AArch64ISD::UADDV;
9433 Opcode = AArch64ISD::SMAXV;
9436 Opcode = AArch64ISD::UMAXV;
9439 Opcode = AArch64ISD::SMINV;
9442 Opcode = AArch64ISD::UMINV;
9445 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9449 Opcode = Intrinsic::aarch64_neon_fminnmv;
9456 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9457 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9459 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9460 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9461 DAG.getConstant(0, DL, MVT::i64));
9464 /// Target-specific DAG combine for the across vector min/max reductions.
9465 /// This function specifically handles the final clean-up step of the vector
9466 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9467 /// pattern, which narrows down and finds the final min/max value from all
9468 /// elements of the vector.
9469 /// For example, for a <16 x i8> vector :
9470 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9471 /// %smax0 = smax %arr, svn0
9472 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9473 /// %smax1 = smax %smax0, %svn1
9474 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9475 /// %smax2 = smax %smax1, svn2
9476 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9477 /// %sc = setcc %smax2, %svn3, gt
9478 /// %n0 = extract_vector_elt %sc, #0
9479 /// %n1 = extract_vector_elt %smax2, #0
9480 /// %n2 = extract_vector_elt $smax2, #1
9481 /// %result = select %n0, %n1, n2
9484 /// %result = extract_vector_elt %1, 0
9486 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9487 const AArch64Subtarget *Subtarget) {
9488 if (!Subtarget->hasNEON())
9491 SDValue N0 = N->getOperand(0);
9492 SDValue IfTrue = N->getOperand(1);
9493 SDValue IfFalse = N->getOperand(2);
9495 // Check if the SELECT merges up the final result of the min/max
9497 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9498 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9499 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9502 // Expect N0 is fed by SETCC.
9503 SDValue SetCC = N0.getOperand(0);
9504 EVT SetCCVT = SetCC.getValueType();
9505 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9506 SetCCVT.getVectorElementType() != MVT::i1)
9509 SDValue VectorOp = SetCC.getOperand(0);
9510 unsigned Op = VectorOp->getOpcode();
9511 // Check if the input vector is fed by the operator we want to handle.
9512 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9513 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9516 EVT VTy = VectorOp.getValueType();
9517 if (!VTy.isVector())
9520 if (VTy.getSizeInBits() < 64)
9523 EVT EltTy = VTy.getVectorElementType();
9524 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9525 if (EltTy != MVT::f32)
9528 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9532 // Check if extracting from the same vector.
9534 // %sc = setcc %vector, %svn1, gt
9535 // %n0 = extract_vector_elt %sc, #0
9536 // %n1 = extract_vector_elt %vector, #0
9537 // %n2 = extract_vector_elt $vector, #1
9538 if (!(VectorOp == IfTrue->getOperand(0) &&
9539 VectorOp == IfFalse->getOperand(0)))
9542 // Check if the condition code is matched with the operator type.
9543 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9544 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9545 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9546 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9547 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9548 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9549 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9550 CC != ISD::SETGE) ||
9551 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9552 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9556 // Expect to check only lane 0 from the vector SETCC.
9557 if (!isNullConstant(N0.getOperand(1)))
9560 // Expect to extract the true value from lane 0.
9561 if (!isNullConstant(IfTrue.getOperand(1)))
9564 // Expect to extract the false value from lane 1.
9565 if (!isOneConstant(IfFalse.getOperand(1)))
9568 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9571 /// Target-specific DAG combine for the across vector add reduction.
9572 /// This function specifically handles the final clean-up step of the vector
9573 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9574 /// pattern, which adds all elements of a vector together.
9575 /// For example, for a <4 x i32> vector :
9576 /// %1 = vector_shuffle %0, <2,3,u,u>
9578 /// %3 = vector_shuffle %2, <1,u,u,u>
9580 /// %result = extract_vector_elt %4, 0
9583 /// %result = extract_vector_elt %0, 0
9585 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9586 const AArch64Subtarget *Subtarget) {
9587 if (!Subtarget->hasNEON())
9589 SDValue N0 = N->getOperand(0);
9590 SDValue N1 = N->getOperand(1);
9592 // Check if the input vector is fed by the ADD.
9593 if (N0->getOpcode() != ISD::ADD)
9596 // The vector extract idx must constant zero because we only expect the final
9597 // result of the reduction is placed in lane 0.
9598 if (!isNullConstant(N1))
9601 EVT VTy = N0.getValueType();
9602 if (!VTy.isVector())
9605 EVT EltTy = VTy.getVectorElementType();
9606 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9609 if (VTy.getSizeInBits() < 64)
9612 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9615 /// Target-specific DAG combine function for NEON load/store intrinsics
9616 /// to merge base address updates.
9617 static SDValue performNEONPostLDSTCombine(SDNode *N,
9618 TargetLowering::DAGCombinerInfo &DCI,
9619 SelectionDAG &DAG) {
9620 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9623 unsigned AddrOpIdx = N->getNumOperands() - 1;
9624 SDValue Addr = N->getOperand(AddrOpIdx);
9626 // Search for a use of the address operand that is an increment.
9627 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9628 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9630 if (User->getOpcode() != ISD::ADD ||
9631 UI.getUse().getResNo() != Addr.getResNo())
9634 // Check that the add is independent of the load/store. Otherwise, folding
9635 // it would create a cycle.
9636 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9639 // Find the new opcode for the updating load/store.
9640 bool IsStore = false;
9641 bool IsLaneOp = false;
9642 bool IsDupOp = false;
9643 unsigned NewOpc = 0;
9644 unsigned NumVecs = 0;
9645 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9647 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9648 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9650 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9652 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9654 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9655 NumVecs = 2; IsStore = true; break;
9656 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9657 NumVecs = 3; IsStore = true; break;
9658 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9659 NumVecs = 4; IsStore = true; break;
9660 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9662 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9664 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9666 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9667 NumVecs = 2; IsStore = true; break;
9668 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9669 NumVecs = 3; IsStore = true; break;
9670 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9671 NumVecs = 4; IsStore = true; break;
9672 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9673 NumVecs = 2; IsDupOp = true; break;
9674 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9675 NumVecs = 3; IsDupOp = true; break;
9676 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9677 NumVecs = 4; IsDupOp = true; break;
9678 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9679 NumVecs = 2; IsLaneOp = true; break;
9680 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9681 NumVecs = 3; IsLaneOp = true; break;
9682 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9683 NumVecs = 4; IsLaneOp = true; break;
9684 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9685 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9686 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9687 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9688 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9689 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9694 VecTy = N->getOperand(2).getValueType();
9696 VecTy = N->getValueType(0);
9698 // If the increment is a constant, it must match the memory ref size.
9699 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9700 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9701 uint32_t IncVal = CInc->getZExtValue();
9702 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9703 if (IsLaneOp || IsDupOp)
9704 NumBytes /= VecTy.getVectorNumElements();
9705 if (IncVal != NumBytes)
9707 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9709 SmallVector<SDValue, 8> Ops;
9710 Ops.push_back(N->getOperand(0)); // Incoming chain
9711 // Load lane and store have vector list as input.
9712 if (IsLaneOp || IsStore)
9713 for (unsigned i = 2; i < AddrOpIdx; ++i)
9714 Ops.push_back(N->getOperand(i));
9715 Ops.push_back(Addr); // Base register
9720 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9722 for (n = 0; n < NumResultVecs; ++n)
9724 Tys[n++] = MVT::i64; // Type of write back register
9725 Tys[n] = MVT::Other; // Type of the chain
9726 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9728 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9729 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9730 MemInt->getMemoryVT(),
9731 MemInt->getMemOperand());
9734 std::vector<SDValue> NewResults;
9735 for (unsigned i = 0; i < NumResultVecs; ++i) {
9736 NewResults.push_back(SDValue(UpdN.getNode(), i));
9738 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9739 DCI.CombineTo(N, NewResults);
9740 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9747 // Checks to see if the value is the prescribed width and returns information
9748 // about its extension mode.
9750 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9751 ExtType = ISD::NON_EXTLOAD;
9752 switch(V.getNode()->getOpcode()) {
9756 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9757 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9758 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9759 ExtType = LoadNode->getExtensionType();
9764 case ISD::AssertSext: {
9765 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9766 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9767 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9768 ExtType = ISD::SEXTLOAD;
9773 case ISD::AssertZext: {
9774 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9775 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9776 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9777 ExtType = ISD::ZEXTLOAD;
9783 case ISD::TargetConstant: {
9784 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9792 // This function does a whole lot of voodoo to determine if the tests are
9793 // equivalent without and with a mask. Essentially what happens is that given a
9796 // +-------------+ +-------------+ +-------------+ +-------------+
9797 // | Input | | AddConstant | | CompConstant| | CC |
9798 // +-------------+ +-------------+ +-------------+ +-------------+
9800 // V V | +----------+
9801 // +-------------+ +----+ | |
9802 // | ADD | |0xff| | |
9803 // +-------------+ +----+ | |
9806 // +-------------+ | |
9808 // +-------------+ | |
9817 // The AND node may be safely removed for some combinations of inputs. In
9818 // particular we need to take into account the extension type of the Input,
9819 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9820 // width of the input (this can work for any width inputs, the above graph is
9821 // specific to 8 bits.
9823 // The specific equations were worked out by generating output tables for each
9824 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9825 // problem was simplified by working with 4 bit inputs, which means we only
9826 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9827 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9828 // patterns present in both extensions (0,7). For every distinct set of
9829 // AddConstant and CompConstants bit patterns we can consider the masked and
9830 // unmasked versions to be equivalent if the result of this function is true for
9831 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9834 // and w10, w8, #0x0f
9836 // cset w9, AArch64CC
9838 // cset w11, AArch64CC
9843 // Since the above function shows when the outputs are equivalent it defines
9844 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9845 // would be expensive to run during compiles. The equations below were written
9846 // in a test harness that confirmed they gave equivalent outputs to the above
9847 // for all inputs function, so they can be used determine if the removal is
9850 // isEquivalentMaskless() is the code for testing if the AND can be removed
9851 // factored out of the DAG recognition as the DAG can take several forms.
9853 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9854 ISD::LoadExtType ExtType, int AddConstant,
9856 // By being careful about our equations and only writing the in term
9857 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9858 // make them generally applicable to all bit widths.
9859 int MaxUInt = (1 << width);
9861 // For the purposes of these comparisons sign extending the type is
9862 // equivalent to zero extending the add and displacing it by half the integer
9863 // width. Provided we are careful and make sure our equations are valid over
9864 // the whole range we can just adjust the input and avoid writing equations
9865 // for sign extended inputs.
9866 if (ExtType == ISD::SEXTLOAD)
9867 AddConstant -= (1 << (width-1));
9872 if ((AddConstant == 0) ||
9873 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9874 (AddConstant >= 0 && CompConstant < 0) ||
9875 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9880 if ((AddConstant == 0) ||
9881 (AddConstant >= 0 && CompConstant <= 0) ||
9882 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9887 if ((AddConstant >= 0 && CompConstant < 0) ||
9888 (AddConstant <= 0 && CompConstant >= -1 &&
9889 CompConstant < AddConstant + MaxUInt))
9894 if ((AddConstant == 0) ||
9895 (AddConstant > 0 && CompConstant <= 0) ||
9896 (AddConstant < 0 && CompConstant <= AddConstant))
9901 if ((AddConstant >= 0 && CompConstant <= 0) ||
9902 (AddConstant <= 0 && CompConstant >= 0 &&
9903 CompConstant <= AddConstant + MaxUInt))
9908 if ((AddConstant > 0 && CompConstant < 0) ||
9909 (AddConstant < 0 && CompConstant >= 0 &&
9910 CompConstant < AddConstant + MaxUInt) ||
9911 (AddConstant >= 0 && CompConstant >= 0 &&
9912 CompConstant >= AddConstant) ||
9913 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9921 case AArch64CC::Invalid:
9929 SDValue performCONDCombine(SDNode *N,
9930 TargetLowering::DAGCombinerInfo &DCI,
9931 SelectionDAG &DAG, unsigned CCIndex,
9932 unsigned CmpIndex) {
9933 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9934 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9935 unsigned CondOpcode = SubsNode->getOpcode();
9937 if (CondOpcode != AArch64ISD::SUBS)
9940 // There is a SUBS feeding this condition. Is it fed by a mask we can
9943 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9944 unsigned MaskBits = 0;
9946 if (AndNode->getOpcode() != ISD::AND)
9949 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9950 uint32_t CNV = CN->getZExtValue();
9953 else if (CNV == 65535)
9960 SDValue AddValue = AndNode->getOperand(0);
9962 if (AddValue.getOpcode() != ISD::ADD)
9965 // The basic dag structure is correct, grab the inputs and validate them.
9967 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9968 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9969 SDValue SubsInputValue = SubsNode->getOperand(1);
9971 // The mask is present and the provenance of all the values is a smaller type,
9972 // lets see if the mask is superfluous.
9974 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9975 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9978 ISD::LoadExtType ExtType;
9980 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9981 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9982 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9985 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9986 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9987 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9990 // The AND is not necessary, remove it.
9992 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9993 SubsNode->getValueType(1));
9994 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9996 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9997 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9999 return SDValue(N, 0);
10002 // Optimize compare with zero and branch.
10003 static SDValue performBRCONDCombine(SDNode *N,
10004 TargetLowering::DAGCombinerInfo &DCI,
10005 SelectionDAG &DAG) {
10006 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10008 SDValue Chain = N->getOperand(0);
10009 SDValue Dest = N->getOperand(1);
10010 SDValue CCVal = N->getOperand(2);
10011 SDValue Cmp = N->getOperand(3);
10013 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10014 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10015 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10018 unsigned CmpOpc = Cmp.getOpcode();
10019 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10022 // Only attempt folding if there is only one use of the flag and no use of the
10024 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10027 SDValue LHS = Cmp.getOperand(0);
10028 SDValue RHS = Cmp.getOperand(1);
10030 assert(LHS.getValueType() == RHS.getValueType() &&
10031 "Expected the value type to be the same for both operands!");
10032 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10035 if (isNullConstant(LHS))
10036 std::swap(LHS, RHS);
10038 if (!isNullConstant(RHS))
10041 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10042 LHS.getOpcode() == ISD::SRL)
10045 // Fold the compare into the branch instruction.
10047 if (CC == AArch64CC::EQ)
10048 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10050 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10052 // Do not add new nodes to DAG combiner worklist.
10053 DCI.CombineTo(N, BR, false);
10058 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10059 // as well as whether the test should be inverted. This code is required to
10060 // catch these cases (as opposed to standard dag combines) because
10061 // AArch64ISD::TBZ is matched during legalization.
10062 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10063 SelectionDAG &DAG) {
10065 if (!Op->hasOneUse())
10068 // We don't handle undef/constant-fold cases below, as they should have
10069 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10072 // (tbz (trunc x), b) -> (tbz x, b)
10073 // This case is just here to enable more of the below cases to be caught.
10074 if (Op->getOpcode() == ISD::TRUNCATE &&
10075 Bit < Op->getValueType(0).getSizeInBits()) {
10076 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10079 if (Op->getNumOperands() != 2)
10082 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10086 switch (Op->getOpcode()) {
10090 // (tbz (and x, m), b) -> (tbz x, b)
10092 if ((C->getZExtValue() >> Bit) & 1)
10093 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10096 // (tbz (shl x, c), b) -> (tbz x, b-c)
10098 if (C->getZExtValue() <= Bit &&
10099 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10100 Bit = Bit - C->getZExtValue();
10101 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10105 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10107 Bit = Bit + C->getZExtValue();
10108 if (Bit >= Op->getValueType(0).getSizeInBits())
10109 Bit = Op->getValueType(0).getSizeInBits() - 1;
10110 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10112 // (tbz (srl x, c), b) -> (tbz x, b+c)
10114 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10115 Bit = Bit + C->getZExtValue();
10116 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10120 // (tbz (xor x, -1), b) -> (tbnz x, b)
10122 if ((C->getZExtValue() >> Bit) & 1)
10124 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10128 // Optimize test single bit zero/non-zero and branch.
10129 static SDValue performTBZCombine(SDNode *N,
10130 TargetLowering::DAGCombinerInfo &DCI,
10131 SelectionDAG &DAG) {
10132 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10133 bool Invert = false;
10134 SDValue TestSrc = N->getOperand(1);
10135 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10137 if (TestSrc == NewTestSrc)
10140 unsigned NewOpc = N->getOpcode();
10142 if (NewOpc == AArch64ISD::TBZ)
10143 NewOpc = AArch64ISD::TBNZ;
10145 assert(NewOpc == AArch64ISD::TBNZ);
10146 NewOpc = AArch64ISD::TBZ;
10151 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10152 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10155 // vselect (v1i1 setcc) ->
10156 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
10157 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10158 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10160 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10161 SDValue N0 = N->getOperand(0);
10162 EVT CCVT = N0.getValueType();
10164 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10165 CCVT.getVectorElementType() != MVT::i1)
10168 EVT ResVT = N->getValueType(0);
10169 EVT CmpVT = N0.getOperand(0).getValueType();
10170 // Only combine when the result type is of the same size as the compared
10172 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10175 SDValue IfTrue = N->getOperand(1);
10176 SDValue IfFalse = N->getOperand(2);
10178 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10179 N0.getOperand(0), N0.getOperand(1),
10180 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10181 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10185 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10186 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10187 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10188 /// with a vector one followed by a DUP shuffle on the result.
10189 static SDValue performSelectCombine(SDNode *N,
10190 TargetLowering::DAGCombinerInfo &DCI) {
10191 SelectionDAG &DAG = DCI.DAG;
10192 SDValue N0 = N->getOperand(0);
10193 EVT ResVT = N->getValueType(0);
10195 if (N0.getOpcode() != ISD::SETCC)
10198 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10199 // scalar SetCCResultType. We also don't expect vectors, because we assume
10200 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10201 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10202 "Scalar-SETCC feeding SELECT has unexpected result type!");
10204 // If NumMaskElts == 0, the comparison is larger than select result. The
10205 // largest real NEON comparison is 64-bits per lane, which means the result is
10206 // at most 32-bits and an illegal vector. Just bail out for now.
10207 EVT SrcVT = N0.getOperand(0).getValueType();
10209 // Don't try to do this optimization when the setcc itself has i1 operands.
10210 // There are no legal vectors of i1, so this would be pointless.
10211 if (SrcVT == MVT::i1)
10214 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10215 if (!ResVT.isVector() || NumMaskElts == 0)
10218 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10219 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10221 // Also bail out if the vector CCVT isn't the same size as ResVT.
10222 // This can happen if the SETCC operand size doesn't divide the ResVT size
10223 // (e.g., f64 vs v3f32).
10224 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10227 // Make sure we didn't create illegal types, if we're not supposed to.
10228 assert(DCI.isBeforeLegalize() ||
10229 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10231 // First perform a vector comparison, where lane 0 is the one we're interested
10235 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10237 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10238 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10240 // Now duplicate the comparison mask we want across all other lanes.
10241 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10242 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10243 Mask = DAG.getNode(ISD::BITCAST, DL,
10244 ResVT.changeVectorElementTypeToInteger(), Mask);
10246 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10249 /// Get rid of unnecessary NVCASTs (that don't change the type).
10250 static SDValue performNVCASTCombine(SDNode *N) {
10251 if (N->getValueType(0) == N->getOperand(0).getValueType())
10252 return N->getOperand(0);
10257 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10258 DAGCombinerInfo &DCI) const {
10259 SelectionDAG &DAG = DCI.DAG;
10260 switch (N->getOpcode()) {
10265 return performAddSubLongCombine(N, DCI, DAG);
10267 return performXorCombine(N, DAG, DCI, Subtarget);
10269 return performMulCombine(N, DAG, DCI, Subtarget);
10270 case ISD::SINT_TO_FP:
10271 case ISD::UINT_TO_FP:
10272 return performIntToFpCombine(N, DAG, Subtarget);
10273 case ISD::FP_TO_SINT:
10274 case ISD::FP_TO_UINT:
10275 return performFpToIntCombine(N, DAG, DCI, Subtarget);
10277 return performFDivCombine(N, DAG, DCI, Subtarget);
10279 return performORCombine(N, DCI, Subtarget);
10281 return performSRLCombine(N, DCI);
10282 case ISD::INTRINSIC_WO_CHAIN:
10283 return performIntrinsicCombine(N, DCI, Subtarget);
10284 case ISD::ANY_EXTEND:
10285 case ISD::ZERO_EXTEND:
10286 case ISD::SIGN_EXTEND:
10287 return performExtendCombine(N, DCI, DAG);
10289 return performBitcastCombine(N, DCI, DAG);
10290 case ISD::CONCAT_VECTORS:
10291 return performConcatVectorsCombine(N, DCI, DAG);
10292 case ISD::SELECT: {
10293 SDValue RV = performSelectCombine(N, DCI);
10295 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10299 return performVSelectCombine(N, DCI.DAG);
10301 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10302 return SDValue(N, 0);
10305 return performSTORECombine(N, DCI, DAG, Subtarget);
10306 case AArch64ISD::BRCOND:
10307 return performBRCONDCombine(N, DCI, DAG);
10308 case AArch64ISD::TBNZ:
10309 case AArch64ISD::TBZ:
10310 return performTBZCombine(N, DCI, DAG);
10311 case AArch64ISD::CSEL:
10312 return performCONDCombine(N, DCI, DAG, 2, 3);
10313 case AArch64ISD::DUP:
10314 return performPostLD1Combine(N, DCI, false);
10315 case AArch64ISD::NVCAST:
10316 return performNVCASTCombine(N);
10317 case ISD::INSERT_VECTOR_ELT:
10318 return performPostLD1Combine(N, DCI, true);
10319 case ISD::EXTRACT_VECTOR_ELT:
10320 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
10321 case ISD::INTRINSIC_VOID:
10322 case ISD::INTRINSIC_W_CHAIN:
10323 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10324 case Intrinsic::aarch64_neon_ld2:
10325 case Intrinsic::aarch64_neon_ld3:
10326 case Intrinsic::aarch64_neon_ld4:
10327 case Intrinsic::aarch64_neon_ld1x2:
10328 case Intrinsic::aarch64_neon_ld1x3:
10329 case Intrinsic::aarch64_neon_ld1x4:
10330 case Intrinsic::aarch64_neon_ld2lane:
10331 case Intrinsic::aarch64_neon_ld3lane:
10332 case Intrinsic::aarch64_neon_ld4lane:
10333 case Intrinsic::aarch64_neon_ld2r:
10334 case Intrinsic::aarch64_neon_ld3r:
10335 case Intrinsic::aarch64_neon_ld4r:
10336 case Intrinsic::aarch64_neon_st2:
10337 case Intrinsic::aarch64_neon_st3:
10338 case Intrinsic::aarch64_neon_st4:
10339 case Intrinsic::aarch64_neon_st1x2:
10340 case Intrinsic::aarch64_neon_st1x3:
10341 case Intrinsic::aarch64_neon_st1x4:
10342 case Intrinsic::aarch64_neon_st2lane:
10343 case Intrinsic::aarch64_neon_st3lane:
10344 case Intrinsic::aarch64_neon_st4lane:
10345 return performNEONPostLDSTCombine(N, DCI, DAG);
10353 // Check if the return value is used as only a return value, as otherwise
10354 // we can't perform a tail-call. In particular, we need to check for
10355 // target ISD nodes that are returns and any other "odd" constructs
10356 // that the generic analysis code won't necessarily catch.
10357 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10358 SDValue &Chain) const {
10359 if (N->getNumValues() != 1)
10361 if (!N->hasNUsesOfValue(1, 0))
10364 SDValue TCChain = Chain;
10365 SDNode *Copy = *N->use_begin();
10366 if (Copy->getOpcode() == ISD::CopyToReg) {
10367 // If the copy has a glue operand, we conservatively assume it isn't safe to
10368 // perform a tail call.
10369 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10372 TCChain = Copy->getOperand(0);
10373 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10376 bool HasRet = false;
10377 for (SDNode *Node : Copy->uses()) {
10378 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10390 // Return whether the an instruction can potentially be optimized to a tail
10391 // call. This will cause the optimizers to attempt to move, or duplicate,
10392 // return instructions to help enable tail call optimizations for this
10394 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10395 return CI->isTailCall();
10398 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10400 ISD::MemIndexedMode &AM,
10402 SelectionDAG &DAG) const {
10403 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10406 Base = Op->getOperand(0);
10407 // All of the indexed addressing mode instructions take a signed
10408 // 9 bit immediate offset.
10409 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10410 int64_t RHSC = RHS->getSExtValue();
10411 if (Op->getOpcode() == ISD::SUB)
10412 RHSC = -(uint64_t)RHSC;
10413 if (!isInt<9>(RHSC))
10415 IsInc = (Op->getOpcode() == ISD::ADD);
10416 Offset = Op->getOperand(1);
10422 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10424 ISD::MemIndexedMode &AM,
10425 SelectionDAG &DAG) const {
10428 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10429 VT = LD->getMemoryVT();
10430 Ptr = LD->getBasePtr();
10431 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10432 VT = ST->getMemoryVT();
10433 Ptr = ST->getBasePtr();
10438 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10440 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10444 bool AArch64TargetLowering::getPostIndexedAddressParts(
10445 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10446 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10449 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10450 VT = LD->getMemoryVT();
10451 Ptr = LD->getBasePtr();
10452 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10453 VT = ST->getMemoryVT();
10454 Ptr = ST->getBasePtr();
10459 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10461 // Post-indexing updates the base, so it's not a valid transform
10462 // if that's not the same as the load's pointer.
10465 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10469 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10470 SelectionDAG &DAG) {
10472 SDValue Op = N->getOperand(0);
10474 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10478 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10479 DAG.getUNDEF(MVT::i32), Op,
10480 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10482 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10483 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10486 static void ReplaceReductionResults(SDNode *N,
10487 SmallVectorImpl<SDValue> &Results,
10488 SelectionDAG &DAG, unsigned InterOp,
10489 unsigned AcrossOp) {
10493 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10494 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10495 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10496 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10497 Results.push_back(SplitVal);
10500 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10502 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10503 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10504 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10505 DAG.getConstant(64, DL, MVT::i64)));
10506 return std::make_pair(Lo, Hi);
10509 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10510 SmallVectorImpl<SDValue> & Results,
10511 SelectionDAG &DAG) {
10512 assert(N->getValueType(0) == MVT::i128 &&
10513 "AtomicCmpSwap on types less than 128 should be legal");
10514 auto Desired = splitInt128(N->getOperand(2), DAG);
10515 auto New = splitInt128(N->getOperand(3), DAG);
10516 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10517 New.first, New.second, N->getOperand(0)};
10518 SDNode *CmpSwap = DAG.getMachineNode(
10519 AArch64::CMP_SWAP_128, SDLoc(N),
10520 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10522 MachineFunction &MF = DAG.getMachineFunction();
10523 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10524 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10525 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10527 Results.push_back(SDValue(CmpSwap, 0));
10528 Results.push_back(SDValue(CmpSwap, 1));
10529 Results.push_back(SDValue(CmpSwap, 3));
10532 void AArch64TargetLowering::ReplaceNodeResults(
10533 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10534 switch (N->getOpcode()) {
10536 llvm_unreachable("Don't know how to custom expand this");
10538 ReplaceBITCASTResults(N, Results, DAG);
10540 case AArch64ISD::SADDV:
10541 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10543 case AArch64ISD::UADDV:
10544 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10546 case AArch64ISD::SMINV:
10547 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10549 case AArch64ISD::UMINV:
10550 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10552 case AArch64ISD::SMAXV:
10553 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10555 case AArch64ISD::UMAXV:
10556 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10558 case ISD::FP_TO_UINT:
10559 case ISD::FP_TO_SINT:
10560 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10561 // Let normal code take care of it by not adding anything to Results.
10563 case ISD::ATOMIC_CMP_SWAP:
10564 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10569 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10570 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10571 return TargetLowering::useLoadStackGuardNode();
10575 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10576 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10577 // reciprocal if there are three or more FDIVs.
10581 TargetLoweringBase::LegalizeTypeAction
10582 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10583 MVT SVT = VT.getSimpleVT();
10584 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10585 // v4i16, v2i32 instead of to promote.
10586 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10587 || SVT == MVT::v1f32)
10588 return TypeWidenVector;
10590 return TargetLoweringBase::getPreferredVectorAction(VT);
10593 // Loads and stores less than 128-bits are already atomic; ones above that
10594 // are doomed anyway, so defer to the default libcall and blame the OS when
10595 // things go wrong.
10596 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10597 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10598 return Size == 128;
10601 // Loads and stores less than 128-bits are already atomic; ones above that
10602 // are doomed anyway, so defer to the default libcall and blame the OS when
10603 // things go wrong.
10604 TargetLowering::AtomicExpansionKind
10605 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10606 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10607 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10610 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10611 TargetLowering::AtomicExpansionKind
10612 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10613 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10614 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10617 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10618 AtomicCmpXchgInst *AI) const {
10619 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10620 // implement cmpxchg without spilling. If the address being exchanged is also
10621 // on the stack and close enough to the spill slot, this can lead to a
10622 // situation where the monitor always gets cleared and the atomic operation
10623 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10624 return getTargetMachine().getOptLevel() != 0;
10627 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10628 AtomicOrdering Ord) const {
10629 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10630 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10631 bool IsAcquire = isAcquireOrStronger(Ord);
10633 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10634 // intrinsic must return {i64, i64} and we have to recombine them into a
10635 // single i128 here.
10636 if (ValTy->getPrimitiveSizeInBits() == 128) {
10637 Intrinsic::ID Int =
10638 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10639 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10641 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10642 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10644 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10645 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10646 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10647 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10648 return Builder.CreateOr(
10649 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10652 Type *Tys[] = { Addr->getType() };
10653 Intrinsic::ID Int =
10654 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10655 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10657 return Builder.CreateTruncOrBitCast(
10658 Builder.CreateCall(Ldxr, Addr),
10659 cast<PointerType>(Addr->getType())->getElementType());
10662 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10663 IRBuilder<> &Builder) const {
10664 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10665 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10668 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10669 Value *Val, Value *Addr,
10670 AtomicOrdering Ord) const {
10671 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10672 bool IsRelease = isReleaseOrStronger(Ord);
10674 // Since the intrinsics must have legal type, the i128 intrinsics take two
10675 // parameters: "i64, i64". We must marshal Val into the appropriate form
10676 // before the call.
10677 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10678 Intrinsic::ID Int =
10679 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10680 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10681 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10683 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10684 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10685 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10686 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10689 Intrinsic::ID Int =
10690 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10691 Type *Tys[] = { Addr->getType() };
10692 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10694 return Builder.CreateCall(Stxr,
10695 {Builder.CreateZExtOrBitCast(
10696 Val, Stxr->getFunctionType()->getParamType(0)),
10700 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10701 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10702 return Ty->isArrayTy();
10705 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10710 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
10711 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10712 Function *ThreadPointerFunc =
10713 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10714 return IRB.CreatePointerCast(
10715 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
10716 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10719 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10720 // Android provides a fixed TLS slot for the stack cookie. See the definition
10721 // of TLS_SLOT_STACK_GUARD in
10722 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10723 if (Subtarget->isTargetAndroid())
10724 return UseTlsOffset(IRB, 0x28);
10726 // Fuchsia is similar.
10727 // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10728 if (Subtarget->isTargetFuchsia())
10729 return UseTlsOffset(IRB, -0x10);
10731 return TargetLowering::getIRStackGuard(IRB);
10734 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10735 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10736 // definition of TLS_SLOT_SAFESTACK in
10737 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10738 if (Subtarget->isTargetAndroid())
10739 return UseTlsOffset(IRB, 0x48);
10741 // Fuchsia is similar.
10742 // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10743 if (Subtarget->isTargetFuchsia())
10744 return UseTlsOffset(IRB, -0x8);
10746 return TargetLowering::getSafeStackPointerLocation(IRB);
10749 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10750 const Instruction &AndI) const {
10751 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10752 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10753 // may be beneficial to sink in other cases, but we would have to check that
10754 // the cmp would not get folded into the br to form a cbz for these to be
10756 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10759 return Mask->getUniqueInteger().isPowerOf2();
10762 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10763 // Update IsSplitCSR in AArch64unctionInfo.
10764 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10765 AFI->setIsSplitCSR(true);
10768 void AArch64TargetLowering::insertCopiesSplitCSR(
10769 MachineBasicBlock *Entry,
10770 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10771 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10772 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10776 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10777 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10778 MachineBasicBlock::iterator MBBI = Entry->begin();
10779 for (const MCPhysReg *I = IStart; *I; ++I) {
10780 const TargetRegisterClass *RC = nullptr;
10781 if (AArch64::GPR64RegClass.contains(*I))
10782 RC = &AArch64::GPR64RegClass;
10783 else if (AArch64::FPR64RegClass.contains(*I))
10784 RC = &AArch64::FPR64RegClass;
10786 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10788 unsigned NewVR = MRI->createVirtualRegister(RC);
10789 // Create copy from CSR to a virtual register.
10790 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10791 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10792 // nounwind. If we want to generalize this later, we may need to emit
10793 // CFI pseudo-instructions.
10794 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10795 Attribute::NoUnwind) &&
10796 "Function should be nounwind in insertCopiesSplitCSR!");
10797 Entry->addLiveIn(*I);
10798 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10801 // Insert the copy-back instructions right before the terminator.
10802 for (auto *Exit : Exits)
10803 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10804 TII->get(TargetOpcode::COPY), *I)
10809 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
10810 // Integer division on AArch64 is expensive. However, when aggressively
10811 // optimizing for code size, we prefer to use a div instruction, as it is
10812 // usually smaller than the alternative sequence.
10813 // The exception to this is vector division. Since AArch64 doesn't have vector
10814 // integer division, leaving the division as-is is a loss even in terms of
10815 // size, because it will have to be scalarized, while the alternative code
10816 // sequence can be performed in vector form.
10818 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
10819 return OptSize && !VT.isVector();
10823 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10824 if (Subtarget->isTargetDarwin())
10825 return getPointerTy(DL).getSizeInBits();
10827 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;