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/KnownBits.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetCallingConv.h"
74 #include "llvm/Target/TargetInstrInfo.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Target/TargetOptions.h"
91 #define DEBUG_TYPE "aarch64-lower"
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99 cl::desc("Allow AArch64 SLI/SRI formation"),
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106 "aarch64-elf-ldtls-generation", cl::Hidden,
107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112 cl::desc("Enable AArch64 logical imm instruction "
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120 const AArch64Subtarget &STI)
121 : TargetLowering(TM), Subtarget(&STI) {
122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123 // we have to make something up. Arbitrarily, choose ZeroOrOne.
124 setBooleanContents(ZeroOrOneBooleanContent);
125 // When comparing vectors the result sets the different elements in the
126 // vector to all-one or all-zero.
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
129 // Set up the register classes.
130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
133 if (Subtarget->hasFPARMv8()) {
134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
140 if (Subtarget->hasNEON()) {
141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143 // Someone set us up the NEON.
144 addDRTypeForNEON(MVT::v2f32);
145 addDRTypeForNEON(MVT::v8i8);
146 addDRTypeForNEON(MVT::v4i16);
147 addDRTypeForNEON(MVT::v2i32);
148 addDRTypeForNEON(MVT::v1i64);
149 addDRTypeForNEON(MVT::v1f64);
150 addDRTypeForNEON(MVT::v4f16);
152 addQRTypeForNEON(MVT::v4f32);
153 addQRTypeForNEON(MVT::v2f64);
154 addQRTypeForNEON(MVT::v16i8);
155 addQRTypeForNEON(MVT::v8i16);
156 addQRTypeForNEON(MVT::v4i32);
157 addQRTypeForNEON(MVT::v2i64);
158 addQRTypeForNEON(MVT::v8f16);
161 // Compute derived properties from the register classes
162 computeRegisterProperties(Subtarget->getRegisterInfo());
164 // Provide all sorts of operation actions
165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167 setOperationAction(ISD::SETCC, MVT::i32, Custom);
168 setOperationAction(ISD::SETCC, MVT::i64, Custom);
169 setOperationAction(ISD::SETCC, MVT::f32, Custom);
170 setOperationAction(ISD::SETCC, MVT::f64, Custom);
171 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
172 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
173 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
174 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
175 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
176 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
177 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
178 setOperationAction(ISD::SELECT, MVT::i32, Custom);
179 setOperationAction(ISD::SELECT, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::f32, Custom);
181 setOperationAction(ISD::SELECT, MVT::f64, Custom);
182 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
183 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
184 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
186 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
189 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
190 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
191 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
193 setOperationAction(ISD::FREM, MVT::f32, Expand);
194 setOperationAction(ISD::FREM, MVT::f64, Expand);
195 setOperationAction(ISD::FREM, MVT::f80, Expand);
197 // Custom lowering hooks are needed for XOR
198 // to fold it into CSINC/CSINV.
199 setOperationAction(ISD::XOR, MVT::i32, Custom);
200 setOperationAction(ISD::XOR, MVT::i64, Custom);
202 // Virtually no operation on f128 is legal, but LLVM can't expand them when
203 // there's a valid register class, so we need custom operations in most cases.
204 setOperationAction(ISD::FABS, MVT::f128, Expand);
205 setOperationAction(ISD::FADD, MVT::f128, Custom);
206 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
207 setOperationAction(ISD::FCOS, MVT::f128, Expand);
208 setOperationAction(ISD::FDIV, MVT::f128, Custom);
209 setOperationAction(ISD::FMA, MVT::f128, Expand);
210 setOperationAction(ISD::FMUL, MVT::f128, Custom);
211 setOperationAction(ISD::FNEG, MVT::f128, Expand);
212 setOperationAction(ISD::FPOW, MVT::f128, Expand);
213 setOperationAction(ISD::FREM, MVT::f128, Expand);
214 setOperationAction(ISD::FRINT, MVT::f128, Expand);
215 setOperationAction(ISD::FSIN, MVT::f128, Expand);
216 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
217 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
218 setOperationAction(ISD::FSUB, MVT::f128, Custom);
219 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
220 setOperationAction(ISD::SETCC, MVT::f128, Custom);
221 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
222 setOperationAction(ISD::SELECT, MVT::f128, Custom);
223 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
224 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
226 // Lowering for many of the conversions is actually specified by the non-f128
227 // type. The LowerXXX function will be trivial when f128 isn't involved.
228 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
229 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
230 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
231 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
232 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
233 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
234 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
235 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
236 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
237 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
238 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
239 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
240 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
241 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
243 // Variable arguments.
244 setOperationAction(ISD::VASTART, MVT::Other, Custom);
245 setOperationAction(ISD::VAARG, MVT::Other, Custom);
246 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
247 setOperationAction(ISD::VAEND, MVT::Other, Expand);
249 // Variable-sized objects.
250 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
251 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
252 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
254 // Constant pool entries
255 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
258 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
260 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
261 setOperationAction(ISD::ADDC, MVT::i32, Custom);
262 setOperationAction(ISD::ADDE, MVT::i32, Custom);
263 setOperationAction(ISD::SUBC, MVT::i32, Custom);
264 setOperationAction(ISD::SUBE, MVT::i32, Custom);
265 setOperationAction(ISD::ADDC, MVT::i64, Custom);
266 setOperationAction(ISD::ADDE, MVT::i64, Custom);
267 setOperationAction(ISD::SUBC, MVT::i64, Custom);
268 setOperationAction(ISD::SUBE, MVT::i64, Custom);
270 // AArch64 lacks both left-rotate and popcount instructions.
271 setOperationAction(ISD::ROTL, MVT::i32, Expand);
272 setOperationAction(ISD::ROTL, MVT::i64, Expand);
273 for (MVT VT : MVT::vector_valuetypes()) {
274 setOperationAction(ISD::ROTL, VT, Expand);
275 setOperationAction(ISD::ROTR, VT, Expand);
278 // AArch64 doesn't have {U|S}MUL_LOHI.
279 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
280 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
282 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
283 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
285 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
287 for (MVT VT : MVT::vector_valuetypes()) {
288 setOperationAction(ISD::SDIVREM, VT, Expand);
289 setOperationAction(ISD::UDIVREM, VT, Expand);
291 setOperationAction(ISD::SREM, MVT::i32, Expand);
292 setOperationAction(ISD::SREM, MVT::i64, Expand);
293 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
294 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
295 setOperationAction(ISD::UREM, MVT::i32, Expand);
296 setOperationAction(ISD::UREM, MVT::i64, Expand);
298 // Custom lower Add/Sub/Mul with overflow.
299 setOperationAction(ISD::SADDO, MVT::i32, Custom);
300 setOperationAction(ISD::SADDO, MVT::i64, Custom);
301 setOperationAction(ISD::UADDO, MVT::i32, Custom);
302 setOperationAction(ISD::UADDO, MVT::i64, Custom);
303 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
304 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
305 setOperationAction(ISD::USUBO, MVT::i32, Custom);
306 setOperationAction(ISD::USUBO, MVT::i64, Custom);
307 setOperationAction(ISD::SMULO, MVT::i32, Custom);
308 setOperationAction(ISD::SMULO, MVT::i64, Custom);
309 setOperationAction(ISD::UMULO, MVT::i32, Custom);
310 setOperationAction(ISD::UMULO, MVT::i64, Custom);
312 setOperationAction(ISD::FSIN, MVT::f32, Expand);
313 setOperationAction(ISD::FSIN, MVT::f64, Expand);
314 setOperationAction(ISD::FCOS, MVT::f32, Expand);
315 setOperationAction(ISD::FCOS, MVT::f64, Expand);
316 setOperationAction(ISD::FPOW, MVT::f32, Expand);
317 setOperationAction(ISD::FPOW, MVT::f64, Expand);
318 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
319 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
321 // f16 is a storage-only type, always promote it to f32.
322 setOperationAction(ISD::SETCC, MVT::f16, Promote);
323 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
324 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
325 setOperationAction(ISD::SELECT, MVT::f16, Promote);
326 setOperationAction(ISD::FADD, MVT::f16, Promote);
327 setOperationAction(ISD::FSUB, MVT::f16, Promote);
328 setOperationAction(ISD::FMUL, MVT::f16, Promote);
329 setOperationAction(ISD::FDIV, MVT::f16, Promote);
330 setOperationAction(ISD::FREM, MVT::f16, Promote);
331 setOperationAction(ISD::FMA, MVT::f16, Promote);
332 setOperationAction(ISD::FNEG, MVT::f16, Promote);
333 setOperationAction(ISD::FABS, MVT::f16, Promote);
334 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
335 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
336 setOperationAction(ISD::FCOS, MVT::f16, Promote);
337 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
338 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
339 setOperationAction(ISD::FPOW, MVT::f16, Promote);
340 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
341 setOperationAction(ISD::FRINT, MVT::f16, Promote);
342 setOperationAction(ISD::FSIN, MVT::f16, Promote);
343 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
344 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
345 setOperationAction(ISD::FEXP, MVT::f16, Promote);
346 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
347 setOperationAction(ISD::FLOG, MVT::f16, Promote);
348 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
349 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
350 setOperationAction(ISD::FROUND, MVT::f16, Promote);
351 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
352 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
353 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
354 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
355 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
357 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
359 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
360 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
361 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
362 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
363 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
364 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
365 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
366 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
367 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
368 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
369 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
370 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
372 // Expand all other v4f16 operations.
373 // FIXME: We could generate better code by promoting some operations to
375 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
376 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
377 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
378 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
379 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
380 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
381 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
382 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
383 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
384 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
385 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
386 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
387 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
388 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
389 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
390 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
391 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
392 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
393 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
394 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
395 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
396 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
397 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
398 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
399 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
400 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
403 // v8f16 is also a storage-only type, so expand it.
404 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
405 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
406 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
407 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
408 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
409 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
410 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
411 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
412 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
413 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
414 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
415 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
416 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
417 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
418 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
419 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
420 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
421 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
422 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
423 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
424 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
425 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
426 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
427 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
428 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
429 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
430 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
431 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
432 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
433 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
434 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
436 // AArch64 has implementations of a lot of rounding-like FP operations.
437 for (MVT Ty : {MVT::f32, MVT::f64}) {
438 setOperationAction(ISD::FFLOOR, Ty, Legal);
439 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
440 setOperationAction(ISD::FCEIL, Ty, Legal);
441 setOperationAction(ISD::FRINT, Ty, Legal);
442 setOperationAction(ISD::FTRUNC, Ty, Legal);
443 setOperationAction(ISD::FROUND, Ty, Legal);
444 setOperationAction(ISD::FMINNUM, Ty, Legal);
445 setOperationAction(ISD::FMAXNUM, Ty, Legal);
446 setOperationAction(ISD::FMINNAN, Ty, Legal);
447 setOperationAction(ISD::FMAXNAN, Ty, Legal);
450 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
452 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
454 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
455 // This requires the Performance Monitors extension.
456 if (Subtarget->hasPerfMon())
457 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
459 if (Subtarget->isTargetMachO()) {
460 // For iOS, we don't want to the normal expansion of a libcall to
461 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
463 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
464 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
466 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
467 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
470 // Make floating-point constants legal for the large code model, so they don't
471 // become loads from the constant pool.
472 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
473 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
474 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
477 // AArch64 does not have floating-point extending loads, i1 sign-extending
478 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
479 for (MVT VT : MVT::fp_valuetypes()) {
480 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
481 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
482 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
483 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
485 for (MVT VT : MVT::integer_valuetypes())
486 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
488 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
489 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
490 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
491 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
492 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
493 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
494 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
496 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
497 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
499 // Indexed loads and stores are supported.
500 for (unsigned im = (unsigned)ISD::PRE_INC;
501 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
502 setIndexedLoadAction(im, MVT::i8, Legal);
503 setIndexedLoadAction(im, MVT::i16, Legal);
504 setIndexedLoadAction(im, MVT::i32, Legal);
505 setIndexedLoadAction(im, MVT::i64, Legal);
506 setIndexedLoadAction(im, MVT::f64, Legal);
507 setIndexedLoadAction(im, MVT::f32, Legal);
508 setIndexedLoadAction(im, MVT::f16, Legal);
509 setIndexedStoreAction(im, MVT::i8, Legal);
510 setIndexedStoreAction(im, MVT::i16, Legal);
511 setIndexedStoreAction(im, MVT::i32, Legal);
512 setIndexedStoreAction(im, MVT::i64, Legal);
513 setIndexedStoreAction(im, MVT::f64, Legal);
514 setIndexedStoreAction(im, MVT::f32, Legal);
515 setIndexedStoreAction(im, MVT::f16, Legal);
519 setOperationAction(ISD::TRAP, MVT::Other, Legal);
521 // We combine OR nodes for bitfield operations.
522 setTargetDAGCombine(ISD::OR);
524 // Vector add and sub nodes may conceal a high-half opportunity.
525 // Also, try to fold ADD into CSINC/CSINV..
526 setTargetDAGCombine(ISD::ADD);
527 setTargetDAGCombine(ISD::SUB);
528 setTargetDAGCombine(ISD::SRL);
529 setTargetDAGCombine(ISD::XOR);
530 setTargetDAGCombine(ISD::SINT_TO_FP);
531 setTargetDAGCombine(ISD::UINT_TO_FP);
533 setTargetDAGCombine(ISD::FP_TO_SINT);
534 setTargetDAGCombine(ISD::FP_TO_UINT);
535 setTargetDAGCombine(ISD::FDIV);
537 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
539 setTargetDAGCombine(ISD::ANY_EXTEND);
540 setTargetDAGCombine(ISD::ZERO_EXTEND);
541 setTargetDAGCombine(ISD::SIGN_EXTEND);
542 setTargetDAGCombine(ISD::BITCAST);
543 setTargetDAGCombine(ISD::CONCAT_VECTORS);
544 setTargetDAGCombine(ISD::STORE);
545 if (Subtarget->supportsAddressTopByteIgnored())
546 setTargetDAGCombine(ISD::LOAD);
548 setTargetDAGCombine(ISD::MUL);
550 setTargetDAGCombine(ISD::SELECT);
551 setTargetDAGCombine(ISD::VSELECT);
553 setTargetDAGCombine(ISD::INTRINSIC_VOID);
554 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
555 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
556 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
558 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
559 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
560 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
562 setStackPointerRegisterToSaveRestore(AArch64::SP);
564 setSchedulingPreference(Sched::Hybrid);
566 EnableExtLdPromotion = true;
568 // Set required alignment.
569 setMinFunctionAlignment(2);
570 // Set preferred alignments.
571 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
572 setPrefLoopAlignment(STI.getPrefLoopAlignment());
574 // Only change the limit for entries in a jump table if specified by
575 // the subtarget, but not at the command line.
576 unsigned MaxJT = STI.getMaximumJumpTableSize();
577 if (MaxJT && getMaximumJumpTableSize() == 0)
578 setMaximumJumpTableSize(MaxJT);
580 setHasExtractBitsInsn(true);
582 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
584 if (Subtarget->hasNEON()) {
585 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
586 // silliness like this:
587 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
588 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
589 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
590 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
591 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
592 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
593 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
594 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
595 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
596 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
597 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
598 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
599 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
600 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
601 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
602 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
603 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
604 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
605 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
606 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
607 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
608 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
609 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
610 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
611 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
613 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
614 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
615 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
616 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
617 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
619 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
621 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
622 // elements smaller than i32, so promote the input to i32 first.
623 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
624 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
625 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
626 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
627 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
628 // -> v8f16 conversions.
629 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
630 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
631 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
632 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
633 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
634 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
635 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
636 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
637 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
638 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
639 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
640 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
641 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
643 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
644 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
646 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
647 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
648 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
649 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
650 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
651 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
652 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
653 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
655 // AArch64 doesn't have MUL.2d:
656 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
657 // Custom handling for some quad-vector types to detect MULL.
658 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
659 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
660 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
662 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
663 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
664 // Likewise, narrowing and extending vector loads/stores aren't handled
666 for (MVT VT : MVT::vector_valuetypes()) {
667 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
669 setOperationAction(ISD::MULHS, VT, Expand);
670 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
671 setOperationAction(ISD::MULHU, VT, Expand);
672 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
674 setOperationAction(ISD::BSWAP, VT, Expand);
676 for (MVT InnerVT : MVT::vector_valuetypes()) {
677 setTruncStoreAction(VT, InnerVT, Expand);
678 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
679 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
680 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
684 // AArch64 has implementations of a lot of rounding-like FP operations.
685 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
686 setOperationAction(ISD::FFLOOR, Ty, Legal);
687 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
688 setOperationAction(ISD::FCEIL, Ty, Legal);
689 setOperationAction(ISD::FRINT, Ty, Legal);
690 setOperationAction(ISD::FTRUNC, Ty, Legal);
691 setOperationAction(ISD::FROUND, Ty, Legal);
695 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
698 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
699 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
700 setOperationAction(ISD::LOAD, VT, Promote);
701 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
703 setOperationAction(ISD::STORE, VT, Promote);
704 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
705 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
706 setOperationAction(ISD::LOAD, VT, Promote);
707 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
709 setOperationAction(ISD::STORE, VT, Promote);
710 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
713 // Mark vector float intrinsics as expand.
714 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
715 setOperationAction(ISD::FSIN, VT, Expand);
716 setOperationAction(ISD::FCOS, VT, Expand);
717 setOperationAction(ISD::FPOWI, VT, Expand);
718 setOperationAction(ISD::FPOW, VT, Expand);
719 setOperationAction(ISD::FLOG, VT, Expand);
720 setOperationAction(ISD::FLOG2, VT, Expand);
721 setOperationAction(ISD::FLOG10, VT, Expand);
722 setOperationAction(ISD::FEXP, VT, Expand);
723 setOperationAction(ISD::FEXP2, VT, Expand);
725 // But we do support custom-lowering for FCOPYSIGN.
726 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
729 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
730 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
731 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
732 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
733 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
734 setOperationAction(ISD::SRA, VT, Custom);
735 setOperationAction(ISD::SRL, VT, Custom);
736 setOperationAction(ISD::SHL, VT, Custom);
737 setOperationAction(ISD::AND, VT, Custom);
738 setOperationAction(ISD::OR, VT, Custom);
739 setOperationAction(ISD::SETCC, VT, Custom);
740 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
742 setOperationAction(ISD::SELECT, VT, Expand);
743 setOperationAction(ISD::SELECT_CC, VT, Expand);
744 setOperationAction(ISD::VSELECT, VT, Expand);
745 for (MVT InnerVT : MVT::all_valuetypes())
746 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748 // CNT supports only B element sizes.
749 if (VT != MVT::v8i8 && VT != MVT::v16i8)
750 setOperationAction(ISD::CTPOP, VT, Expand);
752 setOperationAction(ISD::UDIV, VT, Expand);
753 setOperationAction(ISD::SDIV, VT, Expand);
754 setOperationAction(ISD::UREM, VT, Expand);
755 setOperationAction(ISD::SREM, VT, Expand);
756 setOperationAction(ISD::FREM, VT, Expand);
758 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
759 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
761 if (!VT.isFloatingPoint())
762 setOperationAction(ISD::ABS, VT, Legal);
764 // [SU][MIN|MAX] are available for all NEON types apart from i64.
765 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
766 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
767 setOperationAction(Opcode, VT, Legal);
769 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
770 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
771 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
772 ISD::FMINNUM, ISD::FMAXNUM})
773 setOperationAction(Opcode, VT, Legal);
775 if (Subtarget->isLittleEndian()) {
776 for (unsigned im = (unsigned)ISD::PRE_INC;
777 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
778 setIndexedLoadAction(im, VT, Legal);
779 setIndexedStoreAction(im, VT, Legal);
784 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
785 addRegisterClass(VT, &AArch64::FPR64RegClass);
786 addTypeForNEON(VT, MVT::v2i32);
789 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
790 addRegisterClass(VT, &AArch64::FPR128RegClass);
791 addTypeForNEON(VT, MVT::v4i32);
794 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
798 return VT.changeVectorElementTypeToInteger();
801 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
802 const APInt &Demanded,
803 TargetLowering::TargetLoweringOpt &TLO,
805 uint64_t OldImm = Imm, NewImm, Enc;
806 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
808 // Return if the immediate is already all zeros, all ones, a bimm32 or a
810 if (Imm == 0 || Imm == Mask ||
811 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
814 unsigned EltSize = Size;
815 uint64_t DemandedBits = Demanded.getZExtValue();
817 // Clear bits that are not demanded.
821 // The goal here is to set the non-demanded bits in a way that minimizes
822 // the number of switching between 0 and 1. In order to achieve this goal,
823 // we set the non-demanded bits to the value of the preceding demanded bits.
824 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
825 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
826 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
827 // The final result is 0b11000011.
828 uint64_t NonDemandedBits = ~DemandedBits;
829 uint64_t InvertedImm = ~Imm & DemandedBits;
830 uint64_t RotatedImm =
831 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
833 uint64_t Sum = RotatedImm + NonDemandedBits;
834 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
835 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
836 NewImm = (Imm | Ones) & Mask;
838 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
839 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
840 // we halve the element size and continue the search.
841 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
844 // We cannot shrink the element size any further if it is 2-bits.
850 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
852 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
853 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
856 // Merge the upper and lower halves of Imm and DemandedBits.
858 DemandedBits |= DemandedBitsHi;
863 // Replicate the element across the register width.
864 while (EltSize < Size) {
865 NewImm |= NewImm << EltSize;
870 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
871 "demanded bits should never be altered");
872 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
874 // Create the new constant immediate node.
875 EVT VT = Op.getValueType();
878 // If the new constant immediate is all-zeros or all-ones, let the target
879 // independent DAG combine optimize this node.
880 if (NewImm == 0 || NewImm == OrigMask)
881 return TLO.CombineTo(Op.getOperand(1), TLO.DAG.getConstant(NewImm, DL, VT));
883 // Otherwise, create a machine node so that target independent DAG combine
884 // doesn't undo this optimization.
885 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
886 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
888 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
890 return TLO.CombineTo(Op, New);
893 bool AArch64TargetLowering::targetShrinkDemandedConstant(
894 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
895 // Delay this optimization to as late as possible.
899 if (!EnableOptimizeLogicalImm)
902 EVT VT = Op.getValueType();
906 unsigned Size = VT.getSizeInBits();
907 assert((Size == 32 || Size == 64) &&
908 "i32 or i64 is expected after legalization.");
910 // Exit early if we demand all bits.
911 if (Demanded.countPopulation() == Size)
915 switch (Op.getOpcode()) {
919 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
922 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
925 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
928 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
931 uint64_t Imm = C->getZExtValue();
932 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
935 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
936 /// Mask are known to be either zero or one and return them Known.
937 void AArch64TargetLowering::computeKnownBitsForTargetNode(
938 const SDValue Op, KnownBits &Known,
939 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
940 switch (Op.getOpcode()) {
943 case AArch64ISD::CSEL: {
945 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
946 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
947 Known.Zero &= Known2.Zero;
948 Known.One &= Known2.One;
951 case ISD::INTRINSIC_W_CHAIN: {
952 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
953 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
956 case Intrinsic::aarch64_ldaxr:
957 case Intrinsic::aarch64_ldxr: {
958 unsigned BitWidth = Known.getBitWidth();
959 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
960 unsigned MemBits = VT.getScalarSizeInBits();
961 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
967 case ISD::INTRINSIC_WO_CHAIN:
968 case ISD::INTRINSIC_VOID: {
969 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
973 case Intrinsic::aarch64_neon_umaxv:
974 case Intrinsic::aarch64_neon_uminv: {
975 // Figure out the datatype of the vector operand. The UMINV instruction
976 // will zero extend the result, so we can mark as known zero all the
977 // bits larger than the element datatype. 32-bit or larget doesn't need
978 // this as those are legal types and will be handled by isel directly.
979 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
980 unsigned BitWidth = Known.getBitWidth();
981 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
982 assert(BitWidth >= 8 && "Unexpected width!");
983 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
985 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
986 assert(BitWidth >= 16 && "Unexpected width!");
987 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
997 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1002 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1006 if (Subtarget->requiresStrictAlign())
1010 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1011 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1012 // See comments in performSTORECombine() for more details about
1013 // these conditions.
1015 // Code that uses clang vector extensions can mark that it
1016 // wants unaligned accesses to be treated as fast by
1017 // underspecifying alignment to be 1 or 2.
1020 // Disregard v2i64. Memcpy lowering produces those and splitting
1021 // them regresses performance on micro-benchmarks and olden/bh.
1028 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1029 const TargetLibraryInfo *libInfo) const {
1030 return AArch64::createFastISel(funcInfo, libInfo);
1033 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1034 switch ((AArch64ISD::NodeType)Opcode) {
1035 case AArch64ISD::FIRST_NUMBER: break;
1036 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1037 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1038 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1039 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1040 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1041 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1042 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1043 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1044 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1045 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1046 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1047 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1048 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1049 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1050 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1051 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1052 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1053 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1054 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1055 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1056 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1057 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1058 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1059 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1060 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1061 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1062 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1063 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1064 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1065 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1066 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1067 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1068 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1069 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1070 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1071 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1072 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1073 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1074 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1075 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1076 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1077 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1078 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1079 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1080 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1081 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1082 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1083 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1084 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1085 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1086 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1087 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1088 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1089 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1090 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1091 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1092 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1093 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1094 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1095 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1096 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1097 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1098 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1099 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1100 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1101 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1102 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1103 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1104 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1105 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1106 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1107 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1108 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1109 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1110 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1111 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1112 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1113 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1114 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1115 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1116 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1117 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1118 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1119 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1120 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1121 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1122 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1123 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1124 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1125 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1126 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1127 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1128 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1129 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1130 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1131 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1132 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1133 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1134 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1135 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1136 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1137 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1138 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1139 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1140 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1141 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1142 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1143 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1144 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1145 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1146 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1147 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1148 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1149 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1150 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1151 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1152 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1153 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1154 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1155 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1156 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1157 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1158 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1159 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1165 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1166 MachineBasicBlock *MBB) const {
1167 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1171 // [... previous instrs leading to comparison ...]
1177 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1179 MachineFunction *MF = MBB->getParent();
1180 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1181 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1182 DebugLoc DL = MI.getDebugLoc();
1183 MachineFunction::iterator It = ++MBB->getIterator();
1185 unsigned DestReg = MI.getOperand(0).getReg();
1186 unsigned IfTrueReg = MI.getOperand(1).getReg();
1187 unsigned IfFalseReg = MI.getOperand(2).getReg();
1188 unsigned CondCode = MI.getOperand(3).getImm();
1189 bool NZCVKilled = MI.getOperand(4).isKill();
1191 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1192 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1193 MF->insert(It, TrueBB);
1194 MF->insert(It, EndBB);
1196 // Transfer rest of current basic-block to EndBB
1197 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1199 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1201 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1202 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1203 MBB->addSuccessor(TrueBB);
1204 MBB->addSuccessor(EndBB);
1206 // TrueBB falls through to the end.
1207 TrueBB->addSuccessor(EndBB);
1210 TrueBB->addLiveIn(AArch64::NZCV);
1211 EndBB->addLiveIn(AArch64::NZCV);
1214 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1220 MI.eraseFromParent();
1224 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1225 MachineInstr &MI, MachineBasicBlock *BB) const {
1226 switch (MI.getOpcode()) {
1231 llvm_unreachable("Unexpected instruction for custom inserter!");
1233 case AArch64::F128CSEL:
1234 return EmitF128CSEL(MI, BB);
1236 case TargetOpcode::STACKMAP:
1237 case TargetOpcode::PATCHPOINT:
1238 return emitPatchPoint(MI, BB);
1242 //===----------------------------------------------------------------------===//
1243 // AArch64 Lowering private implementation.
1244 //===----------------------------------------------------------------------===//
1246 //===----------------------------------------------------------------------===//
1248 //===----------------------------------------------------------------------===//
1250 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1252 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1255 llvm_unreachable("Unknown condition code!");
1257 return AArch64CC::NE;
1259 return AArch64CC::EQ;
1261 return AArch64CC::GT;
1263 return AArch64CC::GE;
1265 return AArch64CC::LT;
1267 return AArch64CC::LE;
1269 return AArch64CC::HI;
1271 return AArch64CC::HS;
1273 return AArch64CC::LO;
1275 return AArch64CC::LS;
1279 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1280 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1281 AArch64CC::CondCode &CondCode,
1282 AArch64CC::CondCode &CondCode2) {
1283 CondCode2 = AArch64CC::AL;
1286 llvm_unreachable("Unknown FP condition!");
1289 CondCode = AArch64CC::EQ;
1293 CondCode = AArch64CC::GT;
1297 CondCode = AArch64CC::GE;
1300 CondCode = AArch64CC::MI;
1303 CondCode = AArch64CC::LS;
1306 CondCode = AArch64CC::MI;
1307 CondCode2 = AArch64CC::GT;
1310 CondCode = AArch64CC::VC;
1313 CondCode = AArch64CC::VS;
1316 CondCode = AArch64CC::EQ;
1317 CondCode2 = AArch64CC::VS;
1320 CondCode = AArch64CC::HI;
1323 CondCode = AArch64CC::PL;
1327 CondCode = AArch64CC::LT;
1331 CondCode = AArch64CC::LE;
1335 CondCode = AArch64CC::NE;
1340 /// Convert a DAG fp condition code to an AArch64 CC.
1341 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1342 /// should be AND'ed instead of OR'ed.
1343 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1344 AArch64CC::CondCode &CondCode,
1345 AArch64CC::CondCode &CondCode2) {
1346 CondCode2 = AArch64CC::AL;
1349 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1350 assert(CondCode2 == AArch64CC::AL);
1354 // == ((a olt b) || (a ogt b))
1355 // == ((a ord b) && (a une b))
1356 CondCode = AArch64CC::VC;
1357 CondCode2 = AArch64CC::NE;
1361 // == ((a uno b) || (a oeq b))
1362 // == ((a ule b) && (a uge b))
1363 CondCode = AArch64CC::PL;
1364 CondCode2 = AArch64CC::LE;
1369 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1370 /// CC usable with the vector instructions. Fewer operations are available
1371 /// without a real NZCV register, so we have to use less efficient combinations
1372 /// to get the same effect.
1373 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1374 AArch64CC::CondCode &CondCode,
1375 AArch64CC::CondCode &CondCode2,
1380 // Mostly the scalar mappings work fine.
1381 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1387 CondCode = AArch64CC::MI;
1388 CondCode2 = AArch64CC::GE;
1395 // All of the compare-mask comparisons are ordered, but we can switch
1396 // between the two by a double inversion. E.g. ULE == !OGT.
1398 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1403 static bool isLegalArithImmed(uint64_t C) {
1404 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1405 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1408 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1409 const SDLoc &dl, SelectionDAG &DAG) {
1410 EVT VT = LHS.getValueType();
1412 if (VT.isFloatingPoint()) {
1413 assert(VT != MVT::f128);
1414 if (VT == MVT::f16) {
1415 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1416 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1419 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1422 // The CMP instruction is just an alias for SUBS, and representing it as
1423 // SUBS means that it's possible to get CSE with subtract operations.
1424 // A later phase can perform the optimization of setting the destination
1425 // register to WZR/XZR if it ends up being unused.
1426 unsigned Opcode = AArch64ISD::SUBS;
1428 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1429 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1430 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1431 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1432 // can be set differently by this operation. It comes down to whether
1433 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1434 // everything is fine. If not then the optimization is wrong. Thus general
1435 // comparisons are only valid if op2 != 0.
1437 // So, finally, the only LLVM-native comparisons that don't mention C and V
1438 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1439 // the absence of information about op2.
1440 Opcode = AArch64ISD::ADDS;
1441 RHS = RHS.getOperand(1);
1442 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1443 !isUnsignedIntSetCC(CC)) {
1444 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1445 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1446 // of the signed comparisons.
1447 Opcode = AArch64ISD::ANDS;
1448 RHS = LHS.getOperand(1);
1449 LHS = LHS.getOperand(0);
1452 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1456 /// \defgroup AArch64CCMP CMP;CCMP matching
1458 /// These functions deal with the formation of CMP;CCMP;... sequences.
1459 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1460 /// a comparison. They set the NZCV flags to a predefined value if their
1461 /// predicate is false. This allows to express arbitrary conjunctions, for
1462 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1465 /// ccmp B, inv(CB), CA
1466 /// check for CB flags
1468 /// In general we can create code for arbitrary "... (and (and A B) C)"
1469 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1470 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1471 /// negation operations:
1472 /// We can negate the results of a single comparison by inverting the flags
1473 /// used when the predicate fails and inverting the flags tested in the next
1474 /// instruction; We can also negate the results of the whole previous
1475 /// conditional compare sequence by inverting the flags tested in the next
1476 /// instruction. However there is no way to negate the result of a partial
1479 /// Therefore on encountering an "or" expression we can negate the subtree on
1480 /// one side and have to be able to push the negate to the leafs of the subtree
1481 /// on the other side (see also the comments in code). As complete example:
1482 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1483 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1484 /// is transformed to
1485 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1486 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1487 /// and implemented as:
1489 /// ccmp D, inv(CD), CC
1490 /// ccmp A, CA, inv(CD)
1491 /// ccmp B, CB, inv(CA)
1492 /// check for CB flags
1493 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1494 /// by conditional compare sequences.
1497 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1498 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1499 ISD::CondCode CC, SDValue CCOp,
1500 AArch64CC::CondCode Predicate,
1501 AArch64CC::CondCode OutCC,
1502 const SDLoc &DL, SelectionDAG &DAG) {
1503 unsigned Opcode = 0;
1504 if (LHS.getValueType().isFloatingPoint()) {
1505 assert(LHS.getValueType() != MVT::f128);
1506 if (LHS.getValueType() == MVT::f16) {
1507 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1508 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1510 Opcode = AArch64ISD::FCCMP;
1511 } else if (RHS.getOpcode() == ISD::SUB) {
1512 SDValue SubOp0 = RHS.getOperand(0);
1513 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1514 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1515 Opcode = AArch64ISD::CCMN;
1516 RHS = RHS.getOperand(1);
1520 Opcode = AArch64ISD::CCMP;
1522 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1523 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1524 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1525 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1526 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1529 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1530 /// CanPushNegate is set to true if we can push a negate operation through
1531 /// the tree in a was that we are left with AND operations and negate operations
1532 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1533 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1534 /// brought into such a form.
1535 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1536 unsigned Depth = 0) {
1537 if (!Val.hasOneUse())
1539 unsigned Opcode = Val->getOpcode();
1540 if (Opcode == ISD::SETCC) {
1541 if (Val->getOperand(0).getValueType() == MVT::f128)
1546 // Protect against exponential runtime and stack overflow.
1549 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1550 SDValue O0 = Val->getOperand(0);
1551 SDValue O1 = Val->getOperand(1);
1553 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1556 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1559 if (Opcode == ISD::OR) {
1560 // For an OR expression we need to be able to negate at least one side or
1561 // we cannot do the transformation at all.
1562 if (!CanNegateL && !CanNegateR)
1564 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1565 // can negate the x and y subtrees.
1566 CanNegate = CanNegateL && CanNegateR;
1568 // If the operands are OR expressions then we finally need to negate their
1569 // outputs, we can only do that for the operand with emitted last by
1570 // negating OutCC, not for both operands.
1571 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1572 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1573 if (NeedsNegOutL && NeedsNegOutR)
1575 // We cannot negate an AND operation (it would become an OR),
1583 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1584 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1585 /// Tries to transform the given i1 producing node @p Val to a series compare
1586 /// and conditional compare operations. @returns an NZCV flags producing node
1587 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1588 /// transformation was not possible.
1589 /// On recursive invocations @p PushNegate may be set to true to have negation
1590 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1591 /// for the comparisons in the current subtree; @p Depth limits the search
1592 /// depth to avoid stack overflow.
1593 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1594 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1595 AArch64CC::CondCode Predicate) {
1596 // We're at a tree leaf, produce a conditional comparison operation.
1597 unsigned Opcode = Val->getOpcode();
1598 if (Opcode == ISD::SETCC) {
1599 SDValue LHS = Val->getOperand(0);
1600 SDValue RHS = Val->getOperand(1);
1601 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1602 bool isInteger = LHS.getValueType().isInteger();
1604 CC = getSetCCInverse(CC, isInteger);
1606 // Determine OutCC and handle FP special case.
1608 OutCC = changeIntCCToAArch64CC(CC);
1610 assert(LHS.getValueType().isFloatingPoint());
1611 AArch64CC::CondCode ExtraCC;
1612 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1613 // Some floating point conditions can't be tested with a single condition
1614 // code. Construct an additional comparison in this case.
1615 if (ExtraCC != AArch64CC::AL) {
1617 if (!CCOp.getNode())
1618 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1620 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1623 Predicate = ExtraCC;
1627 // Produce a normal comparison if we are first in the chain
1629 return emitComparison(LHS, RHS, CC, DL, DAG);
1630 // Otherwise produce a ccmp.
1631 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1634 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1635 "Valid conjunction/disjunction tree");
1637 // Check if both sides can be transformed.
1638 SDValue LHS = Val->getOperand(0);
1639 SDValue RHS = Val->getOperand(1);
1641 // In case of an OR we need to negate our operands and the result.
1642 // (A v B) <=> not(not(A) ^ not(B))
1643 bool NegateOpsAndResult = Opcode == ISD::OR;
1644 // We can negate the results of all previous operations by inverting the
1645 // predicate flags giving us a free negation for one side. The other side
1646 // must be negatable by itself.
1647 if (NegateOpsAndResult) {
1648 // See which side we can negate.
1650 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1651 assert(isValidL && "Valid conjunction/disjunction tree");
1656 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1657 assert(isValidR && "Valid conjunction/disjunction tree");
1658 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1661 // Order the side which we cannot negate to RHS so we can emit it first.
1663 std::swap(LHS, RHS);
1665 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1666 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1667 "Valid conjunction/disjunction tree");
1668 // Order the side where we need to negate the output flags to RHS so it
1669 // gets emitted first.
1671 std::swap(LHS, RHS);
1674 // Emit RHS. If we want to negate the tree we only need to push a negate
1675 // through if we are already in a PushNegate case, otherwise we can negate
1676 // the "flags to test" afterwards.
1677 AArch64CC::CondCode RHSCC;
1678 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1680 if (NegateOpsAndResult && !Negate)
1681 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1682 // Emit LHS. We may need to negate it.
1683 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1684 NegateOpsAndResult, CmpR,
1686 // If we transformed an OR to and AND then we have to negate the result
1687 // (or absorb the Negate parameter).
1688 if (NegateOpsAndResult && !Negate)
1689 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1693 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1694 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1695 /// \see emitConjunctionDisjunctionTreeRec().
1696 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1697 AArch64CC::CondCode &OutCC) {
1699 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1702 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1708 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1709 SDValue &AArch64cc, SelectionDAG &DAG,
1711 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1712 EVT VT = RHS.getValueType();
1713 uint64_t C = RHSC->getZExtValue();
1714 if (!isLegalArithImmed(C)) {
1715 // Constant does not fit, try adjusting it by one?
1721 if ((VT == MVT::i32 && C != 0x80000000 &&
1722 isLegalArithImmed((uint32_t)(C - 1))) ||
1723 (VT == MVT::i64 && C != 0x80000000ULL &&
1724 isLegalArithImmed(C - 1ULL))) {
1725 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1726 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1727 RHS = DAG.getConstant(C, dl, VT);
1732 if ((VT == MVT::i32 && C != 0 &&
1733 isLegalArithImmed((uint32_t)(C - 1))) ||
1734 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1735 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1736 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1737 RHS = DAG.getConstant(C, dl, VT);
1742 if ((VT == MVT::i32 && C != INT32_MAX &&
1743 isLegalArithImmed((uint32_t)(C + 1))) ||
1744 (VT == MVT::i64 && C != INT64_MAX &&
1745 isLegalArithImmed(C + 1ULL))) {
1746 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1747 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1748 RHS = DAG.getConstant(C, dl, VT);
1753 if ((VT == MVT::i32 && C != UINT32_MAX &&
1754 isLegalArithImmed((uint32_t)(C + 1))) ||
1755 (VT == MVT::i64 && C != UINT64_MAX &&
1756 isLegalArithImmed(C + 1ULL))) {
1757 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1758 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1759 RHS = DAG.getConstant(C, dl, VT);
1766 AArch64CC::CondCode AArch64CC;
1767 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1768 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1770 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1771 // For the i8 operand, the largest immediate is 255, so this can be easily
1772 // encoded in the compare instruction. For the i16 operand, however, the
1773 // largest immediate cannot be encoded in the compare.
1774 // Therefore, use a sign extending load and cmn to avoid materializing the
1775 // -1 constant. For example,
1777 // ldrh w0, [x0, #0]
1780 // ldrsh w0, [x0, #0]
1782 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1783 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1784 // ensure both the LHS and RHS are truly zero extended and to make sure the
1785 // transformation is profitable.
1786 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1787 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1788 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1789 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1790 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1791 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1793 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1794 DAG.getValueType(MVT::i16));
1795 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1796 RHS.getValueType()),
1798 AArch64CC = changeIntCCToAArch64CC(CC);
1802 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1803 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1804 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1805 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1811 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1812 AArch64CC = changeIntCCToAArch64CC(CC);
1814 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1818 static std::pair<SDValue, SDValue>
1819 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1820 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1821 "Unsupported value type");
1822 SDValue Value, Overflow;
1824 SDValue LHS = Op.getOperand(0);
1825 SDValue RHS = Op.getOperand(1);
1827 switch (Op.getOpcode()) {
1829 llvm_unreachable("Unknown overflow instruction!");
1831 Opc = AArch64ISD::ADDS;
1835 Opc = AArch64ISD::ADDS;
1839 Opc = AArch64ISD::SUBS;
1843 Opc = AArch64ISD::SUBS;
1846 // Multiply needs a little bit extra work.
1850 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1851 if (Op.getValueType() == MVT::i32) {
1852 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1853 // For a 32 bit multiply with overflow check we want the instruction
1854 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1855 // need to generate the following pattern:
1856 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1857 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1858 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1859 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1860 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1861 DAG.getConstant(0, DL, MVT::i64));
1862 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1863 // operation. We need to clear out the upper 32 bits, because we used a
1864 // widening multiply that wrote all 64 bits. In the end this should be a
1866 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1868 // The signed overflow check requires more than just a simple check for
1869 // any bit set in the upper 32 bits of the result. These bits could be
1870 // just the sign bits of a negative number. To perform the overflow
1871 // check we have to arithmetic shift right the 32nd bit of the result by
1872 // 31 bits. Then we compare the result to the upper 32 bits.
1873 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1874 DAG.getConstant(32, DL, MVT::i64));
1875 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1876 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1877 DAG.getConstant(31, DL, MVT::i64));
1878 // It is important that LowerBits is last, otherwise the arithmetic
1879 // shift will not be folded into the compare (SUBS).
1880 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1881 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1884 // The overflow check for unsigned multiply is easy. We only need to
1885 // check if any of the upper 32 bits are set. This can be done with a
1886 // CMP (shifted register). For that we need to generate the following
1888 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1889 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1890 DAG.getConstant(32, DL, MVT::i64));
1891 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1893 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1894 DAG.getConstant(0, DL, MVT::i64),
1895 UpperBits).getValue(1);
1899 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1900 // For the 64 bit multiply
1901 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1903 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1904 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1905 DAG.getConstant(63, DL, MVT::i64));
1906 // It is important that LowerBits is last, otherwise the arithmetic
1907 // shift will not be folded into the compare (SUBS).
1908 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1909 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1912 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1913 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1915 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1916 DAG.getConstant(0, DL, MVT::i64),
1917 UpperBits).getValue(1);
1924 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1926 // Emit the AArch64 operation with overflow check.
1927 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1928 Overflow = Value.getValue(1);
1930 return std::make_pair(Value, Overflow);
1933 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1934 RTLIB::Libcall Call) const {
1935 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1936 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1939 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1940 SDValue Sel = Op.getOperand(0);
1941 SDValue Other = Op.getOperand(1);
1943 // If neither operand is a SELECT_CC, give up.
1944 if (Sel.getOpcode() != ISD::SELECT_CC)
1945 std::swap(Sel, Other);
1946 if (Sel.getOpcode() != ISD::SELECT_CC)
1949 // The folding we want to perform is:
1950 // (xor x, (select_cc a, b, cc, 0, -1) )
1952 // (csel x, (xor x, -1), cc ...)
1954 // The latter will get matched to a CSINV instruction.
1956 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1957 SDValue LHS = Sel.getOperand(0);
1958 SDValue RHS = Sel.getOperand(1);
1959 SDValue TVal = Sel.getOperand(2);
1960 SDValue FVal = Sel.getOperand(3);
1963 // FIXME: This could be generalized to non-integer comparisons.
1964 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1967 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1968 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1970 // The values aren't constants, this isn't the pattern we're looking for.
1971 if (!CFVal || !CTVal)
1974 // We can commute the SELECT_CC by inverting the condition. This
1975 // might be needed to make this fit into a CSINV pattern.
1976 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1977 std::swap(TVal, FVal);
1978 std::swap(CTVal, CFVal);
1979 CC = ISD::getSetCCInverse(CC, true);
1982 // If the constants line up, perform the transform!
1983 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1985 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1988 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1989 DAG.getConstant(-1ULL, dl, Other.getValueType()));
1991 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1998 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1999 EVT VT = Op.getValueType();
2001 // Let legalize expand this if it isn't a legal type yet.
2002 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2005 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2008 bool ExtraOp = false;
2009 switch (Op.getOpcode()) {
2011 llvm_unreachable("Invalid code");
2013 Opc = AArch64ISD::ADDS;
2016 Opc = AArch64ISD::SUBS;
2019 Opc = AArch64ISD::ADCS;
2023 Opc = AArch64ISD::SBCS;
2029 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2030 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2034 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2035 // Let legalize expand this if it isn't a legal type yet.
2036 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2040 AArch64CC::CondCode CC;
2041 // The actual operation that sets the overflow or carry flag.
2042 SDValue Value, Overflow;
2043 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2045 // We use 0 and 1 as false and true values.
2046 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2047 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2049 // We use an inverted condition, because the conditional select is inverted
2050 // too. This will allow it to be selected to a single instruction:
2051 // CSINC Wd, WZR, WZR, invert(cond).
2052 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2053 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2056 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2057 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2060 // Prefetch operands are:
2061 // 1: Address to prefetch
2063 // 3: int locality (0 = no locality ... 3 = extreme locality)
2064 // 4: bool isDataCache
2065 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2067 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2068 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2069 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2071 bool IsStream = !Locality;
2072 // When the locality number is set
2074 // The front-end should have filtered out the out-of-range values
2075 assert(Locality <= 3 && "Prefetch locality out-of-range");
2076 // The locality degree is the opposite of the cache speed.
2077 // Put the number the other way around.
2078 // The encoding starts at 0 for level 1
2079 Locality = 3 - Locality;
2082 // built the mask value encoding the expected behavior.
2083 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2084 (!IsData << 3) | // IsDataCache bit
2085 (Locality << 1) | // Cache level bits
2086 (unsigned)IsStream; // Stream bit
2087 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2088 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2091 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2092 SelectionDAG &DAG) const {
2093 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2096 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2098 return LowerF128Call(Op, DAG, LC);
2101 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2102 SelectionDAG &DAG) const {
2103 if (Op.getOperand(0).getValueType() != MVT::f128) {
2104 // It's legal except when f128 is involved
2109 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2111 // FP_ROUND node has a second operand indicating whether it is known to be
2112 // precise. That doesn't take part in the LibCall so we can't directly use
2114 SDValue SrcVal = Op.getOperand(0);
2115 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2119 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2120 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2121 // Any additional optimization in this function should be recorded
2122 // in the cost tables.
2123 EVT InVT = Op.getOperand(0).getValueType();
2124 EVT VT = Op.getValueType();
2125 unsigned NumElts = InVT.getVectorNumElements();
2127 // f16 vectors are promoted to f32 before a conversion.
2128 if (InVT.getVectorElementType() == MVT::f16) {
2129 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2132 Op.getOpcode(), dl, Op.getValueType(),
2133 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2136 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2139 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2141 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2144 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2147 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2148 VT.getVectorNumElements());
2149 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2150 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2153 // Type changing conversions are illegal.
2157 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2158 SelectionDAG &DAG) const {
2159 if (Op.getOperand(0).getValueType().isVector())
2160 return LowerVectorFP_TO_INT(Op, DAG);
2162 // f16 conversions are promoted to f32.
2163 if (Op.getOperand(0).getValueType() == MVT::f16) {
2166 Op.getOpcode(), dl, Op.getValueType(),
2167 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2170 if (Op.getOperand(0).getValueType() != MVT::f128) {
2171 // It's legal except when f128 is involved
2176 if (Op.getOpcode() == ISD::FP_TO_SINT)
2177 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2179 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2181 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2182 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2185 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2186 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2187 // Any additional optimization in this function should be recorded
2188 // in the cost tables.
2189 EVT VT = Op.getValueType();
2191 SDValue In = Op.getOperand(0);
2192 EVT InVT = In.getValueType();
2194 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2196 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2197 InVT.getVectorNumElements());
2198 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2199 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2202 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2204 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2205 EVT CastVT = VT.changeVectorElementTypeToInteger();
2206 In = DAG.getNode(CastOpc, dl, CastVT, In);
2207 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2213 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2214 SelectionDAG &DAG) const {
2215 if (Op.getValueType().isVector())
2216 return LowerVectorINT_TO_FP(Op, DAG);
2218 // f16 conversions are promoted to f32.
2219 if (Op.getValueType() == MVT::f16) {
2222 ISD::FP_ROUND, dl, MVT::f16,
2223 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2224 DAG.getIntPtrConstant(0, dl));
2227 // i128 conversions are libcalls.
2228 if (Op.getOperand(0).getValueType() == MVT::i128)
2231 // Other conversions are legal, unless it's to the completely software-based
2233 if (Op.getValueType() != MVT::f128)
2237 if (Op.getOpcode() == ISD::SINT_TO_FP)
2238 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2240 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2242 return LowerF128Call(Op, DAG, LC);
2245 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2246 SelectionDAG &DAG) const {
2247 // For iOS, we want to call an alternative entry point: __sincos_stret,
2248 // which returns the values in two S / D registers.
2250 SDValue Arg = Op.getOperand(0);
2251 EVT ArgVT = Arg.getValueType();
2252 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2259 Entry.IsSExt = false;
2260 Entry.IsZExt = false;
2261 Args.push_back(Entry);
2263 const char *LibcallName =
2264 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2266 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2268 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
2269 TargetLowering::CallLoweringInfo CLI(DAG);
2271 .setChain(DAG.getEntryNode())
2272 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2274 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2275 return CallResult.first;
2278 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2279 if (Op.getValueType() != MVT::f16)
2282 assert(Op.getOperand(0).getValueType() == MVT::i16);
2285 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2286 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2288 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2289 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2293 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2294 if (OrigVT.getSizeInBits() >= 64)
2297 assert(OrigVT.isSimple() && "Expecting a simple value type");
2299 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2300 switch (OrigSimpleTy) {
2301 default: llvm_unreachable("Unexpected Vector Type");
2310 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2313 unsigned ExtOpcode) {
2314 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2315 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2316 // 64-bits we need to insert a new extension so that it will be 64-bits.
2317 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2318 if (OrigTy.getSizeInBits() >= 64)
2321 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2322 EVT NewVT = getExtensionTo64Bits(OrigTy);
2324 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2327 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2329 EVT VT = N->getValueType(0);
2331 if (N->getOpcode() != ISD::BUILD_VECTOR)
2334 for (const SDValue &Elt : N->op_values()) {
2335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2336 unsigned EltSize = VT.getScalarSizeInBits();
2337 unsigned HalfSize = EltSize / 2;
2339 if (!isIntN(HalfSize, C->getSExtValue()))
2342 if (!isUIntN(HalfSize, C->getZExtValue()))
2353 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2354 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2355 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2356 N->getOperand(0)->getValueType(0),
2360 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2361 EVT VT = N->getValueType(0);
2363 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2364 unsigned NumElts = VT.getVectorNumElements();
2365 MVT TruncVT = MVT::getIntegerVT(EltSize);
2366 SmallVector<SDValue, 8> Ops;
2367 for (unsigned i = 0; i != NumElts; ++i) {
2368 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2369 const APInt &CInt = C->getAPIntValue();
2370 // Element types smaller than 32 bits are not legal, so use i32 elements.
2371 // The values are implicitly truncated so sext vs. zext doesn't matter.
2372 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2374 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2377 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2378 return N->getOpcode() == ISD::SIGN_EXTEND ||
2379 isExtendedBUILD_VECTOR(N, DAG, true);
2382 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2383 return N->getOpcode() == ISD::ZERO_EXTEND ||
2384 isExtendedBUILD_VECTOR(N, DAG, false);
2387 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2388 unsigned Opcode = N->getOpcode();
2389 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2390 SDNode *N0 = N->getOperand(0).getNode();
2391 SDNode *N1 = N->getOperand(1).getNode();
2392 return N0->hasOneUse() && N1->hasOneUse() &&
2393 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2398 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2399 unsigned Opcode = N->getOpcode();
2400 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2401 SDNode *N0 = N->getOperand(0).getNode();
2402 SDNode *N1 = N->getOperand(1).getNode();
2403 return N0->hasOneUse() && N1->hasOneUse() &&
2404 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2409 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2410 // Multiplications are only custom-lowered for 128-bit vectors so that
2411 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2412 EVT VT = Op.getValueType();
2413 assert(VT.is128BitVector() && VT.isInteger() &&
2414 "unexpected type for custom-lowering ISD::MUL");
2415 SDNode *N0 = Op.getOperand(0).getNode();
2416 SDNode *N1 = Op.getOperand(1).getNode();
2417 unsigned NewOpc = 0;
2419 bool isN0SExt = isSignExtended(N0, DAG);
2420 bool isN1SExt = isSignExtended(N1, DAG);
2421 if (isN0SExt && isN1SExt)
2422 NewOpc = AArch64ISD::SMULL;
2424 bool isN0ZExt = isZeroExtended(N0, DAG);
2425 bool isN1ZExt = isZeroExtended(N1, DAG);
2426 if (isN0ZExt && isN1ZExt)
2427 NewOpc = AArch64ISD::UMULL;
2428 else if (isN1SExt || isN1ZExt) {
2429 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2430 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2431 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2432 NewOpc = AArch64ISD::SMULL;
2434 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2435 NewOpc = AArch64ISD::UMULL;
2437 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2439 NewOpc = AArch64ISD::UMULL;
2445 if (VT == MVT::v2i64)
2446 // Fall through to expand this. It is not legal.
2449 // Other vector multiplications are legal.
2454 // Legalize to a S/UMULL instruction
2457 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2459 Op0 = skipExtensionForVectorMULL(N0, DAG);
2460 assert(Op0.getValueType().is64BitVector() &&
2461 Op1.getValueType().is64BitVector() &&
2462 "unexpected types for extended operands to VMULL");
2463 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2465 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2466 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2467 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2468 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2469 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2470 EVT Op1VT = Op1.getValueType();
2471 return DAG.getNode(N0->getOpcode(), DL, VT,
2472 DAG.getNode(NewOpc, DL, VT,
2473 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2474 DAG.getNode(NewOpc, DL, VT,
2475 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2478 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2479 SelectionDAG &DAG) const {
2480 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2483 default: return SDValue(); // Don't custom lower most intrinsics.
2484 case Intrinsic::thread_pointer: {
2485 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2486 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2488 case Intrinsic::aarch64_neon_abs:
2489 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2491 case Intrinsic::aarch64_neon_smax:
2492 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2493 Op.getOperand(1), Op.getOperand(2));
2494 case Intrinsic::aarch64_neon_umax:
2495 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2496 Op.getOperand(1), Op.getOperand(2));
2497 case Intrinsic::aarch64_neon_smin:
2498 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2499 Op.getOperand(1), Op.getOperand(2));
2500 case Intrinsic::aarch64_neon_umin:
2501 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2502 Op.getOperand(1), Op.getOperand(2));
2506 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2507 SelectionDAG &DAG) const {
2508 switch (Op.getOpcode()) {
2510 llvm_unreachable("unimplemented operand");
2513 return LowerBITCAST(Op, DAG);
2514 case ISD::GlobalAddress:
2515 return LowerGlobalAddress(Op, DAG);
2516 case ISD::GlobalTLSAddress:
2517 return LowerGlobalTLSAddress(Op, DAG);
2519 return LowerSETCC(Op, DAG);
2521 return LowerBR_CC(Op, DAG);
2523 return LowerSELECT(Op, DAG);
2524 case ISD::SELECT_CC:
2525 return LowerSELECT_CC(Op, DAG);
2526 case ISD::JumpTable:
2527 return LowerJumpTable(Op, DAG);
2528 case ISD::ConstantPool:
2529 return LowerConstantPool(Op, DAG);
2530 case ISD::BlockAddress:
2531 return LowerBlockAddress(Op, DAG);
2533 return LowerVASTART(Op, DAG);
2535 return LowerVACOPY(Op, DAG);
2537 return LowerVAARG(Op, DAG);
2542 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2549 return LowerXALUO(Op, DAG);
2551 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2553 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2555 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2557 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2559 return LowerFP_ROUND(Op, DAG);
2560 case ISD::FP_EXTEND:
2561 return LowerFP_EXTEND(Op, DAG);
2562 case ISD::FRAMEADDR:
2563 return LowerFRAMEADDR(Op, DAG);
2564 case ISD::RETURNADDR:
2565 return LowerRETURNADDR(Op, DAG);
2566 case ISD::INSERT_VECTOR_ELT:
2567 return LowerINSERT_VECTOR_ELT(Op, DAG);
2568 case ISD::EXTRACT_VECTOR_ELT:
2569 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2570 case ISD::BUILD_VECTOR:
2571 return LowerBUILD_VECTOR(Op, DAG);
2572 case ISD::VECTOR_SHUFFLE:
2573 return LowerVECTOR_SHUFFLE(Op, DAG);
2574 case ISD::EXTRACT_SUBVECTOR:
2575 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2579 return LowerVectorSRA_SRL_SHL(Op, DAG);
2580 case ISD::SHL_PARTS:
2581 return LowerShiftLeftParts(Op, DAG);
2582 case ISD::SRL_PARTS:
2583 case ISD::SRA_PARTS:
2584 return LowerShiftRightParts(Op, DAG);
2586 return LowerCTPOP(Op, DAG);
2587 case ISD::FCOPYSIGN:
2588 return LowerFCOPYSIGN(Op, DAG);
2590 return LowerVectorAND(Op, DAG);
2592 return LowerVectorOR(Op, DAG);
2594 return LowerXOR(Op, DAG);
2596 return LowerPREFETCH(Op, DAG);
2597 case ISD::SINT_TO_FP:
2598 case ISD::UINT_TO_FP:
2599 return LowerINT_TO_FP(Op, DAG);
2600 case ISD::FP_TO_SINT:
2601 case ISD::FP_TO_UINT:
2602 return LowerFP_TO_INT(Op, DAG);
2604 return LowerFSINCOS(Op, DAG);
2606 return LowerMUL(Op, DAG);
2607 case ISD::INTRINSIC_WO_CHAIN:
2608 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2612 //===----------------------------------------------------------------------===//
2613 // Calling Convention Implementation
2614 //===----------------------------------------------------------------------===//
2616 #include "AArch64GenCallingConv.inc"
2618 /// Selects the correct CCAssignFn for a given CallingConvention value.
2619 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2620 bool IsVarArg) const {
2623 llvm_unreachable("Unsupported calling convention.");
2624 case CallingConv::WebKit_JS:
2625 return CC_AArch64_WebKit_JS;
2626 case CallingConv::GHC:
2627 return CC_AArch64_GHC;
2628 case CallingConv::C:
2629 case CallingConv::Fast:
2630 case CallingConv::PreserveMost:
2631 case CallingConv::CXX_FAST_TLS:
2632 case CallingConv::Swift:
2633 if (!Subtarget->isTargetDarwin())
2634 return CC_AArch64_AAPCS;
2635 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2640 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2641 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2642 : RetCC_AArch64_AAPCS;
2645 SDValue AArch64TargetLowering::LowerFormalArguments(
2646 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2647 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2648 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2649 MachineFunction &MF = DAG.getMachineFunction();
2650 MachineFrameInfo &MFI = MF.getFrameInfo();
2652 // Assign locations to all of the incoming arguments.
2653 SmallVector<CCValAssign, 16> ArgLocs;
2654 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2657 // At this point, Ins[].VT may already be promoted to i32. To correctly
2658 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2659 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2660 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2661 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2663 unsigned NumArgs = Ins.size();
2664 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2665 unsigned CurArgIdx = 0;
2666 for (unsigned i = 0; i != NumArgs; ++i) {
2667 MVT ValVT = Ins[i].VT;
2668 if (Ins[i].isOrigArg()) {
2669 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2670 CurArgIdx = Ins[i].getOrigArgIndex();
2672 // Get type of the original argument.
2673 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2674 /*AllowUnknown*/ true);
2675 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2676 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2677 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2679 else if (ActualMVT == MVT::i16)
2682 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2684 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2685 assert(!Res && "Call operand has unhandled type");
2688 assert(ArgLocs.size() == Ins.size());
2689 SmallVector<SDValue, 16> ArgValues;
2690 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2691 CCValAssign &VA = ArgLocs[i];
2693 if (Ins[i].Flags.isByVal()) {
2694 // Byval is used for HFAs in the PCS, but the system should work in a
2695 // non-compliant manner for larger structs.
2696 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2697 int Size = Ins[i].Flags.getByValSize();
2698 unsigned NumRegs = (Size + 7) / 8;
2700 // FIXME: This works on big-endian for composite byvals, which are the common
2701 // case. It should also work for fundamental types too.
2703 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2704 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2705 InVals.push_back(FrameIdxN);
2710 if (VA.isRegLoc()) {
2711 // Arguments stored in registers.
2712 EVT RegVT = VA.getLocVT();
2715 const TargetRegisterClass *RC;
2717 if (RegVT == MVT::i32)
2718 RC = &AArch64::GPR32RegClass;
2719 else if (RegVT == MVT::i64)
2720 RC = &AArch64::GPR64RegClass;
2721 else if (RegVT == MVT::f16)
2722 RC = &AArch64::FPR16RegClass;
2723 else if (RegVT == MVT::f32)
2724 RC = &AArch64::FPR32RegClass;
2725 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2726 RC = &AArch64::FPR64RegClass;
2727 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2728 RC = &AArch64::FPR128RegClass;
2730 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2732 // Transform the arguments in physical registers into virtual ones.
2733 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2734 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2736 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2737 // to 64 bits. Insert an assert[sz]ext to capture this, then
2738 // truncate to the right size.
2739 switch (VA.getLocInfo()) {
2741 llvm_unreachable("Unknown loc info!");
2742 case CCValAssign::Full:
2744 case CCValAssign::BCvt:
2745 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2747 case CCValAssign::AExt:
2748 case CCValAssign::SExt:
2749 case CCValAssign::ZExt:
2750 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2751 // nodes after our lowering.
2752 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2756 InVals.push_back(ArgValue);
2758 } else { // VA.isRegLoc()
2759 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2760 unsigned ArgOffset = VA.getLocMemOffset();
2761 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2763 uint32_t BEAlign = 0;
2764 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2765 !Ins[i].Flags.isInConsecutiveRegs())
2766 BEAlign = 8 - ArgSize;
2768 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2770 // Create load nodes to retrieve arguments from the stack.
2771 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2774 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2775 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2776 MVT MemVT = VA.getValVT();
2778 switch (VA.getLocInfo()) {
2781 case CCValAssign::BCvt:
2782 MemVT = VA.getLocVT();
2784 case CCValAssign::SExt:
2785 ExtType = ISD::SEXTLOAD;
2787 case CCValAssign::ZExt:
2788 ExtType = ISD::ZEXTLOAD;
2790 case CCValAssign::AExt:
2791 ExtType = ISD::EXTLOAD;
2795 ArgValue = DAG.getExtLoad(
2796 ExtType, DL, VA.getLocVT(), Chain, FIN,
2797 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2800 InVals.push_back(ArgValue);
2805 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2807 if (!Subtarget->isTargetDarwin()) {
2808 // The AAPCS variadic function ABI is identical to the non-variadic
2809 // one. As a result there may be more arguments in registers and we should
2810 // save them for future reference.
2811 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2814 // This will point to the next argument passed via stack.
2815 unsigned StackOffset = CCInfo.getNextStackOffset();
2816 // We currently pass all varargs at 8-byte alignment.
2817 StackOffset = ((StackOffset + 7) & ~7);
2818 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2821 unsigned StackArgSize = CCInfo.getNextStackOffset();
2822 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2823 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2824 // This is a non-standard ABI so by fiat I say we're allowed to make full
2825 // use of the stack area to be popped, which must be aligned to 16 bytes in
2827 StackArgSize = alignTo(StackArgSize, 16);
2829 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2830 // a multiple of 16.
2831 FuncInfo->setArgumentStackToRestore(StackArgSize);
2833 // This realignment carries over to the available bytes below. Our own
2834 // callers will guarantee the space is free by giving an aligned value to
2837 // Even if we're not expected to free up the space, it's useful to know how
2838 // much is there while considering tail calls (because we can reuse it).
2839 FuncInfo->setBytesInStackArgArea(StackArgSize);
2844 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2847 SDValue &Chain) const {
2848 MachineFunction &MF = DAG.getMachineFunction();
2849 MachineFrameInfo &MFI = MF.getFrameInfo();
2850 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2851 auto PtrVT = getPointerTy(DAG.getDataLayout());
2853 SmallVector<SDValue, 8> MemOps;
2855 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2856 AArch64::X3, AArch64::X4, AArch64::X5,
2857 AArch64::X6, AArch64::X7 };
2858 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2859 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2861 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2863 if (GPRSaveSize != 0) {
2864 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2866 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2868 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2869 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2870 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2871 SDValue Store = DAG.getStore(
2872 Val.getValue(1), DL, Val, FIN,
2873 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2874 MemOps.push_back(Store);
2876 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2879 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2880 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2882 if (Subtarget->hasFPARMv8()) {
2883 static const MCPhysReg FPRArgRegs[] = {
2884 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2885 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2886 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2887 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2889 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2891 if (FPRSaveSize != 0) {
2892 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2894 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2896 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2897 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2898 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2900 SDValue Store = DAG.getStore(
2901 Val.getValue(1), DL, Val, FIN,
2902 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2903 MemOps.push_back(Store);
2904 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2905 DAG.getConstant(16, DL, PtrVT));
2908 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2909 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2912 if (!MemOps.empty()) {
2913 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2917 /// LowerCallResult - Lower the result values of a call into the
2918 /// appropriate copies out of appropriate physical registers.
2919 SDValue AArch64TargetLowering::LowerCallResult(
2920 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2921 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2922 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2923 SDValue ThisVal) const {
2924 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2925 ? RetCC_AArch64_WebKit_JS
2926 : RetCC_AArch64_AAPCS;
2927 // Assign locations to each value returned by this call.
2928 SmallVector<CCValAssign, 16> RVLocs;
2929 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2931 CCInfo.AnalyzeCallResult(Ins, RetCC);
2933 // Copy all of the result registers out of their specified physreg.
2934 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2935 CCValAssign VA = RVLocs[i];
2937 // Pass 'this' value directly from the argument to return value, to avoid
2938 // reg unit interference
2939 if (i == 0 && isThisReturn) {
2940 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2941 "unexpected return calling convention register assignment");
2942 InVals.push_back(ThisVal);
2947 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2948 Chain = Val.getValue(1);
2949 InFlag = Val.getValue(2);
2951 switch (VA.getLocInfo()) {
2953 llvm_unreachable("Unknown loc info!");
2954 case CCValAssign::Full:
2956 case CCValAssign::BCvt:
2957 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2961 InVals.push_back(Val);
2967 /// Return true if the calling convention is one that we can guarantee TCO for.
2968 static bool canGuaranteeTCO(CallingConv::ID CC) {
2969 return CC == CallingConv::Fast;
2972 /// Return true if we might ever do TCO for calls with this calling convention.
2973 static bool mayTailCallThisCC(CallingConv::ID CC) {
2975 case CallingConv::C:
2976 case CallingConv::PreserveMost:
2977 case CallingConv::Swift:
2980 return canGuaranteeTCO(CC);
2984 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2985 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2986 const SmallVectorImpl<ISD::OutputArg> &Outs,
2987 const SmallVectorImpl<SDValue> &OutVals,
2988 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2989 if (!mayTailCallThisCC(CalleeCC))
2992 MachineFunction &MF = DAG.getMachineFunction();
2993 const Function *CallerF = MF.getFunction();
2994 CallingConv::ID CallerCC = CallerF->getCallingConv();
2995 bool CCMatch = CallerCC == CalleeCC;
2997 // Byval parameters hand the function a pointer directly into the stack area
2998 // we want to reuse during a tail call. Working around this *is* possible (see
2999 // X86) but less efficient and uglier in LowerCall.
3000 for (Function::const_arg_iterator i = CallerF->arg_begin(),
3001 e = CallerF->arg_end();
3003 if (i->hasByValAttr())
3006 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3007 return canGuaranteeTCO(CalleeCC) && CCMatch;
3009 // Externally-defined functions with weak linkage should not be
3010 // tail-called on AArch64 when the OS does not support dynamic
3011 // pre-emption of symbols, as the AAELF spec requires normal calls
3012 // to undefined weak functions to be replaced with a NOP or jump to the
3013 // next instruction. The behaviour of branch instructions in this
3014 // situation (as used for tail calls) is implementation-defined, so we
3015 // cannot rely on the linker replacing the tail call with a return.
3016 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3017 const GlobalValue *GV = G->getGlobal();
3018 const Triple &TT = getTargetMachine().getTargetTriple();
3019 if (GV->hasExternalWeakLinkage() &&
3020 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3024 // Now we search for cases where we can use a tail call without changing the
3025 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3028 // I want anyone implementing a new calling convention to think long and hard
3029 // about this assert.
3030 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3031 "Unexpected variadic calling convention");
3033 LLVMContext &C = *DAG.getContext();
3034 if (isVarArg && !Outs.empty()) {
3035 // At least two cases here: if caller is fastcc then we can't have any
3036 // memory arguments (we'd be expected to clean up the stack afterwards). If
3037 // caller is C then we could potentially use its argument area.
3039 // FIXME: for now we take the most conservative of these in both cases:
3040 // disallow all variadic memory operands.
3041 SmallVector<CCValAssign, 16> ArgLocs;
3042 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3044 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3045 for (const CCValAssign &ArgLoc : ArgLocs)
3046 if (!ArgLoc.isRegLoc())
3050 // Check that the call results are passed in the same way.
3051 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3052 CCAssignFnForCall(CalleeCC, isVarArg),
3053 CCAssignFnForCall(CallerCC, isVarArg)))
3055 // The callee has to preserve all registers the caller needs to preserve.
3056 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3057 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3059 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3060 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3064 // Nothing more to check if the callee is taking no arguments
3068 SmallVector<CCValAssign, 16> ArgLocs;
3069 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3071 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3073 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3075 // If the stack arguments for this call do not fit into our own save area then
3076 // the call cannot be made tail.
3077 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3080 const MachineRegisterInfo &MRI = MF.getRegInfo();
3081 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3087 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3089 MachineFrameInfo &MFI,
3090 int ClobberedFI) const {
3091 SmallVector<SDValue, 8> ArgChains;
3092 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3093 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3095 // Include the original chain at the beginning of the list. When this is
3096 // used by target LowerCall hooks, this helps legalize find the
3097 // CALLSEQ_BEGIN node.
3098 ArgChains.push_back(Chain);
3100 // Add a chain value for each stack argument corresponding
3101 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3102 UE = DAG.getEntryNode().getNode()->use_end();
3104 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3105 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3106 if (FI->getIndex() < 0) {
3107 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3108 int64_t InLastByte = InFirstByte;
3109 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3111 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3112 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3113 ArgChains.push_back(SDValue(L, 1));
3116 // Build a tokenfactor for all the chains.
3117 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3120 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3121 bool TailCallOpt) const {
3122 return CallCC == CallingConv::Fast && TailCallOpt;
3125 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3126 /// and add input and output parameter nodes.
3128 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3129 SmallVectorImpl<SDValue> &InVals) const {
3130 SelectionDAG &DAG = CLI.DAG;
3132 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3133 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3134 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3135 SDValue Chain = CLI.Chain;
3136 SDValue Callee = CLI.Callee;
3137 bool &IsTailCall = CLI.IsTailCall;
3138 CallingConv::ID CallConv = CLI.CallConv;
3139 bool IsVarArg = CLI.IsVarArg;
3141 MachineFunction &MF = DAG.getMachineFunction();
3142 bool IsThisReturn = false;
3144 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3145 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3146 bool IsSibCall = false;
3149 // Check if it's really possible to do a tail call.
3150 IsTailCall = isEligibleForTailCallOptimization(
3151 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3152 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3153 report_fatal_error("failed to perform tail call elimination on a call "
3154 "site marked musttail");
3156 // A sibling call is one where we're under the usual C ABI and not planning
3157 // to change that but can still do a tail call:
3158 if (!TailCallOpt && IsTailCall)
3165 // Analyze operands of the call, assigning locations to each operand.
3166 SmallVector<CCValAssign, 16> ArgLocs;
3167 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3171 // Handle fixed and variable vector arguments differently.
3172 // Variable vector arguments always go into memory.
3173 unsigned NumArgs = Outs.size();
3175 for (unsigned i = 0; i != NumArgs; ++i) {
3176 MVT ArgVT = Outs[i].VT;
3177 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3178 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3179 /*IsVarArg=*/ !Outs[i].IsFixed);
3180 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3181 assert(!Res && "Call operand has unhandled type");
3185 // At this point, Outs[].VT may already be promoted to i32. To correctly
3186 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3187 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3188 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3189 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3191 unsigned NumArgs = Outs.size();
3192 for (unsigned i = 0; i != NumArgs; ++i) {
3193 MVT ValVT = Outs[i].VT;
3194 // Get type of the original argument.
3195 EVT ActualVT = getValueType(DAG.getDataLayout(),
3196 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3197 /*AllowUnknown*/ true);
3198 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3199 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3200 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3201 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3203 else if (ActualMVT == MVT::i16)
3206 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3207 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3208 assert(!Res && "Call operand has unhandled type");
3213 // Get a count of how many bytes are to be pushed on the stack.
3214 unsigned NumBytes = CCInfo.getNextStackOffset();
3217 // Since we're not changing the ABI to make this a tail call, the memory
3218 // operands are already available in the caller's incoming argument space.
3222 // FPDiff is the byte offset of the call's argument area from the callee's.
3223 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3224 // by this amount for a tail call. In a sibling call it must be 0 because the
3225 // caller will deallocate the entire stack and the callee still expects its
3226 // arguments to begin at SP+0. Completely unused for non-tail calls.
3229 if (IsTailCall && !IsSibCall) {
3230 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3232 // Since callee will pop argument stack as a tail call, we must keep the
3233 // popped size 16-byte aligned.
3234 NumBytes = alignTo(NumBytes, 16);
3236 // FPDiff will be negative if this tail call requires more space than we
3237 // would automatically have in our incoming argument space. Positive if we
3238 // can actually shrink the stack.
3239 FPDiff = NumReusableBytes - NumBytes;
3241 // The stack pointer must be 16-byte aligned at all times it's used for a
3242 // memory operation, which in practice means at *all* times and in
3243 // particular across call boundaries. Therefore our own arguments started at
3244 // a 16-byte aligned SP and the delta applied for the tail call should
3245 // satisfy the same constraint.
3246 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3249 // Adjust the stack pointer for the new arguments...
3250 // These operations are automatically eliminated by the prolog/epilog pass
3252 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3256 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3257 getPointerTy(DAG.getDataLayout()));
3259 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3260 SmallVector<SDValue, 8> MemOpChains;
3261 auto PtrVT = getPointerTy(DAG.getDataLayout());
3263 // Walk the register/memloc assignments, inserting copies/loads.
3264 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3265 ++i, ++realArgIdx) {
3266 CCValAssign &VA = ArgLocs[i];
3267 SDValue Arg = OutVals[realArgIdx];
3268 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3270 // Promote the value if needed.
3271 switch (VA.getLocInfo()) {
3273 llvm_unreachable("Unknown loc info!");
3274 case CCValAssign::Full:
3276 case CCValAssign::SExt:
3277 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3279 case CCValAssign::ZExt:
3280 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3282 case CCValAssign::AExt:
3283 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3284 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3285 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3286 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3288 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3290 case CCValAssign::BCvt:
3291 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3293 case CCValAssign::FPExt:
3294 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3298 if (VA.isRegLoc()) {
3299 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3300 Outs[0].VT == MVT::i64) {
3301 assert(VA.getLocVT() == MVT::i64 &&
3302 "unexpected calling convention register assignment");
3303 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3304 "unexpected use of 'returned'");
3305 IsThisReturn = true;
3307 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3309 assert(VA.isMemLoc());
3312 MachinePointerInfo DstInfo;
3314 // FIXME: This works on big-endian for composite byvals, which are the
3315 // common case. It should also work for fundamental types too.
3316 uint32_t BEAlign = 0;
3317 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3318 : VA.getValVT().getSizeInBits();
3319 OpSize = (OpSize + 7) / 8;
3320 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3321 !Flags.isInConsecutiveRegs()) {
3323 BEAlign = 8 - OpSize;
3325 unsigned LocMemOffset = VA.getLocMemOffset();
3326 int32_t Offset = LocMemOffset + BEAlign;
3327 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3328 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3331 Offset = Offset + FPDiff;
3332 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3334 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3336 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3338 // Make sure any stack arguments overlapping with where we're storing
3339 // are loaded before this eventual operation. Otherwise they'll be
3341 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3343 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3345 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3346 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3350 if (Outs[i].Flags.isByVal()) {
3352 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3353 SDValue Cpy = DAG.getMemcpy(
3354 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3355 /*isVol = */ false, /*AlwaysInline = */ false,
3356 /*isTailCall = */ false,
3357 DstInfo, MachinePointerInfo());
3359 MemOpChains.push_back(Cpy);
3361 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3362 // promoted to a legal register type i32, we should truncate Arg back to
3364 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3365 VA.getValVT() == MVT::i16)
3366 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3368 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3369 MemOpChains.push_back(Store);
3374 if (!MemOpChains.empty())
3375 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3377 // Build a sequence of copy-to-reg nodes chained together with token chain
3378 // and flag operands which copy the outgoing args into the appropriate regs.
3380 for (auto &RegToPass : RegsToPass) {
3381 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3382 RegToPass.second, InFlag);
3383 InFlag = Chain.getValue(1);
3386 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3387 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3388 // node so that legalize doesn't hack it.
3389 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3390 auto GV = G->getGlobal();
3391 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3392 AArch64II::MO_GOT) {
3393 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3394 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3396 const GlobalValue *GV = G->getGlobal();
3397 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3399 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3400 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3401 Subtarget->isTargetMachO()) {
3402 const char *Sym = S->getSymbol();
3403 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3404 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3406 const char *Sym = S->getSymbol();
3407 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3411 // We don't usually want to end the call-sequence here because we would tidy
3412 // the frame up *after* the call, however in the ABI-changing tail-call case
3413 // we've carefully laid out the parameters so that when sp is reset they'll be
3414 // in the correct location.
3415 if (IsTailCall && !IsSibCall) {
3416 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3417 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3418 InFlag = Chain.getValue(1);
3421 std::vector<SDValue> Ops;
3422 Ops.push_back(Chain);
3423 Ops.push_back(Callee);
3426 // Each tail call may have to adjust the stack by a different amount, so
3427 // this information must travel along with the operation for eventual
3428 // consumption by emitEpilogue.
3429 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3432 // Add argument registers to the end of the list so that they are known live
3434 for (auto &RegToPass : RegsToPass)
3435 Ops.push_back(DAG.getRegister(RegToPass.first,
3436 RegToPass.second.getValueType()));
3438 // Add a register mask operand representing the call-preserved registers.
3439 const uint32_t *Mask;
3440 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3442 // For 'this' returns, use the X0-preserving mask if applicable
3443 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3445 IsThisReturn = false;
3446 Mask = TRI->getCallPreservedMask(MF, CallConv);
3449 Mask = TRI->getCallPreservedMask(MF, CallConv);
3451 assert(Mask && "Missing call preserved mask for calling convention");
3452 Ops.push_back(DAG.getRegisterMask(Mask));
3454 if (InFlag.getNode())
3455 Ops.push_back(InFlag);
3457 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3459 // If we're doing a tall call, use a TC_RETURN here rather than an
3460 // actual call instruction.
3462 MF.getFrameInfo().setHasTailCall();
3463 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3466 // Returns a chain and a flag for retval copy to use.
3467 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3468 InFlag = Chain.getValue(1);
3470 uint64_t CalleePopBytes =
3471 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3473 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3474 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3477 InFlag = Chain.getValue(1);
3479 // Handle result values, copying them out of physregs into vregs that we
3481 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3482 InVals, IsThisReturn,
3483 IsThisReturn ? OutVals[0] : SDValue());
3486 bool AArch64TargetLowering::CanLowerReturn(
3487 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3488 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3489 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3490 ? RetCC_AArch64_WebKit_JS
3491 : RetCC_AArch64_AAPCS;
3492 SmallVector<CCValAssign, 16> RVLocs;
3493 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3494 return CCInfo.CheckReturn(Outs, RetCC);
3498 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3500 const SmallVectorImpl<ISD::OutputArg> &Outs,
3501 const SmallVectorImpl<SDValue> &OutVals,
3502 const SDLoc &DL, SelectionDAG &DAG) const {
3503 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3504 ? RetCC_AArch64_WebKit_JS
3505 : RetCC_AArch64_AAPCS;
3506 SmallVector<CCValAssign, 16> RVLocs;
3507 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3509 CCInfo.AnalyzeReturn(Outs, RetCC);
3511 // Copy the result values into the output registers.
3513 SmallVector<SDValue, 4> RetOps(1, Chain);
3514 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3515 ++i, ++realRVLocIdx) {
3516 CCValAssign &VA = RVLocs[i];
3517 assert(VA.isRegLoc() && "Can only return in registers!");
3518 SDValue Arg = OutVals[realRVLocIdx];
3520 switch (VA.getLocInfo()) {
3522 llvm_unreachable("Unknown loc info!");
3523 case CCValAssign::Full:
3524 if (Outs[i].ArgVT == MVT::i1) {
3525 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3526 // value. This is strictly redundant on Darwin (which uses "zeroext
3527 // i1"), but will be optimised out before ISel.
3528 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3529 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3532 case CCValAssign::BCvt:
3533 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3537 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3538 Flag = Chain.getValue(1);
3539 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3541 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3542 const MCPhysReg *I =
3543 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3546 if (AArch64::GPR64RegClass.contains(*I))
3547 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3548 else if (AArch64::FPR64RegClass.contains(*I))
3549 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3551 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3555 RetOps[0] = Chain; // Update chain.
3557 // Add the flag if we have it.
3559 RetOps.push_back(Flag);
3561 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3564 //===----------------------------------------------------------------------===//
3565 // Other Lowering Code
3566 //===----------------------------------------------------------------------===//
3568 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3570 unsigned Flag) const {
3571 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3574 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3576 unsigned Flag) const {
3577 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3580 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3582 unsigned Flag) const {
3583 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3584 N->getOffset(), Flag);
3587 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3589 unsigned Flag) const {
3590 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3594 template <class NodeTy>
3595 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const {
3596 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3598 EVT Ty = getPointerTy(DAG.getDataLayout());
3599 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT);
3600 // FIXME: Once remat is capable of dealing with instructions with register
3601 // operands, expand this into two nodes instead of using a wrapper node.
3602 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3605 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3606 template <class NodeTy>
3607 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG)
3609 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3611 EVT Ty = getPointerTy(DAG.getDataLayout());
3612 const unsigned char MO_NC = AArch64II::MO_NC;
3614 AArch64ISD::WrapperLarge, DL, Ty,
3615 getTargetNode(N, Ty, DAG, AArch64II::MO_G3),
3616 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC),
3617 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC),
3618 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC));
3621 // (addlow (adrp %hi(sym)) %lo(sym))
3622 template <class NodeTy>
3623 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
3624 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3626 EVT Ty = getPointerTy(DAG.getDataLayout());
3627 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE);
3628 SDValue Lo = getTargetNode(N, Ty, DAG,
3629 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3630 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3631 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3634 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3635 SelectionDAG &DAG) const {
3636 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3637 const GlobalValue *GV = GN->getGlobal();
3638 unsigned char OpFlags =
3639 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3641 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3642 "unexpected offset in global node");
3644 // This also catches the large code model case for Darwin.
3645 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3646 return getGOT(GN, DAG);
3649 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3650 return getAddrLarge(GN, DAG);
3652 return getAddr(GN, DAG);
3656 /// \brief Convert a TLS address reference into the correct sequence of loads
3657 /// and calls to compute the variable's address (for Darwin, currently) and
3658 /// return an SDValue containing the final node.
3660 /// Darwin only has one TLS scheme which must be capable of dealing with the
3661 /// fully general situation, in the worst case. This means:
3662 /// + "extern __thread" declaration.
3663 /// + Defined in a possibly unknown dynamic library.
3665 /// The general system is that each __thread variable has a [3 x i64] descriptor
3666 /// which contains information used by the runtime to calculate the address. The
3667 /// only part of this the compiler needs to know about is the first xword, which
3668 /// contains a function pointer that must be called with the address of the
3669 /// entire descriptor in "x0".
3671 /// Since this descriptor may be in a different unit, in general even the
3672 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3674 /// adrp x0, _var@TLVPPAGE
3675 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3676 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3677 /// ; the function pointer
3678 /// blr x1 ; Uses descriptor address in x0
3679 /// ; Address of _var is now in x0.
3681 /// If the address of _var's descriptor *is* known to the linker, then it can
3682 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3683 /// a slight efficiency gain.
3685 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3686 SelectionDAG &DAG) const {
3687 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3690 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3691 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3694 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3695 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3697 // The first entry in the descriptor is a function pointer that we must call
3698 // to obtain the address of the variable.
3699 SDValue Chain = DAG.getEntryNode();
3700 SDValue FuncTLVGet = DAG.getLoad(
3701 MVT::i64, DL, Chain, DescAddr,
3702 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3703 /* Alignment = */ 8,
3704 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3705 MachineMemOperand::MODereferenceable);
3706 Chain = FuncTLVGet.getValue(1);
3708 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3709 MFI.setAdjustsStack(true);
3711 // TLS calls preserve all registers except those that absolutely must be
3712 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3714 const uint32_t *Mask =
3715 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3717 // Finally, we can make the call. This is just a degenerate version of a
3718 // normal AArch64 call node: x0 takes the address of the descriptor, and
3719 // returns the address of the variable in this thread.
3720 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3722 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3723 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3724 DAG.getRegisterMask(Mask), Chain.getValue(1));
3725 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3728 /// When accessing thread-local variables under either the general-dynamic or
3729 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3730 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3731 /// is a function pointer to carry out the resolution.
3733 /// The sequence is:
3734 /// adrp x0, :tlsdesc:var
3735 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3736 /// add x0, x0, #:tlsdesc_lo12:var
3737 /// .tlsdesccall var
3739 /// (TPIDR_EL0 offset now in x0)
3741 /// The above sequence must be produced unscheduled, to enable the linker to
3742 /// optimize/relax this sequence.
3743 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3744 /// above sequence, and expanded really late in the compilation flow, to ensure
3745 /// the sequence is produced as per above.
3746 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3748 SelectionDAG &DAG) const {
3749 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3751 SDValue Chain = DAG.getEntryNode();
3752 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3755 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3756 SDValue Glue = Chain.getValue(1);
3758 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3762 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3763 SelectionDAG &DAG) const {
3764 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3765 assert(Subtarget->useSmallAddressing() &&
3766 "ELF TLS only supported in small memory model");
3767 // Different choices can be made for the maximum size of the TLS area for a
3768 // module. For the small address model, the default TLS size is 16MiB and the
3769 // maximum TLS size is 4GiB.
3770 // FIXME: add -mtls-size command line option and make it control the 16MiB
3771 // vs. 4GiB code sequence generation.
3772 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3774 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3776 if (DAG.getTarget().Options.EmulatedTLS)
3777 return LowerToTLSEmulatedModel(GA, DAG);
3779 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3780 if (Model == TLSModel::LocalDynamic)
3781 Model = TLSModel::GeneralDynamic;
3785 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3787 const GlobalValue *GV = GA->getGlobal();
3789 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3791 if (Model == TLSModel::LocalExec) {
3792 SDValue HiVar = DAG.getTargetGlobalAddress(
3793 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3794 SDValue LoVar = DAG.getTargetGlobalAddress(
3796 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3798 SDValue TPWithOff_lo =
3799 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3801 DAG.getTargetConstant(0, DL, MVT::i32)),
3804 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3806 DAG.getTargetConstant(0, DL, MVT::i32)),
3809 } else if (Model == TLSModel::InitialExec) {
3810 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3811 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3812 } else if (Model == TLSModel::LocalDynamic) {
3813 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3814 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3815 // the beginning of the module's TLS region, followed by a DTPREL offset
3818 // These accesses will need deduplicating if there's more than one.
3819 AArch64FunctionInfo *MFI =
3820 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3821 MFI->incNumLocalDynamicTLSAccesses();
3823 // The call needs a relocation too for linker relaxation. It doesn't make
3824 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3826 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3829 // Now we can calculate the offset from TPIDR_EL0 to this module's
3830 // thread-local area.
3831 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3833 // Now use :dtprel_whatever: operations to calculate this variable's offset
3834 // in its thread-storage area.
3835 SDValue HiVar = DAG.getTargetGlobalAddress(
3836 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3837 SDValue LoVar = DAG.getTargetGlobalAddress(
3838 GV, DL, MVT::i64, 0,
3839 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3841 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3842 DAG.getTargetConstant(0, DL, MVT::i32)),
3844 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3845 DAG.getTargetConstant(0, DL, MVT::i32)),
3847 } else if (Model == TLSModel::GeneralDynamic) {
3848 // The call needs a relocation too for linker relaxation. It doesn't make
3849 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3852 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3854 // Finally we can make a call to calculate the offset from tpidr_el0.
3855 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3857 llvm_unreachable("Unsupported ELF TLS access model");
3859 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3862 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3863 SelectionDAG &DAG) const {
3864 if (Subtarget->isTargetDarwin())
3865 return LowerDarwinGlobalTLSAddress(Op, DAG);
3866 if (Subtarget->isTargetELF())
3867 return LowerELFGlobalTLSAddress(Op, DAG);
3869 llvm_unreachable("Unexpected platform trying to use TLS");
3872 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3873 SDValue Chain = Op.getOperand(0);
3874 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3875 SDValue LHS = Op.getOperand(2);
3876 SDValue RHS = Op.getOperand(3);
3877 SDValue Dest = Op.getOperand(4);
3880 // Handle f128 first, since lowering it will result in comparing the return
3881 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3882 // is expecting to deal with.
3883 if (LHS.getValueType() == MVT::f128) {
3884 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3886 // If softenSetCCOperands returned a scalar, we need to compare the result
3887 // against zero to select between true and false values.
3888 if (!RHS.getNode()) {
3889 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3894 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3896 unsigned Opc = LHS.getOpcode();
3897 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3898 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3899 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3900 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3901 "Unexpected condition code.");
3902 // Only lower legal XALUO ops.
3903 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3906 // The actual operation with overflow check.
3907 AArch64CC::CondCode OFCC;
3908 SDValue Value, Overflow;
3909 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3911 if (CC == ISD::SETNE)
3912 OFCC = getInvertedCondCode(OFCC);
3913 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3915 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3919 if (LHS.getValueType().isInteger()) {
3920 assert((LHS.getValueType() == RHS.getValueType()) &&
3921 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3923 // If the RHS of the comparison is zero, we can potentially fold this
3924 // to a specialized branch.
3925 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3926 if (RHSC && RHSC->getZExtValue() == 0) {
3927 if (CC == ISD::SETEQ) {
3928 // See if we can use a TBZ to fold in an AND as well.
3929 // TBZ has a smaller branch displacement than CBZ. If the offset is
3930 // out of bounds, a late MI-layer pass rewrites branches.
3931 // 403.gcc is an example that hits this case.
3932 if (LHS.getOpcode() == ISD::AND &&
3933 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3934 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3935 SDValue Test = LHS.getOperand(0);
3936 uint64_t Mask = LHS.getConstantOperandVal(1);
3937 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3938 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3942 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3943 } else if (CC == ISD::SETNE) {
3944 // See if we can use a TBZ to fold in an AND as well.
3945 // TBZ has a smaller branch displacement than CBZ. If the offset is
3946 // out of bounds, a late MI-layer pass rewrites branches.
3947 // 403.gcc is an example that hits this case.
3948 if (LHS.getOpcode() == ISD::AND &&
3949 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3950 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3951 SDValue Test = LHS.getOperand(0);
3952 uint64_t Mask = LHS.getConstantOperandVal(1);
3953 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3954 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3958 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3959 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3960 // Don't combine AND since emitComparison converts the AND to an ANDS
3961 // (a.k.a. TST) and the test in the test bit and branch instruction
3962 // becomes redundant. This would also increase register pressure.
3963 uint64_t Mask = LHS.getValueSizeInBits() - 1;
3964 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3965 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3968 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3969 LHS.getOpcode() != ISD::AND) {
3970 // Don't combine AND since emitComparison converts the AND to an ANDS
3971 // (a.k.a. TST) and the test in the test bit and branch instruction
3972 // becomes redundant. This would also increase register pressure.
3973 uint64_t Mask = LHS.getValueSizeInBits() - 1;
3974 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3975 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3979 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3980 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3984 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3986 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3987 // clean. Some of them require two branches to implement.
3988 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3989 AArch64CC::CondCode CC1, CC2;
3990 changeFPCCToAArch64CC(CC, CC1, CC2);
3991 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3993 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3994 if (CC2 != AArch64CC::AL) {
3995 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3996 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4003 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4004 SelectionDAG &DAG) const {
4005 EVT VT = Op.getValueType();
4008 SDValue In1 = Op.getOperand(0);
4009 SDValue In2 = Op.getOperand(1);
4010 EVT SrcVT = In2.getValueType();
4012 if (SrcVT.bitsLT(VT))
4013 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4014 else if (SrcVT.bitsGT(VT))
4015 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4020 SDValue VecVal1, VecVal2;
4021 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4023 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4024 EltMask = 0x80000000ULL;
4026 if (!VT.isVector()) {
4027 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4028 DAG.getUNDEF(VecVT), In1);
4029 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4030 DAG.getUNDEF(VecVT), In2);
4032 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4033 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4035 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4039 // We want to materialize a mask with the high bit set, but the AdvSIMD
4040 // immediate moves cannot materialize that in a single instruction for
4041 // 64-bit elements. Instead, materialize zero and then negate it.
4044 if (!VT.isVector()) {
4045 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4046 DAG.getUNDEF(VecVT), In1);
4047 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4048 DAG.getUNDEF(VecVT), In2);
4050 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4051 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4054 llvm_unreachable("Invalid type for copysign!");
4057 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4059 // If we couldn't materialize the mask above, then the mask vector will be
4060 // the zero vector, and we need to negate it here.
4061 if (VT == MVT::f64 || VT == MVT::v2f64) {
4062 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4063 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4064 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4068 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4071 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4072 else if (VT == MVT::f64)
4073 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4075 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4078 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4079 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
4080 Attribute::NoImplicitFloat))
4083 if (!Subtarget->hasNEON())
4086 // While there is no integer popcount instruction, it can
4087 // be more efficiently lowered to the following sequence that uses
4088 // AdvSIMD registers/instructions as long as the copies to/from
4089 // the AdvSIMD registers are cheap.
4090 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4091 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4092 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4093 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4094 SDValue Val = Op.getOperand(0);
4096 EVT VT = Op.getValueType();
4099 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4100 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4102 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4103 SDValue UaddLV = DAG.getNode(
4104 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4105 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4108 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4112 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4114 if (Op.getValueType().isVector())
4115 return LowerVSETCC(Op, DAG);
4117 SDValue LHS = Op.getOperand(0);
4118 SDValue RHS = Op.getOperand(1);
4119 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4122 // We chose ZeroOrOneBooleanContents, so use zero and one.
4123 EVT VT = Op.getValueType();
4124 SDValue TVal = DAG.getConstant(1, dl, VT);
4125 SDValue FVal = DAG.getConstant(0, dl, VT);
4127 // Handle f128 first, since one possible outcome is a normal integer
4128 // comparison which gets picked up by the next if statement.
4129 if (LHS.getValueType() == MVT::f128) {
4130 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4132 // If softenSetCCOperands returned a scalar, use it.
4133 if (!RHS.getNode()) {
4134 assert(LHS.getValueType() == Op.getValueType() &&
4135 "Unexpected setcc expansion!");
4140 if (LHS.getValueType().isInteger()) {
4143 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4145 // Note that we inverted the condition above, so we reverse the order of
4146 // the true and false operands here. This will allow the setcc to be
4147 // matched to a single CSINC instruction.
4148 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4151 // Now we know we're dealing with FP values.
4152 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4154 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4155 // and do the comparison.
4156 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4158 AArch64CC::CondCode CC1, CC2;
4159 changeFPCCToAArch64CC(CC, CC1, CC2);
4160 if (CC2 == AArch64CC::AL) {
4161 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4162 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4164 // Note that we inverted the condition above, so we reverse the order of
4165 // the true and false operands here. This will allow the setcc to be
4166 // matched to a single CSINC instruction.
4167 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4169 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4170 // totally clean. Some of them require two CSELs to implement. As is in
4171 // this case, we emit the first CSEL and then emit a second using the output
4172 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4174 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4175 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4177 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4179 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4180 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4184 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4185 SDValue RHS, SDValue TVal,
4186 SDValue FVal, const SDLoc &dl,
4187 SelectionDAG &DAG) const {
4188 // Handle f128 first, because it will result in a comparison of some RTLIB
4189 // call result against zero.
4190 if (LHS.getValueType() == MVT::f128) {
4191 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4193 // If softenSetCCOperands returned a scalar, we need to compare the result
4194 // against zero to select between true and false values.
4195 if (!RHS.getNode()) {
4196 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4201 // Also handle f16, for which we need to do a f32 comparison.
4202 if (LHS.getValueType() == MVT::f16) {
4203 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4204 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4207 // Next, handle integers.
4208 if (LHS.getValueType().isInteger()) {
4209 assert((LHS.getValueType() == RHS.getValueType()) &&
4210 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4212 unsigned Opcode = AArch64ISD::CSEL;
4214 // If both the TVal and the FVal are constants, see if we can swap them in
4215 // order to for a CSINV or CSINC out of them.
4216 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4217 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4219 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4220 std::swap(TVal, FVal);
4221 std::swap(CTVal, CFVal);
4222 CC = ISD::getSetCCInverse(CC, true);
4223 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4224 std::swap(TVal, FVal);
4225 std::swap(CTVal, CFVal);
4226 CC = ISD::getSetCCInverse(CC, true);
4227 } else if (TVal.getOpcode() == ISD::XOR) {
4228 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4229 // with a CSINV rather than a CSEL.
4230 if (isAllOnesConstant(TVal.getOperand(1))) {
4231 std::swap(TVal, FVal);
4232 std::swap(CTVal, CFVal);
4233 CC = ISD::getSetCCInverse(CC, true);
4235 } else if (TVal.getOpcode() == ISD::SUB) {
4236 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4237 // that we can match with a CSNEG rather than a CSEL.
4238 if (isNullConstant(TVal.getOperand(0))) {
4239 std::swap(TVal, FVal);
4240 std::swap(CTVal, CFVal);
4241 CC = ISD::getSetCCInverse(CC, true);
4243 } else if (CTVal && CFVal) {
4244 const int64_t TrueVal = CTVal->getSExtValue();
4245 const int64_t FalseVal = CFVal->getSExtValue();
4248 // If both TVal and FVal are constants, see if FVal is the
4249 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4250 // instead of a CSEL in that case.
4251 if (TrueVal == ~FalseVal) {
4252 Opcode = AArch64ISD::CSINV;
4253 } else if (TrueVal == -FalseVal) {
4254 Opcode = AArch64ISD::CSNEG;
4255 } else if (TVal.getValueType() == MVT::i32) {
4256 // If our operands are only 32-bit wide, make sure we use 32-bit
4257 // arithmetic for the check whether we can use CSINC. This ensures that
4258 // the addition in the check will wrap around properly in case there is
4259 // an overflow (which would not be the case if we do the check with
4260 // 64-bit arithmetic).
4261 const uint32_t TrueVal32 = CTVal->getZExtValue();
4262 const uint32_t FalseVal32 = CFVal->getZExtValue();
4264 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4265 Opcode = AArch64ISD::CSINC;
4267 if (TrueVal32 > FalseVal32) {
4271 // 64-bit check whether we can use CSINC.
4272 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4273 Opcode = AArch64ISD::CSINC;
4275 if (TrueVal > FalseVal) {
4280 // Swap TVal and FVal if necessary.
4282 std::swap(TVal, FVal);
4283 std::swap(CTVal, CFVal);
4284 CC = ISD::getSetCCInverse(CC, true);
4287 if (Opcode != AArch64ISD::CSEL) {
4288 // Drop FVal since we can get its value by simply inverting/negating
4294 // Avoid materializing a constant when possible by reusing a known value in
4295 // a register. However, don't perform this optimization if the known value
4296 // is one, zero or negative one in the case of a CSEL. We can always
4297 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4298 // FVal, respectively.
4299 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4300 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4301 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4302 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4303 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4304 // "a != C ? x : a" to avoid materializing C.
4305 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4307 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4309 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4310 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4311 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4312 // avoid materializing C.
4313 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4314 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4315 Opcode = AArch64ISD::CSINV;
4317 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4322 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4324 EVT VT = TVal.getValueType();
4325 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4328 // Now we know we're dealing with FP values.
4329 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4330 assert(LHS.getValueType() == RHS.getValueType());
4331 EVT VT = TVal.getValueType();
4332 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4334 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4335 // clean. Some of them require two CSELs to implement.
4336 AArch64CC::CondCode CC1, CC2;
4337 changeFPCCToAArch64CC(CC, CC1, CC2);
4339 if (DAG.getTarget().Options.UnsafeFPMath) {
4340 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4341 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4342 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4343 if (RHSVal && RHSVal->isZero()) {
4344 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4345 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4347 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4348 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4350 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4351 CFVal && CFVal->isZero() &&
4352 FVal.getValueType() == LHS.getValueType())
4357 // Emit first, and possibly only, CSEL.
4358 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4359 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4361 // If we need a second CSEL, emit it, using the output of the first as the
4362 // RHS. We're effectively OR'ing the two CC's together.
4363 if (CC2 != AArch64CC::AL) {
4364 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4365 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4368 // Otherwise, return the output of the first CSEL.
4372 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4373 SelectionDAG &DAG) const {
4374 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4375 SDValue LHS = Op.getOperand(0);
4376 SDValue RHS = Op.getOperand(1);
4377 SDValue TVal = Op.getOperand(2);
4378 SDValue FVal = Op.getOperand(3);
4380 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4383 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4384 SelectionDAG &DAG) const {
4385 SDValue CCVal = Op->getOperand(0);
4386 SDValue TVal = Op->getOperand(1);
4387 SDValue FVal = Op->getOperand(2);
4390 unsigned Opc = CCVal.getOpcode();
4391 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4393 if (CCVal.getResNo() == 1 &&
4394 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4395 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4396 // Only lower legal XALUO ops.
4397 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4400 AArch64CC::CondCode OFCC;
4401 SDValue Value, Overflow;
4402 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4403 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4405 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4409 // Lower it the same way as we would lower a SELECT_CC node.
4412 if (CCVal.getOpcode() == ISD::SETCC) {
4413 LHS = CCVal.getOperand(0);
4414 RHS = CCVal.getOperand(1);
4415 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4418 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4421 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4424 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4425 SelectionDAG &DAG) const {
4426 // Jump table entries as PC relative offsets. No additional tweaking
4427 // is necessary here. Just get the address of the jump table.
4428 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4430 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4431 !Subtarget->isTargetMachO()) {
4432 return getAddrLarge(JT, DAG);
4434 return getAddr(JT, DAG);
4437 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4438 SelectionDAG &DAG) const {
4439 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4441 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4442 // Use the GOT for the large code model on iOS.
4443 if (Subtarget->isTargetMachO()) {
4444 return getGOT(CP, DAG);
4446 return getAddrLarge(CP, DAG);
4448 return getAddr(CP, DAG);
4452 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4453 SelectionDAG &DAG) const {
4454 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4455 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4456 !Subtarget->isTargetMachO()) {
4457 return getAddrLarge(BA, DAG);
4459 return getAddr(BA, DAG);
4463 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4464 SelectionDAG &DAG) const {
4465 AArch64FunctionInfo *FuncInfo =
4466 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4469 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4470 getPointerTy(DAG.getDataLayout()));
4471 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4472 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4473 MachinePointerInfo(SV));
4476 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4477 SelectionDAG &DAG) const {
4478 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4479 // Standard, section B.3.
4480 MachineFunction &MF = DAG.getMachineFunction();
4481 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4482 auto PtrVT = getPointerTy(DAG.getDataLayout());
4485 SDValue Chain = Op.getOperand(0);
4486 SDValue VAList = Op.getOperand(1);
4487 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4488 SmallVector<SDValue, 4> MemOps;
4490 // void *__stack at offset 0
4491 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4492 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4493 MachinePointerInfo(SV), /* Alignment = */ 8));
4495 // void *__gr_top at offset 8
4496 int GPRSize = FuncInfo->getVarArgsGPRSize();
4498 SDValue GRTop, GRTopAddr;
4501 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4503 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4504 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4505 DAG.getConstant(GPRSize, DL, PtrVT));
4507 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4508 MachinePointerInfo(SV, 8),
4509 /* Alignment = */ 8));
4512 // void *__vr_top at offset 16
4513 int FPRSize = FuncInfo->getVarArgsFPRSize();
4515 SDValue VRTop, VRTopAddr;
4516 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4517 DAG.getConstant(16, DL, PtrVT));
4519 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4520 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4521 DAG.getConstant(FPRSize, DL, PtrVT));
4523 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4524 MachinePointerInfo(SV, 16),
4525 /* Alignment = */ 8));
4528 // int __gr_offs at offset 24
4529 SDValue GROffsAddr =
4530 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4531 MemOps.push_back(DAG.getStore(
4532 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4533 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4535 // int __vr_offs at offset 28
4536 SDValue VROffsAddr =
4537 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4538 MemOps.push_back(DAG.getStore(
4539 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4540 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4542 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4545 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4546 SelectionDAG &DAG) const {
4547 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4548 : LowerAAPCS_VASTART(Op, DAG);
4551 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4552 SelectionDAG &DAG) const {
4553 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4556 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4557 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4558 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4560 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4562 DAG.getConstant(VaListSize, DL, MVT::i32),
4563 8, false, false, false, MachinePointerInfo(DestSV),
4564 MachinePointerInfo(SrcSV));
4567 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4568 assert(Subtarget->isTargetDarwin() &&
4569 "automatic va_arg instruction only works on Darwin");
4571 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4572 EVT VT = Op.getValueType();
4574 SDValue Chain = Op.getOperand(0);
4575 SDValue Addr = Op.getOperand(1);
4576 unsigned Align = Op.getConstantOperandVal(3);
4577 auto PtrVT = getPointerTy(DAG.getDataLayout());
4579 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4580 Chain = VAList.getValue(1);
4583 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4584 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4585 DAG.getConstant(Align - 1, DL, PtrVT));
4586 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4587 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4590 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4591 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4593 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4594 // up to 64 bits. At the very least, we have to increase the striding of the
4595 // vaargs list to match this, and for FP values we need to introduce
4596 // FP_ROUND nodes as well.
4597 if (VT.isInteger() && !VT.isVector())
4599 bool NeedFPTrunc = false;
4600 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4605 // Increment the pointer, VAList, to the next vaarg
4606 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4607 DAG.getConstant(ArgSize, DL, PtrVT));
4608 // Store the incremented VAList to the legalized pointer
4610 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4612 // Load the actual argument out of the pointer VAList
4614 // Load the value as an f64.
4616 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4617 // Round the value down to an f32.
4618 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4619 DAG.getIntPtrConstant(1, DL));
4620 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4621 // Merge the rounded value with the chain output of the load.
4622 return DAG.getMergeValues(Ops, DL);
4625 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4628 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4629 SelectionDAG &DAG) const {
4630 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4631 MFI.setFrameAddressIsTaken(true);
4633 EVT VT = Op.getValueType();
4635 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4637 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4639 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4640 MachinePointerInfo());
4644 // FIXME? Maybe this could be a TableGen attribute on some registers and
4645 // this table could be generated automatically from RegInfo.
4646 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4647 SelectionDAG &DAG) const {
4648 unsigned Reg = StringSwitch<unsigned>(RegName)
4649 .Case("sp", AArch64::SP)
4650 .Case("x18", AArch64::X18)
4651 .Case("w18", AArch64::W18)
4653 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4654 !Subtarget->isX18Reserved())
4658 report_fatal_error(Twine("Invalid register name \""
4659 + StringRef(RegName) + "\"."));
4662 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4663 SelectionDAG &DAG) const {
4664 MachineFunction &MF = DAG.getMachineFunction();
4665 MachineFrameInfo &MFI = MF.getFrameInfo();
4666 MFI.setReturnAddressIsTaken(true);
4668 EVT VT = Op.getValueType();
4670 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4672 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4673 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4674 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4675 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4676 MachinePointerInfo());
4679 // Return LR, which contains the return address. Mark it an implicit live-in.
4680 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4681 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4684 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4685 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4686 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4687 SelectionDAG &DAG) const {
4688 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4689 EVT VT = Op.getValueType();
4690 unsigned VTBits = VT.getSizeInBits();
4692 SDValue ShOpLo = Op.getOperand(0);
4693 SDValue ShOpHi = Op.getOperand(1);
4694 SDValue ShAmt = Op.getOperand(2);
4695 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4697 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4699 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4700 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4701 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4703 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4704 // is "undef". We wanted 0, so CSEL it directly.
4705 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4706 ISD::SETEQ, dl, DAG);
4707 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4709 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4710 HiBitsForLo, CCVal, Cmp);
4712 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4713 DAG.getConstant(VTBits, dl, MVT::i64));
4715 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4716 SDValue LoForNormalShift =
4717 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4719 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4721 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4722 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4723 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4724 LoForNormalShift, CCVal, Cmp);
4726 // AArch64 shifts larger than the register width are wrapped rather than
4727 // clamped, so we can't just emit "hi >> x".
4728 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4729 SDValue HiForBigShift =
4731 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4732 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4733 : DAG.getConstant(0, dl, VT);
4734 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4735 HiForNormalShift, CCVal, Cmp);
4737 SDValue Ops[2] = { Lo, Hi };
4738 return DAG.getMergeValues(Ops, dl);
4741 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4742 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4743 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4744 SelectionDAG &DAG) const {
4745 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4746 EVT VT = Op.getValueType();
4747 unsigned VTBits = VT.getSizeInBits();
4749 SDValue ShOpLo = Op.getOperand(0);
4750 SDValue ShOpHi = Op.getOperand(1);
4751 SDValue ShAmt = Op.getOperand(2);
4753 assert(Op.getOpcode() == ISD::SHL_PARTS);
4754 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4755 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4756 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4758 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4759 // is "undef". We wanted 0, so CSEL it directly.
4760 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4761 ISD::SETEQ, dl, DAG);
4762 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4764 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4765 LoBitsForHi, CCVal, Cmp);
4767 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4768 DAG.getConstant(VTBits, dl, MVT::i64));
4769 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4770 SDValue HiForNormalShift =
4771 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4773 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4775 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4777 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4778 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4779 HiForNormalShift, CCVal, Cmp);
4781 // AArch64 shifts of larger than register sizes are wrapped rather than
4782 // clamped, so we can't just emit "lo << a" if a is too big.
4783 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4784 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4785 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4786 LoForNormalShift, CCVal, Cmp);
4788 SDValue Ops[2] = { Lo, Hi };
4789 return DAG.getMergeValues(Ops, dl);
4792 bool AArch64TargetLowering::isOffsetFoldingLegal(
4793 const GlobalAddressSDNode *GA) const {
4794 // The AArch64 target doesn't support folding offsets into global addresses.
4798 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4799 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4800 // FIXME: We should be able to handle f128 as well with a clever lowering.
4801 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4805 return AArch64_AM::getFP64Imm(Imm) != -1;
4806 else if (VT == MVT::f32)
4807 return AArch64_AM::getFP32Imm(Imm) != -1;
4811 //===----------------------------------------------------------------------===//
4812 // AArch64 Optimization Hooks
4813 //===----------------------------------------------------------------------===//
4815 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4816 SDValue Operand, SelectionDAG &DAG,
4818 EVT VT = Operand.getValueType();
4819 if (ST->hasNEON() &&
4820 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4821 VT == MVT::f32 || VT == MVT::v1f32 ||
4822 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4823 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4824 // For the reciprocal estimates, convergence is quadratic, so the number
4825 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4826 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4827 // the result for float (23 mantissa bits) is 2 and for double (52
4828 // mantissa bits) is 3.
4829 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4831 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4837 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4838 SelectionDAG &DAG, int Enabled,
4841 bool Reciprocal) const {
4842 if (Enabled == ReciprocalEstimate::Enabled ||
4843 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4844 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4847 EVT VT = Operand.getValueType();
4850 Flags.setUnsafeAlgebra(true);
4852 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4853 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4854 for (int i = ExtraSteps; i > 0; --i) {
4855 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4857 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
4858 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4862 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4864 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4865 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4867 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
4868 // Correct the result if the operand is 0.0.
4869 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4870 VT, Eq, Operand, Estimate);
4880 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4881 SelectionDAG &DAG, int Enabled,
4882 int &ExtraSteps) const {
4883 if (Enabled == ReciprocalEstimate::Enabled)
4884 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4887 EVT VT = Operand.getValueType();
4890 Flags.setUnsafeAlgebra(true);
4892 // Newton reciprocal iteration: E * (2 - X * E)
4893 // AArch64 reciprocal iteration instruction: (2 - M * N)
4894 for (int i = ExtraSteps; i > 0; --i) {
4895 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4897 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4907 //===----------------------------------------------------------------------===//
4908 // AArch64 Inline Assembly Support
4909 //===----------------------------------------------------------------------===//
4911 // Table of Constraints
4912 // TODO: This is the current set of constraints supported by ARM for the
4913 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4915 // r - A general register
4916 // w - An FP/SIMD register of some size in the range v0-v31
4917 // x - An FP/SIMD register of some size in the range v0-v15
4918 // I - Constant that can be used with an ADD instruction
4919 // J - Constant that can be used with a SUB instruction
4920 // K - Constant that can be used with a 32-bit logical instruction
4921 // L - Constant that can be used with a 64-bit logical instruction
4922 // M - Constant that can be used as a 32-bit MOV immediate
4923 // N - Constant that can be used as a 64-bit MOV immediate
4924 // Q - A memory reference with base register and no offset
4925 // S - A symbolic address
4926 // Y - Floating point constant zero
4927 // Z - Integer constant zero
4929 // Note that general register operands will be output using their 64-bit x
4930 // register name, whatever the size of the variable, unless the asm operand
4931 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4932 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4934 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4935 // At this point, we have to lower this constraint to something else, so we
4936 // lower it to an "r" or "w". However, by doing this we will force the result
4937 // to be in register, while the X constraint is much more permissive.
4939 // Although we are correct (we are free to emit anything, without
4940 // constraints), we might break use cases that would expect us to be more
4941 // efficient and emit something else.
4942 if (!Subtarget->hasFPARMv8())
4945 if (ConstraintVT.isFloatingPoint())
4948 if (ConstraintVT.isVector() &&
4949 (ConstraintVT.getSizeInBits() == 64 ||
4950 ConstraintVT.getSizeInBits() == 128))
4956 /// getConstraintType - Given a constraint letter, return the type of
4957 /// constraint it is for this target.
4958 AArch64TargetLowering::ConstraintType
4959 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4960 if (Constraint.size() == 1) {
4961 switch (Constraint[0]) {
4968 return C_RegisterClass;
4969 // An address with a single base register. Due to the way we
4970 // currently handle addresses it is the same as 'r'.
4975 return TargetLowering::getConstraintType(Constraint);
4978 /// Examine constraint type and operand type and determine a weight value.
4979 /// This object must already have been set up with the operand type
4980 /// and the current alternative constraint selected.
4981 TargetLowering::ConstraintWeight
4982 AArch64TargetLowering::getSingleConstraintMatchWeight(
4983 AsmOperandInfo &info, const char *constraint) const {
4984 ConstraintWeight weight = CW_Invalid;
4985 Value *CallOperandVal = info.CallOperandVal;
4986 // If we don't have a value, we can't do a match,
4987 // but allow it at the lowest weight.
4988 if (!CallOperandVal)
4990 Type *type = CallOperandVal->getType();
4991 // Look at the constraint type.
4992 switch (*constraint) {
4994 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4998 if (type->isFloatingPointTy() || type->isVectorTy())
4999 weight = CW_Register;
5002 weight = CW_Constant;
5008 std::pair<unsigned, const TargetRegisterClass *>
5009 AArch64TargetLowering::getRegForInlineAsmConstraint(
5010 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5011 if (Constraint.size() == 1) {
5012 switch (Constraint[0]) {
5014 if (VT.getSizeInBits() == 64)
5015 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5016 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5018 if (VT.getSizeInBits() == 16)
5019 return std::make_pair(0U, &AArch64::FPR16RegClass);
5020 if (VT.getSizeInBits() == 32)
5021 return std::make_pair(0U, &AArch64::FPR32RegClass);
5022 if (VT.getSizeInBits() == 64)
5023 return std::make_pair(0U, &AArch64::FPR64RegClass);
5024 if (VT.getSizeInBits() == 128)
5025 return std::make_pair(0U, &AArch64::FPR128RegClass);
5027 // The instructions that this constraint is designed for can
5028 // only take 128-bit registers so just use that regclass.
5030 if (VT.getSizeInBits() == 128)
5031 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5035 if (StringRef("{cc}").equals_lower(Constraint))
5036 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5038 // Use the default implementation in TargetLowering to convert the register
5039 // constraint into a member of a register class.
5040 std::pair<unsigned, const TargetRegisterClass *> Res;
5041 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5043 // Not found as a standard register?
5045 unsigned Size = Constraint.size();
5046 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5047 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5049 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5050 if (!Failed && RegNo >= 0 && RegNo <= 31) {
5051 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5052 // By default we'll emit v0-v31 for this unless there's a modifier where
5053 // we'll emit the correct register as well.
5054 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5055 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5056 Res.second = &AArch64::FPR64RegClass;
5058 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5059 Res.second = &AArch64::FPR128RegClass;
5068 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5069 /// vector. If it is invalid, don't add anything to Ops.
5070 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5071 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5072 SelectionDAG &DAG) const {
5075 // Currently only support length 1 constraints.
5076 if (Constraint.length() != 1)
5079 char ConstraintLetter = Constraint[0];
5080 switch (ConstraintLetter) {
5084 // This set of constraints deal with valid constants for various instructions.
5085 // Validate and return a target constant for them if we can.
5087 // 'z' maps to xzr or wzr so it needs an input of 0.
5088 if (!isNullConstant(Op))
5091 if (Op.getValueType() == MVT::i64)
5092 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5094 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5104 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5108 // Grab the value and do some validation.
5109 uint64_t CVal = C->getZExtValue();
5110 switch (ConstraintLetter) {
5111 // The I constraint applies only to simple ADD or SUB immediate operands:
5112 // i.e. 0 to 4095 with optional shift by 12
5113 // The J constraint applies only to ADD or SUB immediates that would be
5114 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5115 // instruction [or vice versa], in other words -1 to -4095 with optional
5116 // left shift by 12.
5118 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5122 uint64_t NVal = -C->getSExtValue();
5123 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5124 CVal = C->getSExtValue();
5129 // The K and L constraints apply *only* to logical immediates, including
5130 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5131 // been removed and MOV should be used). So these constraints have to
5132 // distinguish between bit patterns that are valid 32-bit or 64-bit
5133 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5134 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5137 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5141 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5144 // The M and N constraints are a superset of K and L respectively, for use
5145 // with the MOV (immediate) alias. As well as the logical immediates they
5146 // also match 32 or 64-bit immediates that can be loaded either using a
5147 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5148 // (M) or 64-bit 0x1234000000000000 (N) etc.
5149 // As a note some of this code is liberally stolen from the asm parser.
5151 if (!isUInt<32>(CVal))
5153 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5155 if ((CVal & 0xFFFF) == CVal)
5157 if ((CVal & 0xFFFF0000ULL) == CVal)
5159 uint64_t NCVal = ~(uint32_t)CVal;
5160 if ((NCVal & 0xFFFFULL) == NCVal)
5162 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5167 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5169 if ((CVal & 0xFFFFULL) == CVal)
5171 if ((CVal & 0xFFFF0000ULL) == CVal)
5173 if ((CVal & 0xFFFF00000000ULL) == CVal)
5175 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5177 uint64_t NCVal = ~CVal;
5178 if ((NCVal & 0xFFFFULL) == NCVal)
5180 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5182 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5184 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5192 // All assembler immediates are 64-bit integers.
5193 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5197 if (Result.getNode()) {
5198 Ops.push_back(Result);
5202 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5205 //===----------------------------------------------------------------------===//
5206 // AArch64 Advanced SIMD Support
5207 //===----------------------------------------------------------------------===//
5209 /// WidenVector - Given a value in the V64 register class, produce the
5210 /// equivalent value in the V128 register class.
5211 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5212 EVT VT = V64Reg.getValueType();
5213 unsigned NarrowSize = VT.getVectorNumElements();
5214 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5215 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5218 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5219 V64Reg, DAG.getConstant(0, DL, MVT::i32));
5222 /// getExtFactor - Determine the adjustment factor for the position when
5223 /// generating an "extract from vector registers" instruction.
5224 static unsigned getExtFactor(SDValue &V) {
5225 EVT EltType = V.getValueType().getVectorElementType();
5226 return EltType.getSizeInBits() / 8;
5229 /// NarrowVector - Given a value in the V128 register class, produce the
5230 /// equivalent value in the V64 register class.
5231 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5232 EVT VT = V128Reg.getValueType();
5233 unsigned WideSize = VT.getVectorNumElements();
5234 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5235 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5238 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5241 // Gather data to see if the operation can be modelled as a
5242 // shuffle in combination with VEXTs.
5243 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5244 SelectionDAG &DAG) const {
5245 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5247 EVT VT = Op.getValueType();
5248 unsigned NumElts = VT.getVectorNumElements();
5250 struct ShuffleSourceInfo {
5255 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5256 // be compatible with the shuffle we intend to construct. As a result
5257 // ShuffleVec will be some sliding window into the original Vec.
5260 // Code should guarantee that element i in Vec starts at element "WindowBase
5261 // + i * WindowScale in ShuffleVec".
5265 ShuffleSourceInfo(SDValue Vec)
5266 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5267 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5269 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5272 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5274 SmallVector<ShuffleSourceInfo, 2> Sources;
5275 for (unsigned i = 0; i < NumElts; ++i) {
5276 SDValue V = Op.getOperand(i);
5279 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5280 !isa<ConstantSDNode>(V.getOperand(1))) {
5281 // A shuffle can only come from building a vector from various
5282 // elements of other vectors, provided their indices are constant.
5286 // Add this element source to the list if it's not already there.
5287 SDValue SourceVec = V.getOperand(0);
5288 auto Source = find(Sources, SourceVec);
5289 if (Source == Sources.end())
5290 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5292 // Update the minimum and maximum lane number seen.
5293 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5294 Source->MinElt = std::min(Source->MinElt, EltNo);
5295 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5298 // Currently only do something sane when at most two source vectors
5300 if (Sources.size() > 2)
5303 // Find out the smallest element size among result and two sources, and use
5304 // it as element size to build the shuffle_vector.
5305 EVT SmallestEltTy = VT.getVectorElementType();
5306 for (auto &Source : Sources) {
5307 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5308 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5309 SmallestEltTy = SrcEltTy;
5312 unsigned ResMultiplier =
5313 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5314 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5315 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5317 // If the source vector is too wide or too narrow, we may nevertheless be able
5318 // to construct a compatible shuffle either by concatenating it with UNDEF or
5319 // extracting a suitable range of elements.
5320 for (auto &Src : Sources) {
5321 EVT SrcVT = Src.ShuffleVec.getValueType();
5323 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5326 // This stage of the search produces a source with the same element type as
5327 // the original, but with a total width matching the BUILD_VECTOR output.
5328 EVT EltVT = SrcVT.getVectorElementType();
5329 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5330 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5332 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5333 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5334 // We can pad out the smaller vector for free, so if it's part of a
5337 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5338 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5342 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5344 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5345 // Span too large for a VEXT to cope
5349 if (Src.MinElt >= NumSrcElts) {
5350 // The extraction can just take the second half
5352 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5353 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5354 Src.WindowBase = -NumSrcElts;
5355 } else if (Src.MaxElt < NumSrcElts) {
5356 // The extraction can just take the first half
5358 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5359 DAG.getConstant(0, dl, MVT::i64));
5361 // An actual VEXT is needed
5363 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5364 DAG.getConstant(0, dl, MVT::i64));
5366 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5367 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5368 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5370 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5372 DAG.getConstant(Imm, dl, MVT::i32));
5373 Src.WindowBase = -Src.MinElt;
5377 // Another possible incompatibility occurs from the vector element types. We
5378 // can fix this by bitcasting the source vectors to the same type we intend
5380 for (auto &Src : Sources) {
5381 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5382 if (SrcEltTy == SmallestEltTy)
5384 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5385 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5386 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5387 Src.WindowBase *= Src.WindowScale;
5390 // Final sanity check before we try to actually produce a shuffle.
5392 for (auto Src : Sources)
5393 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5396 // The stars all align, our next step is to produce the mask for the shuffle.
5397 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5398 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5399 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5400 SDValue Entry = Op.getOperand(i);
5401 if (Entry.isUndef())
5404 auto Src = find(Sources, Entry.getOperand(0));
5405 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5407 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5408 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5410 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5412 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5413 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5415 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5416 // starting at the appropriate offset.
5417 int *LaneMask = &Mask[i * ResMultiplier];
5419 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5420 ExtractBase += NumElts * (Src - Sources.begin());
5421 for (int j = 0; j < LanesDefined; ++j)
5422 LaneMask[j] = ExtractBase + j;
5425 // Final check before we try to produce nonsense...
5426 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5429 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5430 for (unsigned i = 0; i < Sources.size(); ++i)
5431 ShuffleOps[i] = Sources[i].ShuffleVec;
5433 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5434 ShuffleOps[1], Mask);
5435 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5438 // check if an EXT instruction can handle the shuffle mask when the
5439 // vector sources of the shuffle are the same.
5440 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5441 unsigned NumElts = VT.getVectorNumElements();
5443 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5449 // If this is a VEXT shuffle, the immediate value is the index of the first
5450 // element. The other shuffle indices must be the successive elements after
5452 unsigned ExpectedElt = Imm;
5453 for (unsigned i = 1; i < NumElts; ++i) {
5454 // Increment the expected index. If it wraps around, just follow it
5455 // back to index zero and keep going.
5457 if (ExpectedElt == NumElts)
5461 continue; // ignore UNDEF indices
5462 if (ExpectedElt != static_cast<unsigned>(M[i]))
5469 // check if an EXT instruction can handle the shuffle mask when the
5470 // vector sources of the shuffle are different.
5471 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5473 // Look for the first non-undef element.
5474 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5476 // Benefit form APInt to handle overflow when calculating expected element.
5477 unsigned NumElts = VT.getVectorNumElements();
5478 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5479 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5480 // The following shuffle indices must be the successive elements after the
5481 // first real element.
5482 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5483 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5484 if (FirstWrongElt != M.end())
5487 // The index of an EXT is the first element if it is not UNDEF.
5488 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5489 // value of the first element. E.g.
5490 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5491 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5492 // ExpectedElt is the last mask index plus 1.
5493 Imm = ExpectedElt.getZExtValue();
5495 // There are two difference cases requiring to reverse input vectors.
5496 // For example, for vector <4 x i32> we have the following cases,
5497 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5498 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5499 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5500 // to reverse two input vectors.
5509 /// isREVMask - Check if a vector shuffle corresponds to a REV
5510 /// instruction with the specified blocksize. (The order of the elements
5511 /// within each block of the vector is reversed.)
5512 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5513 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5514 "Only possible block sizes for REV are: 16, 32, 64");
5516 unsigned EltSz = VT.getScalarSizeInBits();
5520 unsigned NumElts = VT.getVectorNumElements();
5521 unsigned BlockElts = M[0] + 1;
5522 // If the first shuffle index is UNDEF, be optimistic.
5524 BlockElts = BlockSize / EltSz;
5526 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5529 for (unsigned i = 0; i < NumElts; ++i) {
5531 continue; // ignore UNDEF indices
5532 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5539 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5540 unsigned NumElts = VT.getVectorNumElements();
5541 WhichResult = (M[0] == 0 ? 0 : 1);
5542 unsigned Idx = WhichResult * NumElts / 2;
5543 for (unsigned i = 0; i != NumElts; i += 2) {
5544 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5545 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5553 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5554 unsigned NumElts = VT.getVectorNumElements();
5555 WhichResult = (M[0] == 0 ? 0 : 1);
5556 for (unsigned i = 0; i != NumElts; ++i) {
5558 continue; // ignore UNDEF indices
5559 if ((unsigned)M[i] != 2 * i + WhichResult)
5566 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5567 unsigned NumElts = VT.getVectorNumElements();
5568 WhichResult = (M[0] == 0 ? 0 : 1);
5569 for (unsigned i = 0; i < NumElts; i += 2) {
5570 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5571 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5577 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5578 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5579 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5580 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5581 unsigned NumElts = VT.getVectorNumElements();
5582 WhichResult = (M[0] == 0 ? 0 : 1);
5583 unsigned Idx = WhichResult * NumElts / 2;
5584 for (unsigned i = 0; i != NumElts; i += 2) {
5585 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5586 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5594 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5595 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5596 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5597 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5598 unsigned Half = VT.getVectorNumElements() / 2;
5599 WhichResult = (M[0] == 0 ? 0 : 1);
5600 for (unsigned j = 0; j != 2; ++j) {
5601 unsigned Idx = WhichResult;
5602 for (unsigned i = 0; i != Half; ++i) {
5603 int MIdx = M[i + j * Half];
5604 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5613 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5614 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5615 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5616 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5617 unsigned NumElts = VT.getVectorNumElements();
5618 WhichResult = (M[0] == 0 ? 0 : 1);
5619 for (unsigned i = 0; i < NumElts; i += 2) {
5620 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5621 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5627 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5628 bool &DstIsLeft, int &Anomaly) {
5629 if (M.size() != static_cast<size_t>(NumInputElements))
5632 int NumLHSMatch = 0, NumRHSMatch = 0;
5633 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5635 for (int i = 0; i < NumInputElements; ++i) {
5645 LastLHSMismatch = i;
5647 if (M[i] == i + NumInputElements)
5650 LastRHSMismatch = i;
5653 if (NumLHSMatch == NumInputElements - 1) {
5655 Anomaly = LastLHSMismatch;
5657 } else if (NumRHSMatch == NumInputElements - 1) {
5659 Anomaly = LastRHSMismatch;
5666 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5667 if (VT.getSizeInBits() != 128)
5670 unsigned NumElts = VT.getVectorNumElements();
5672 for (int I = 0, E = NumElts / 2; I != E; I++) {
5677 int Offset = NumElts / 2;
5678 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5679 if (Mask[I] != I + SplitLHS * Offset)
5686 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5688 EVT VT = Op.getValueType();
5689 SDValue V0 = Op.getOperand(0);
5690 SDValue V1 = Op.getOperand(1);
5691 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5693 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5694 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5697 bool SplitV0 = V0.getValueSizeInBits() == 128;
5699 if (!isConcatMask(Mask, VT, SplitV0))
5702 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5703 VT.getVectorNumElements() / 2);
5705 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5706 DAG.getConstant(0, DL, MVT::i64));
5708 if (V1.getValueSizeInBits() == 128) {
5709 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5710 DAG.getConstant(0, DL, MVT::i64));
5712 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5715 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5716 /// the specified operations to build the shuffle.
5717 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5718 SDValue RHS, SelectionDAG &DAG,
5720 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5721 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5722 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5725 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5734 OP_VUZPL, // VUZP, left result
5735 OP_VUZPR, // VUZP, right result
5736 OP_VZIPL, // VZIP, left result
5737 OP_VZIPR, // VZIP, right result
5738 OP_VTRNL, // VTRN, left result
5739 OP_VTRNR // VTRN, right result
5742 if (OpNum == OP_COPY) {
5743 if (LHSID == (1 * 9 + 2) * 9 + 3)
5745 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5749 SDValue OpLHS, OpRHS;
5750 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5751 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5752 EVT VT = OpLHS.getValueType();
5756 llvm_unreachable("Unknown shuffle opcode!");
5758 // VREV divides the vector in half and swaps within the half.
5759 if (VT.getVectorElementType() == MVT::i32 ||
5760 VT.getVectorElementType() == MVT::f32)
5761 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5762 // vrev <4 x i16> -> REV32
5763 if (VT.getVectorElementType() == MVT::i16 ||
5764 VT.getVectorElementType() == MVT::f16)
5765 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5766 // vrev <4 x i8> -> REV16
5767 assert(VT.getVectorElementType() == MVT::i8);
5768 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5773 EVT EltTy = VT.getVectorElementType();
5775 if (EltTy == MVT::i8)
5776 Opcode = AArch64ISD::DUPLANE8;
5777 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5778 Opcode = AArch64ISD::DUPLANE16;
5779 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5780 Opcode = AArch64ISD::DUPLANE32;
5781 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5782 Opcode = AArch64ISD::DUPLANE64;
5784 llvm_unreachable("Invalid vector element type?");
5786 if (VT.getSizeInBits() == 64)
5787 OpLHS = WidenVector(OpLHS, DAG);
5788 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5789 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5794 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5795 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5796 DAG.getConstant(Imm, dl, MVT::i32));
5799 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5802 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5805 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5808 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5811 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5814 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5819 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5820 SelectionDAG &DAG) {
5821 // Check to see if we can use the TBL instruction.
5822 SDValue V1 = Op.getOperand(0);
5823 SDValue V2 = Op.getOperand(1);
5826 EVT EltVT = Op.getValueType().getVectorElementType();
5827 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5829 SmallVector<SDValue, 8> TBLMask;
5830 for (int Val : ShuffleMask) {
5831 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5832 unsigned Offset = Byte + Val * BytesPerElt;
5833 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5837 MVT IndexVT = MVT::v8i8;
5838 unsigned IndexLen = 8;
5839 if (Op.getValueSizeInBits() == 128) {
5840 IndexVT = MVT::v16i8;
5844 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5845 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5848 if (V2.getNode()->isUndef()) {
5850 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5851 Shuffle = DAG.getNode(
5852 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5853 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5854 DAG.getBuildVector(IndexVT, DL,
5855 makeArrayRef(TBLMask.data(), IndexLen)));
5857 if (IndexLen == 8) {
5858 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5859 Shuffle = DAG.getNode(
5860 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5861 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5862 DAG.getBuildVector(IndexVT, DL,
5863 makeArrayRef(TBLMask.data(), IndexLen)));
5865 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5866 // cannot currently represent the register constraints on the input
5868 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5869 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5871 Shuffle = DAG.getNode(
5872 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5873 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5874 V2Cst, DAG.getBuildVector(IndexVT, DL,
5875 makeArrayRef(TBLMask.data(), IndexLen)));
5878 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5881 static unsigned getDUPLANEOp(EVT EltType) {
5882 if (EltType == MVT::i8)
5883 return AArch64ISD::DUPLANE8;
5884 if (EltType == MVT::i16 || EltType == MVT::f16)
5885 return AArch64ISD::DUPLANE16;
5886 if (EltType == MVT::i32 || EltType == MVT::f32)
5887 return AArch64ISD::DUPLANE32;
5888 if (EltType == MVT::i64 || EltType == MVT::f64)
5889 return AArch64ISD::DUPLANE64;
5891 llvm_unreachable("Invalid vector element type?");
5894 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5895 SelectionDAG &DAG) const {
5897 EVT VT = Op.getValueType();
5899 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5901 // Convert shuffles that are directly supported on NEON to target-specific
5902 // DAG nodes, instead of keeping them as shuffles and matching them again
5903 // during code selection. This is more efficient and avoids the possibility
5904 // of inconsistencies between legalization and selection.
5905 ArrayRef<int> ShuffleMask = SVN->getMask();
5907 SDValue V1 = Op.getOperand(0);
5908 SDValue V2 = Op.getOperand(1);
5910 if (SVN->isSplat()) {
5911 int Lane = SVN->getSplatIndex();
5912 // If this is undef splat, generate it via "just" vdup, if possible.
5916 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5917 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5919 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5920 // constant. If so, we can just reference the lane's definition directly.
5921 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5922 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5923 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5925 // Otherwise, duplicate from the lane of the input vector.
5926 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5928 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5929 // to make a vector of the same size as this SHUFFLE. We can ignore the
5930 // extract entirely, and canonicalise the concat using WidenVector.
5931 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5932 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5933 V1 = V1.getOperand(0);
5934 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5935 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5936 Lane -= Idx * VT.getVectorNumElements() / 2;
5937 V1 = WidenVector(V1.getOperand(Idx), DAG);
5938 } else if (VT.getSizeInBits() == 64)
5939 V1 = WidenVector(V1, DAG);
5941 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5944 if (isREVMask(ShuffleMask, VT, 64))
5945 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5946 if (isREVMask(ShuffleMask, VT, 32))
5947 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5948 if (isREVMask(ShuffleMask, VT, 16))
5949 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5951 bool ReverseEXT = false;
5953 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5956 Imm *= getExtFactor(V1);
5957 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5958 DAG.getConstant(Imm, dl, MVT::i32));
5959 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5960 Imm *= getExtFactor(V1);
5961 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5962 DAG.getConstant(Imm, dl, MVT::i32));
5965 unsigned WhichResult;
5966 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5967 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5968 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5970 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5971 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5972 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5974 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5975 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5976 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5979 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5980 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5981 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5983 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5984 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5985 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5987 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5988 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5989 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5992 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
5997 int NumInputElements = V1.getValueType().getVectorNumElements();
5998 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5999 SDValue DstVec = DstIsLeft ? V1 : V2;
6000 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6002 SDValue SrcVec = V1;
6003 int SrcLane = ShuffleMask[Anomaly];
6004 if (SrcLane >= NumInputElements) {
6006 SrcLane -= VT.getVectorNumElements();
6008 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6010 EVT ScalarVT = VT.getVectorElementType();
6012 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6013 ScalarVT = MVT::i32;
6016 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6017 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6021 // If the shuffle is not directly supported and it has 4 elements, use
6022 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6023 unsigned NumElts = VT.getVectorNumElements();
6025 unsigned PFIndexes[4];
6026 for (unsigned i = 0; i != 4; ++i) {
6027 if (ShuffleMask[i] < 0)
6030 PFIndexes[i] = ShuffleMask[i];
6033 // Compute the index in the perfect shuffle table.
6034 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6035 PFIndexes[2] * 9 + PFIndexes[3];
6036 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6037 unsigned Cost = (PFEntry >> 30);
6040 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6043 return GenerateTBL(Op, ShuffleMask, DAG);
6046 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6048 EVT VT = BVN->getValueType(0);
6049 APInt SplatBits, SplatUndef;
6050 unsigned SplatBitSize;
6052 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6053 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6055 for (unsigned i = 0; i < NumSplats; ++i) {
6056 CnstBits <<= SplatBitSize;
6057 UndefBits <<= SplatBitSize;
6058 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6059 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6068 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6069 SelectionDAG &DAG) const {
6070 BuildVectorSDNode *BVN =
6071 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6072 SDValue LHS = Op.getOperand(0);
6074 EVT VT = Op.getValueType();
6079 APInt CnstBits(VT.getSizeInBits(), 0);
6080 APInt UndefBits(VT.getSizeInBits(), 0);
6081 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6082 // We only have BIC vector immediate instruction, which is and-not.
6083 CnstBits = ~CnstBits;
6085 // We make use of a little bit of goto ickiness in order to avoid having to
6086 // duplicate the immediate matching logic for the undef toggled case.
6087 bool SecondTry = false;
6090 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6091 CnstBits = CnstBits.zextOrTrunc(64);
6092 uint64_t CnstVal = CnstBits.getZExtValue();
6094 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6095 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6096 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6097 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6098 DAG.getConstant(CnstVal, dl, MVT::i32),
6099 DAG.getConstant(0, dl, MVT::i32));
6100 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6103 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6104 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6105 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6106 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6107 DAG.getConstant(CnstVal, dl, MVT::i32),
6108 DAG.getConstant(8, dl, MVT::i32));
6109 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6112 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6113 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6114 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6115 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6116 DAG.getConstant(CnstVal, dl, MVT::i32),
6117 DAG.getConstant(16, dl, MVT::i32));
6118 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6121 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6122 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6123 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6124 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6125 DAG.getConstant(CnstVal, dl, MVT::i32),
6126 DAG.getConstant(24, dl, MVT::i32));
6127 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6130 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6131 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6132 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6133 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6134 DAG.getConstant(CnstVal, dl, MVT::i32),
6135 DAG.getConstant(0, dl, MVT::i32));
6136 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6139 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6140 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6141 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6142 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6143 DAG.getConstant(CnstVal, dl, MVT::i32),
6144 DAG.getConstant(8, dl, MVT::i32));
6145 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6152 CnstBits = ~UndefBits;
6156 // We can always fall back to a non-immediate AND.
6161 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6162 // consists of only the same constant int value, returned in reference arg
6164 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6165 uint64_t &ConstVal) {
6166 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6169 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6172 EVT VT = Bvec->getValueType(0);
6173 unsigned NumElts = VT.getVectorNumElements();
6174 for (unsigned i = 1; i < NumElts; ++i)
6175 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6177 ConstVal = FirstElt->getZExtValue();
6181 static unsigned getIntrinsicID(const SDNode *N) {
6182 unsigned Opcode = N->getOpcode();
6185 return Intrinsic::not_intrinsic;
6186 case ISD::INTRINSIC_WO_CHAIN: {
6187 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6188 if (IID < Intrinsic::num_intrinsics)
6190 return Intrinsic::not_intrinsic;
6195 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6196 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6197 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6198 // Also, logical shift right -> sri, with the same structure.
6199 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6200 EVT VT = N->getValueType(0);
6207 // Is the first op an AND?
6208 const SDValue And = N->getOperand(0);
6209 if (And.getOpcode() != ISD::AND)
6212 // Is the second op an shl or lshr?
6213 SDValue Shift = N->getOperand(1);
6214 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6215 // or AArch64ISD::VLSHR vector, #shift
6216 unsigned ShiftOpc = Shift.getOpcode();
6217 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6219 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6221 // Is the shift amount constant?
6222 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6226 // Is the and mask vector all constant?
6228 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6231 // Is C1 == ~C2, taking into account how much one can shift elements of a
6233 uint64_t C2 = C2node->getZExtValue();
6234 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6235 if (C2 > ElemSizeInBits)
6237 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6238 if ((C1 & ElemMask) != (~C2 & ElemMask))
6241 SDValue X = And.getOperand(0);
6242 SDValue Y = Shift.getOperand(0);
6245 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6247 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6248 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6249 Shift.getOperand(1));
6251 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6252 DEBUG(N->dump(&DAG));
6253 DEBUG(dbgs() << "into: \n");
6254 DEBUG(ResultSLI->dump(&DAG));
6260 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6261 SelectionDAG &DAG) const {
6262 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6263 if (EnableAArch64SlrGeneration) {
6264 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6268 BuildVectorSDNode *BVN =
6269 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6270 SDValue LHS = Op.getOperand(1);
6272 EVT VT = Op.getValueType();
6274 // OR commutes, so try swapping the operands.
6276 LHS = Op.getOperand(0);
6277 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6282 APInt CnstBits(VT.getSizeInBits(), 0);
6283 APInt UndefBits(VT.getSizeInBits(), 0);
6284 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6285 // We make use of a little bit of goto ickiness in order to avoid having to
6286 // duplicate the immediate matching logic for the undef toggled case.
6287 bool SecondTry = false;
6290 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6291 CnstBits = CnstBits.zextOrTrunc(64);
6292 uint64_t CnstVal = CnstBits.getZExtValue();
6294 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6295 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6296 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6297 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6298 DAG.getConstant(CnstVal, dl, MVT::i32),
6299 DAG.getConstant(0, dl, MVT::i32));
6300 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6303 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6304 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6305 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6306 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6307 DAG.getConstant(CnstVal, dl, MVT::i32),
6308 DAG.getConstant(8, dl, MVT::i32));
6309 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6312 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6313 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6314 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6315 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6316 DAG.getConstant(CnstVal, dl, MVT::i32),
6317 DAG.getConstant(16, dl, MVT::i32));
6318 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6321 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6322 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6323 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6324 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6325 DAG.getConstant(CnstVal, dl, MVT::i32),
6326 DAG.getConstant(24, dl, MVT::i32));
6327 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6330 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6331 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6332 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6333 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6334 DAG.getConstant(CnstVal, dl, MVT::i32),
6335 DAG.getConstant(0, dl, MVT::i32));
6336 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6339 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6340 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6341 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6342 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6343 DAG.getConstant(CnstVal, dl, MVT::i32),
6344 DAG.getConstant(8, dl, MVT::i32));
6345 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6352 CnstBits = UndefBits;
6356 // We can always fall back to a non-immediate OR.
6361 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6362 // be truncated to fit element width.
6363 static SDValue NormalizeBuildVector(SDValue Op,
6364 SelectionDAG &DAG) {
6365 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6367 EVT VT = Op.getValueType();
6368 EVT EltTy= VT.getVectorElementType();
6370 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6373 SmallVector<SDValue, 16> Ops;
6374 for (SDValue Lane : Op->ops()) {
6375 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6376 APInt LowBits(EltTy.getSizeInBits(),
6377 CstLane->getZExtValue());
6378 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6380 Ops.push_back(Lane);
6382 return DAG.getBuildVector(VT, dl, Ops);
6385 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6386 SelectionDAG &DAG) const {
6388 EVT VT = Op.getValueType();
6389 Op = NormalizeBuildVector(Op, DAG);
6390 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6392 APInt CnstBits(VT.getSizeInBits(), 0);
6393 APInt UndefBits(VT.getSizeInBits(), 0);
6394 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6395 // We make use of a little bit of goto ickiness in order to avoid having to
6396 // duplicate the immediate matching logic for the undef toggled case.
6397 bool SecondTry = false;
6400 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6401 CnstBits = CnstBits.zextOrTrunc(64);
6402 uint64_t CnstVal = CnstBits.getZExtValue();
6404 // Certain magic vector constants (used to express things like NOT
6405 // and NEG) are passed through unmodified. This allows codegen patterns
6406 // for these operations to match. Special-purpose patterns will lower
6407 // these immediates to MOVIs if it proves necessary.
6408 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6411 // The many faces of MOVI...
6412 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6413 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6414 if (VT.getSizeInBits() == 128) {
6415 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6416 DAG.getConstant(CnstVal, dl, MVT::i32));
6417 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6420 // Support the V64 version via subregister insertion.
6421 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6422 DAG.getConstant(CnstVal, dl, MVT::i32));
6423 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6426 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6427 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6428 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6429 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6430 DAG.getConstant(CnstVal, dl, MVT::i32),
6431 DAG.getConstant(0, dl, MVT::i32));
6432 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6435 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6436 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6437 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6438 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6439 DAG.getConstant(CnstVal, dl, MVT::i32),
6440 DAG.getConstant(8, dl, MVT::i32));
6441 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6444 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6445 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6446 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6447 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6448 DAG.getConstant(CnstVal, dl, MVT::i32),
6449 DAG.getConstant(16, dl, MVT::i32));
6450 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6453 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6454 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6455 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6456 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6457 DAG.getConstant(CnstVal, dl, MVT::i32),
6458 DAG.getConstant(24, dl, MVT::i32));
6459 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6462 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6463 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6464 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6465 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6466 DAG.getConstant(CnstVal, dl, MVT::i32),
6467 DAG.getConstant(0, dl, MVT::i32));
6468 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6471 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6472 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6473 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6474 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6475 DAG.getConstant(CnstVal, dl, MVT::i32),
6476 DAG.getConstant(8, dl, MVT::i32));
6477 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6480 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6481 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6482 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6483 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6484 DAG.getConstant(CnstVal, dl, MVT::i32),
6485 DAG.getConstant(264, dl, MVT::i32));
6486 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6489 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6490 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6491 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6492 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6493 DAG.getConstant(CnstVal, dl, MVT::i32),
6494 DAG.getConstant(272, dl, MVT::i32));
6495 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6498 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6499 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6500 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6501 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6502 DAG.getConstant(CnstVal, dl, MVT::i32));
6503 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6506 // The few faces of FMOV...
6507 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6508 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6509 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6510 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6511 DAG.getConstant(CnstVal, dl, MVT::i32));
6512 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6515 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6516 VT.getSizeInBits() == 128) {
6517 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6518 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6519 DAG.getConstant(CnstVal, dl, MVT::i32));
6520 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6523 // The many faces of MVNI...
6525 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6526 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6527 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6528 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6529 DAG.getConstant(CnstVal, dl, MVT::i32),
6530 DAG.getConstant(0, dl, MVT::i32));
6531 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6534 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6535 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6536 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6537 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6538 DAG.getConstant(CnstVal, dl, MVT::i32),
6539 DAG.getConstant(8, dl, MVT::i32));
6540 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6543 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6544 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6545 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6546 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6547 DAG.getConstant(CnstVal, dl, MVT::i32),
6548 DAG.getConstant(16, dl, MVT::i32));
6549 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6552 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6553 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6554 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6555 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6556 DAG.getConstant(CnstVal, dl, MVT::i32),
6557 DAG.getConstant(24, dl, MVT::i32));
6558 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6561 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6562 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6563 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6564 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6565 DAG.getConstant(CnstVal, dl, MVT::i32),
6566 DAG.getConstant(0, dl, MVT::i32));
6567 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6570 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6571 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6572 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6573 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6574 DAG.getConstant(CnstVal, dl, MVT::i32),
6575 DAG.getConstant(8, dl, MVT::i32));
6576 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6579 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6580 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6581 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6582 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6583 DAG.getConstant(CnstVal, dl, MVT::i32),
6584 DAG.getConstant(264, dl, MVT::i32));
6585 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6588 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6589 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6590 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6591 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6592 DAG.getConstant(CnstVal, dl, MVT::i32),
6593 DAG.getConstant(272, dl, MVT::i32));
6594 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6601 CnstBits = UndefBits;
6606 // Scan through the operands to find some interesting properties we can
6608 // 1) If only one value is used, we can use a DUP, or
6609 // 2) if only the low element is not undef, we can just insert that, or
6610 // 3) if only one constant value is used (w/ some non-constant lanes),
6611 // we can splat the constant value into the whole vector then fill
6612 // in the non-constant lanes.
6613 // 4) FIXME: If different constant values are used, but we can intelligently
6614 // select the values we'll be overwriting for the non-constant
6615 // lanes such that we can directly materialize the vector
6616 // some other way (MOVI, e.g.), we can be sneaky.
6617 unsigned NumElts = VT.getVectorNumElements();
6618 bool isOnlyLowElement = true;
6619 bool usesOnlyOneValue = true;
6620 bool usesOnlyOneConstantValue = true;
6621 bool isConstant = true;
6622 unsigned NumConstantLanes = 0;
6624 SDValue ConstantValue;
6625 for (unsigned i = 0; i < NumElts; ++i) {
6626 SDValue V = Op.getOperand(i);
6630 isOnlyLowElement = false;
6631 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6634 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6636 if (!ConstantValue.getNode())
6638 else if (ConstantValue != V)
6639 usesOnlyOneConstantValue = false;
6642 if (!Value.getNode())
6644 else if (V != Value)
6645 usesOnlyOneValue = false;
6648 if (!Value.getNode())
6649 return DAG.getUNDEF(VT);
6651 if (isOnlyLowElement)
6652 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6654 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6655 // i32 and try again.
6656 if (usesOnlyOneValue) {
6658 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6659 Value.getValueType() != VT)
6660 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6662 // This is actually a DUPLANExx operation, which keeps everything vectory.
6664 // DUPLANE works on 128-bit vectors, widen it if necessary.
6665 SDValue Lane = Value.getOperand(1);
6666 Value = Value.getOperand(0);
6667 if (Value.getValueSizeInBits() == 64)
6668 Value = WidenVector(Value, DAG);
6670 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6671 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6674 if (VT.getVectorElementType().isFloatingPoint()) {
6675 SmallVector<SDValue, 8> Ops;
6676 EVT EltTy = VT.getVectorElementType();
6677 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6678 "Unsupported floating-point vector type");
6679 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6680 for (unsigned i = 0; i < NumElts; ++i)
6681 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6682 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6683 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6684 Val = LowerBUILD_VECTOR(Val, DAG);
6686 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6690 // If there was only one constant value used and for more than one lane,
6691 // start by splatting that value, then replace the non-constant lanes. This
6692 // is better than the default, which will perform a separate initialization
6694 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6695 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6696 // Now insert the non-constant lanes.
6697 for (unsigned i = 0; i < NumElts; ++i) {
6698 SDValue V = Op.getOperand(i);
6699 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6700 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6701 // Note that type legalization likely mucked about with the VT of the
6702 // source operand, so we may have to convert it here before inserting.
6703 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6709 // If all elements are constants and the case above didn't get hit, fall back
6710 // to the default expansion, which will generate a load from the constant
6715 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6717 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6721 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6722 // know the default expansion would otherwise fall back on something even
6723 // worse. For a vector with one or two non-undef values, that's
6724 // scalar_to_vector for the elements followed by a shuffle (provided the
6725 // shuffle is valid for the target) and materialization element by element
6726 // on the stack followed by a load for everything else.
6727 if (!isConstant && !usesOnlyOneValue) {
6728 SDValue Vec = DAG.getUNDEF(VT);
6729 SDValue Op0 = Op.getOperand(0);
6732 // Use SCALAR_TO_VECTOR for lane zero to
6733 // a) Avoid a RMW dependency on the full vector register, and
6734 // b) Allow the register coalescer to fold away the copy if the
6735 // value is already in an S or D register, and we're forced to emit an
6736 // INSERT_SUBREG that we can't fold anywhere.
6738 // We also allow types like i8 and i16 which are illegal scalar but legal
6739 // vector element types. After type-legalization the inserted value is
6740 // extended (i32) and it is safe to cast them to the vector type by ignoring
6741 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6742 if (!Op0.isUndef()) {
6743 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
6746 for (; i < NumElts; ++i) {
6747 SDValue V = Op.getOperand(i);
6750 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6751 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6756 // Just use the default expansion. We failed to find a better alternative.
6760 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6761 SelectionDAG &DAG) const {
6762 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6764 // Check for non-constant or out of range lane.
6765 EVT VT = Op.getOperand(0).getValueType();
6766 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6767 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6771 // Insertion/extraction are legal for V128 types.
6772 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6773 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6777 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6778 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6781 // For V64 types, we perform insertion by expanding the value
6782 // to a V128 type and perform the insertion on that.
6784 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6785 EVT WideTy = WideVec.getValueType();
6787 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6788 Op.getOperand(1), Op.getOperand(2));
6789 // Re-narrow the resultant vector.
6790 return NarrowVector(Node, DAG);
6794 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6795 SelectionDAG &DAG) const {
6796 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6798 // Check for non-constant or out of range lane.
6799 EVT VT = Op.getOperand(0).getValueType();
6800 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6801 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6805 // Insertion/extraction are legal for V128 types.
6806 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6807 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6811 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6812 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6815 // For V64 types, we perform extraction by expanding the value
6816 // to a V128 type and perform the extraction on that.
6818 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6819 EVT WideTy = WideVec.getValueType();
6821 EVT ExtrTy = WideTy.getVectorElementType();
6822 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6825 // For extractions, we just return the result directly.
6826 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6830 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6831 SelectionDAG &DAG) const {
6832 EVT VT = Op.getOperand(0).getValueType();
6838 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6841 unsigned Val = Cst->getZExtValue();
6843 unsigned Size = Op.getValueSizeInBits();
6845 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6849 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6851 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6857 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6859 if (VT.getVectorNumElements() == 4 &&
6860 (VT.is128BitVector() || VT.is64BitVector())) {
6861 unsigned PFIndexes[4];
6862 for (unsigned i = 0; i != 4; ++i) {
6866 PFIndexes[i] = M[i];
6869 // Compute the index in the perfect shuffle table.
6870 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6871 PFIndexes[2] * 9 + PFIndexes[3];
6872 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6873 unsigned Cost = (PFEntry >> 30);
6881 unsigned DummyUnsigned;
6883 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6884 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6885 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6886 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6887 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6888 isZIPMask(M, VT, DummyUnsigned) ||
6889 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6890 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6891 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6892 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6893 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6896 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6897 /// operand of a vector shift operation, where all the elements of the
6898 /// build_vector must have the same constant integer value.
6899 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6900 // Ignore bit_converts.
6901 while (Op.getOpcode() == ISD::BITCAST)
6902 Op = Op.getOperand(0);
6903 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6904 APInt SplatBits, SplatUndef;
6905 unsigned SplatBitSize;
6907 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6908 HasAnyUndefs, ElementBits) ||
6909 SplatBitSize > ElementBits)
6911 Cnt = SplatBits.getSExtValue();
6915 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6916 /// operand of a vector shift left operation. That value must be in the range:
6917 /// 0 <= Value < ElementBits for a left shift; or
6918 /// 0 <= Value <= ElementBits for a long left shift.
6919 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6920 assert(VT.isVector() && "vector shift count is not a vector type");
6921 int64_t ElementBits = VT.getScalarSizeInBits();
6922 if (!getVShiftImm(Op, ElementBits, Cnt))
6924 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6927 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6928 /// operand of a vector shift right operation. The value must be in the range:
6929 /// 1 <= Value <= ElementBits for a right shift; or
6930 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6931 assert(VT.isVector() && "vector shift count is not a vector type");
6932 int64_t ElementBits = VT.getScalarSizeInBits();
6933 if (!getVShiftImm(Op, ElementBits, Cnt))
6935 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6938 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6939 SelectionDAG &DAG) const {
6940 EVT VT = Op.getValueType();
6944 if (!Op.getOperand(1).getValueType().isVector())
6946 unsigned EltSize = VT.getScalarSizeInBits();
6948 switch (Op.getOpcode()) {
6950 llvm_unreachable("unexpected shift opcode");
6953 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6954 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6955 DAG.getConstant(Cnt, DL, MVT::i32));
6956 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6957 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6959 Op.getOperand(0), Op.getOperand(1));
6962 // Right shift immediate
6963 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6965 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6966 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6967 DAG.getConstant(Cnt, DL, MVT::i32));
6970 // Right shift register. Note, there is not a shift right register
6971 // instruction, but the shift left register instruction takes a signed
6972 // value, where negative numbers specify a right shift.
6973 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6974 : Intrinsic::aarch64_neon_ushl;
6975 // negate the shift amount
6976 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6977 SDValue NegShiftLeft =
6978 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6979 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6981 return NegShiftLeft;
6987 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6988 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6989 const SDLoc &dl, SelectionDAG &DAG) {
6990 EVT SrcVT = LHS.getValueType();
6991 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6992 "function only supposed to emit natural comparisons");
6994 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6995 APInt CnstBits(VT.getSizeInBits(), 0);
6996 APInt UndefBits(VT.getSizeInBits(), 0);
6997 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6998 bool IsZero = IsCnst && (CnstBits == 0);
7000 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7004 case AArch64CC::NE: {
7007 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7009 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7010 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7014 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7015 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7018 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7019 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7022 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7023 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7026 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7027 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7031 // If we ignore NaNs then we can use to the MI implementation.
7035 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7036 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7043 case AArch64CC::NE: {
7046 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7048 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7049 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7053 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7054 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7057 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7058 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7061 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7062 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7065 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7066 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7068 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7070 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7073 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7074 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7076 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7078 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7082 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7083 SelectionDAG &DAG) const {
7084 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7085 SDValue LHS = Op.getOperand(0);
7086 SDValue RHS = Op.getOperand(1);
7087 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7090 if (LHS.getValueType().getVectorElementType().isInteger()) {
7091 assert(LHS.getValueType() == RHS.getValueType());
7092 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7094 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7095 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7098 if (LHS.getValueType().getVectorElementType() == MVT::f16)
7101 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7102 LHS.getValueType().getVectorElementType() == MVT::f64);
7104 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7105 // clean. Some of them require two branches to implement.
7106 AArch64CC::CondCode CC1, CC2;
7108 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7110 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7112 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7116 if (CC2 != AArch64CC::AL) {
7118 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7119 if (!Cmp2.getNode())
7122 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7125 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7128 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7133 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7134 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7135 /// specified in the intrinsic calls.
7136 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7138 unsigned Intrinsic) const {
7139 auto &DL = I.getModule()->getDataLayout();
7140 switch (Intrinsic) {
7141 case Intrinsic::aarch64_neon_ld2:
7142 case Intrinsic::aarch64_neon_ld3:
7143 case Intrinsic::aarch64_neon_ld4:
7144 case Intrinsic::aarch64_neon_ld1x2:
7145 case Intrinsic::aarch64_neon_ld1x3:
7146 case Intrinsic::aarch64_neon_ld1x4:
7147 case Intrinsic::aarch64_neon_ld2lane:
7148 case Intrinsic::aarch64_neon_ld3lane:
7149 case Intrinsic::aarch64_neon_ld4lane:
7150 case Intrinsic::aarch64_neon_ld2r:
7151 case Intrinsic::aarch64_neon_ld3r:
7152 case Intrinsic::aarch64_neon_ld4r: {
7153 Info.opc = ISD::INTRINSIC_W_CHAIN;
7154 // Conservatively set memVT to the entire set of vectors loaded.
7155 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7156 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7157 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7160 Info.vol = false; // volatile loads with NEON intrinsics not supported
7161 Info.readMem = true;
7162 Info.writeMem = false;
7165 case Intrinsic::aarch64_neon_st2:
7166 case Intrinsic::aarch64_neon_st3:
7167 case Intrinsic::aarch64_neon_st4:
7168 case Intrinsic::aarch64_neon_st1x2:
7169 case Intrinsic::aarch64_neon_st1x3:
7170 case Intrinsic::aarch64_neon_st1x4:
7171 case Intrinsic::aarch64_neon_st2lane:
7172 case Intrinsic::aarch64_neon_st3lane:
7173 case Intrinsic::aarch64_neon_st4lane: {
7174 Info.opc = ISD::INTRINSIC_VOID;
7175 // Conservatively set memVT to the entire set of vectors stored.
7176 unsigned NumElts = 0;
7177 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7178 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7179 if (!ArgTy->isVectorTy())
7181 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7183 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7184 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7187 Info.vol = false; // volatile stores with NEON intrinsics not supported
7188 Info.readMem = false;
7189 Info.writeMem = true;
7192 case Intrinsic::aarch64_ldaxr:
7193 case Intrinsic::aarch64_ldxr: {
7194 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7195 Info.opc = ISD::INTRINSIC_W_CHAIN;
7196 Info.memVT = MVT::getVT(PtrTy->getElementType());
7197 Info.ptrVal = I.getArgOperand(0);
7199 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7201 Info.readMem = true;
7202 Info.writeMem = false;
7205 case Intrinsic::aarch64_stlxr:
7206 case Intrinsic::aarch64_stxr: {
7207 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7208 Info.opc = ISD::INTRINSIC_W_CHAIN;
7209 Info.memVT = MVT::getVT(PtrTy->getElementType());
7210 Info.ptrVal = I.getArgOperand(1);
7212 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7214 Info.readMem = false;
7215 Info.writeMem = true;
7218 case Intrinsic::aarch64_ldaxp:
7219 case Intrinsic::aarch64_ldxp:
7220 Info.opc = ISD::INTRINSIC_W_CHAIN;
7221 Info.memVT = MVT::i128;
7222 Info.ptrVal = I.getArgOperand(0);
7226 Info.readMem = true;
7227 Info.writeMem = false;
7229 case Intrinsic::aarch64_stlxp:
7230 case Intrinsic::aarch64_stxp:
7231 Info.opc = ISD::INTRINSIC_W_CHAIN;
7232 Info.memVT = MVT::i128;
7233 Info.ptrVal = I.getArgOperand(2);
7237 Info.readMem = false;
7238 Info.writeMem = true;
7247 // Truncations from 64-bit GPR to 32-bit GPR is free.
7248 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7249 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7251 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7252 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7253 return NumBits1 > NumBits2;
7255 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7256 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7258 unsigned NumBits1 = VT1.getSizeInBits();
7259 unsigned NumBits2 = VT2.getSizeInBits();
7260 return NumBits1 > NumBits2;
7263 /// Check if it is profitable to hoist instruction in then/else to if.
7264 /// Not profitable if I and it's user can form a FMA instruction
7265 /// because we prefer FMSUB/FMADD.
7266 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7267 if (I->getOpcode() != Instruction::FMul)
7270 if (!I->hasOneUse())
7273 Instruction *User = I->user_back();
7276 !(User->getOpcode() == Instruction::FSub ||
7277 User->getOpcode() == Instruction::FAdd))
7280 const TargetOptions &Options = getTargetMachine().Options;
7281 const DataLayout &DL = I->getModule()->getDataLayout();
7282 EVT VT = getValueType(DL, User->getOperand(0)->getType());
7284 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7285 isOperationLegalOrCustom(ISD::FMA, VT) &&
7286 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7287 Options.UnsafeFPMath));
7290 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7292 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7293 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7295 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7296 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7297 return NumBits1 == 32 && NumBits2 == 64;
7299 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7300 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7302 unsigned NumBits1 = VT1.getSizeInBits();
7303 unsigned NumBits2 = VT2.getSizeInBits();
7304 return NumBits1 == 32 && NumBits2 == 64;
7307 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7308 EVT VT1 = Val.getValueType();
7309 if (isZExtFree(VT1, VT2)) {
7313 if (Val.getOpcode() != ISD::LOAD)
7316 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7317 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7318 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7319 VT1.getSizeInBits() <= 32);
7322 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7323 if (isa<FPExtInst>(Ext))
7326 // Vector types are next free.
7327 if (Ext->getType()->isVectorTy())
7330 for (const Use &U : Ext->uses()) {
7331 // The extension is free if we can fold it with a left shift in an
7332 // addressing mode or an arithmetic operation: add, sub, and cmp.
7334 // Is there a shift?
7335 const Instruction *Instr = cast<Instruction>(U.getUser());
7337 // Is this a constant shift?
7338 switch (Instr->getOpcode()) {
7339 case Instruction::Shl:
7340 if (!isa<ConstantInt>(Instr->getOperand(1)))
7343 case Instruction::GetElementPtr: {
7344 gep_type_iterator GTI = gep_type_begin(Instr);
7345 auto &DL = Ext->getModule()->getDataLayout();
7346 std::advance(GTI, U.getOperandNo()-1);
7347 Type *IdxTy = GTI.getIndexedType();
7348 // This extension will end up with a shift because of the scaling factor.
7349 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7350 // Get the shift amount based on the scaling factor:
7351 // log2(sizeof(IdxTy)) - log2(8).
7353 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7354 // Is the constant foldable in the shift of the addressing mode?
7355 // I.e., shift amount is between 1 and 4 inclusive.
7356 if (ShiftAmt == 0 || ShiftAmt > 4)
7360 case Instruction::Trunc:
7361 // Check if this is a noop.
7362 // trunc(sext ty1 to ty2) to ty1.
7363 if (Instr->getType() == Ext->getOperand(0)->getType())
7370 // At this point we can use the bfm family, so this extension is free
7376 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7377 unsigned &RequiredAligment) const {
7378 if (!LoadedType.isSimple() ||
7379 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7381 // Cyclone supports unaligned accesses.
7382 RequiredAligment = 0;
7383 unsigned NumBits = LoadedType.getSizeInBits();
7384 return NumBits == 32 || NumBits == 64;
7387 /// A helper function for determining the number of interleaved accesses we
7388 /// will generate when lowering accesses of the given type.
7390 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7391 const DataLayout &DL) const {
7392 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7395 bool AArch64TargetLowering::isLegalInterleavedAccessType(
7396 VectorType *VecTy, const DataLayout &DL) const {
7398 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7399 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7401 // Ensure the number of vector elements is greater than 1.
7402 if (VecTy->getNumElements() < 2)
7405 // Ensure the element type is legal.
7406 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7409 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7410 // 128 will be split into multiple interleaved accesses.
7411 return VecSize == 64 || VecSize % 128 == 0;
7414 /// \brief Lower an interleaved load into a ldN intrinsic.
7416 /// E.g. Lower an interleaved load (Factor = 2):
7417 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7418 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7419 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7422 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7423 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7424 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7425 bool AArch64TargetLowering::lowerInterleavedLoad(
7426 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7427 ArrayRef<unsigned> Indices, unsigned Factor) const {
7428 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7429 "Invalid interleave factor");
7430 assert(!Shuffles.empty() && "Empty shufflevector input");
7431 assert(Shuffles.size() == Indices.size() &&
7432 "Unmatched number of shufflevectors and indices");
7434 const DataLayout &DL = LI->getModule()->getDataLayout();
7436 VectorType *VecTy = Shuffles[0]->getType();
7438 // Skip if we do not have NEON and skip illegal vector types. We can
7439 // "legalize" wide vector types into multiple interleaved accesses as long as
7440 // the vector types are divisible by 128.
7441 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
7444 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7446 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7447 // load integer vectors first and then convert to pointer vectors.
7448 Type *EltTy = VecTy->getVectorElementType();
7449 if (EltTy->isPointerTy())
7451 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7453 IRBuilder<> Builder(LI);
7455 // The base address of the load.
7456 Value *BaseAddr = LI->getPointerOperand();
7459 // If we're going to generate more than one load, reset the sub-vector type
7460 // to something legal.
7461 VecTy = VectorType::get(VecTy->getVectorElementType(),
7462 VecTy->getVectorNumElements() / NumLoads);
7464 // We will compute the pointer operand of each load from the original base
7465 // address using GEPs. Cast the base address to a pointer to the scalar
7467 BaseAddr = Builder.CreateBitCast(
7468 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7469 LI->getPointerAddressSpace()));
7472 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7473 Type *Tys[2] = {VecTy, PtrTy};
7474 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7475 Intrinsic::aarch64_neon_ld3,
7476 Intrinsic::aarch64_neon_ld4};
7478 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7480 // Holds sub-vectors extracted from the load intrinsic return values. The
7481 // sub-vectors are associated with the shufflevector instructions they will
7483 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
7485 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
7487 // If we're generating more than one load, compute the base address of
7488 // subsequent loads as an offset from the previous.
7490 BaseAddr = Builder.CreateConstGEP1_32(
7491 BaseAddr, VecTy->getVectorNumElements() * Factor);
7493 CallInst *LdN = Builder.CreateCall(
7494 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
7496 // Extract and store the sub-vectors returned by the load intrinsic.
7497 for (unsigned i = 0; i < Shuffles.size(); i++) {
7498 ShuffleVectorInst *SVI = Shuffles[i];
7499 unsigned Index = Indices[i];
7501 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7503 // Convert the integer vector to pointer vector if the element is pointer.
7504 if (EltTy->isPointerTy())
7505 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7507 SubVecs[SVI].push_back(SubVec);
7511 // Replace uses of the shufflevector instructions with the sub-vectors
7512 // returned by the load intrinsic. If a shufflevector instruction is
7513 // associated with more than one sub-vector, those sub-vectors will be
7514 // concatenated into a single wide vector.
7515 for (ShuffleVectorInst *SVI : Shuffles) {
7516 auto &SubVec = SubVecs[SVI];
7518 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7519 SVI->replaceAllUsesWith(WideVec);
7525 /// \brief Lower an interleaved store into a stN intrinsic.
7527 /// E.g. Lower an interleaved store (Factor = 3):
7528 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7529 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7530 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7533 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7534 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7535 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7536 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7538 /// Note that the new shufflevectors will be removed and we'll only generate one
7539 /// st3 instruction in CodeGen.
7541 /// Example for a more general valid mask (Factor 3). Lower:
7542 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7543 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7544 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7547 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7548 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7549 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7550 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7551 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7552 ShuffleVectorInst *SVI,
7553 unsigned Factor) const {
7554 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7555 "Invalid interleave factor");
7557 VectorType *VecTy = SVI->getType();
7558 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7559 "Invalid interleaved store");
7561 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7562 Type *EltTy = VecTy->getVectorElementType();
7563 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7565 const DataLayout &DL = SI->getModule()->getDataLayout();
7567 // Skip if we do not have NEON and skip illegal vector types. We can
7568 // "legalize" wide vector types into multiple interleaved accesses as long as
7569 // the vector types are divisible by 128.
7570 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
7573 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7575 Value *Op0 = SVI->getOperand(0);
7576 Value *Op1 = SVI->getOperand(1);
7577 IRBuilder<> Builder(SI);
7579 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7580 // vectors to integer vectors.
7581 if (EltTy->isPointerTy()) {
7582 Type *IntTy = DL.getIntPtrType(EltTy);
7583 unsigned NumOpElts =
7584 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7586 // Convert to the corresponding integer vector.
7587 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7588 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7589 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7591 SubVecTy = VectorType::get(IntTy, LaneLen);
7594 // The base address of the store.
7595 Value *BaseAddr = SI->getPointerOperand();
7597 if (NumStores > 1) {
7598 // If we're going to generate more than one store, reset the lane length
7599 // and sub-vector type to something legal.
7600 LaneLen /= NumStores;
7601 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7603 // We will compute the pointer operand of each store from the original base
7604 // address using GEPs. Cast the base address to a pointer to the scalar
7606 BaseAddr = Builder.CreateBitCast(
7607 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7608 SI->getPointerAddressSpace()));
7611 auto Mask = SVI->getShuffleMask();
7613 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7614 Type *Tys[2] = {SubVecTy, PtrTy};
7615 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7616 Intrinsic::aarch64_neon_st3,
7617 Intrinsic::aarch64_neon_st4};
7619 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7621 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
7623 SmallVector<Value *, 5> Ops;
7625 // Split the shufflevector operands into sub vectors for the new stN call.
7626 for (unsigned i = 0; i < Factor; i++) {
7627 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7628 if (Mask[IdxI] >= 0) {
7629 Ops.push_back(Builder.CreateShuffleVector(
7630 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7632 unsigned StartMask = 0;
7633 for (unsigned j = 1; j < LaneLen; j++) {
7634 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7635 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7636 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7640 // Note: Filling undef gaps with random elements is ok, since
7641 // those elements were being written anyway (with undefs).
7642 // In the case of all undefs we're defaulting to using elems from 0
7643 // Note: StartMask cannot be negative, it's checked in
7644 // isReInterleaveMask
7645 Ops.push_back(Builder.CreateShuffleVector(
7646 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7650 // If we generating more than one store, we compute the base address of
7651 // subsequent stores as an offset from the previous.
7653 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7655 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7656 Builder.CreateCall(StNFunc, Ops);
7661 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7662 unsigned AlignCheck) {
7663 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7664 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7667 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7668 unsigned SrcAlign, bool IsMemset,
7671 MachineFunction &MF) const {
7672 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7673 // instruction to materialize the v2i64 zero and one store (with restrictive
7674 // addressing mode). Just do two i64 store of zero-registers.
7676 const Function *F = MF.getFunction();
7677 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7678 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7679 (memOpAlign(SrcAlign, DstAlign, 16) ||
7680 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7684 (memOpAlign(SrcAlign, DstAlign, 8) ||
7685 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7689 (memOpAlign(SrcAlign, DstAlign, 4) ||
7690 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7696 // 12-bit optionally shifted immediates are legal for adds.
7697 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7698 // Avoid UB for INT64_MIN.
7699 if (Immed == std::numeric_limits<int64_t>::min())
7701 // Same encoding for add/sub, just flip the sign.
7702 Immed = std::abs(Immed);
7703 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7706 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7707 // immediates is the same as for an add or a sub.
7708 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7709 return isLegalAddImmediate(Immed);
7712 /// isLegalAddressingMode - Return true if the addressing mode represented
7713 /// by AM is legal for this target, for a load/store of the specified type.
7714 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7715 const AddrMode &AM, Type *Ty,
7716 unsigned AS) const {
7717 // AArch64 has five basic addressing modes:
7719 // reg + 9-bit signed offset
7720 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7722 // reg + SIZE_IN_BYTES * reg
7724 // No global is ever allowed as a base.
7728 // No reg+reg+imm addressing.
7729 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7732 // check reg + imm case:
7733 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7734 uint64_t NumBytes = 0;
7735 if (Ty->isSized()) {
7736 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7737 NumBytes = NumBits / 8;
7738 if (!isPowerOf2_64(NumBits))
7743 int64_t Offset = AM.BaseOffs;
7745 // 9-bit signed offset
7746 if (isInt<9>(Offset))
7749 // 12-bit unsigned offset
7750 unsigned shift = Log2_64(NumBytes);
7751 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7752 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7753 (Offset >> shift) << shift == Offset)
7758 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7760 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7763 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7764 const AddrMode &AM, Type *Ty,
7765 unsigned AS) const {
7766 // Scaling factors are not free at all.
7767 // Operands | Rt Latency
7768 // -------------------------------------------
7770 // -------------------------------------------
7771 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7772 // Rt, [Xn, Wm, <extend> #imm] |
7773 if (isLegalAddressingMode(DL, AM, Ty, AS))
7774 // Scale represents reg2 * scale, thus account for 1 if
7775 // it is not equal to 0 or 1.
7776 return AM.Scale != 0 && AM.Scale != 1;
7780 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7781 VT = VT.getScalarType();
7786 switch (VT.getSimpleVT().SimpleTy) {
7798 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7799 // LR is a callee-save register, but we must treat it as clobbered by any call
7800 // site. Hence we include LR in the scratch registers, which are in turn added
7801 // as implicit-defs for stackmaps and patchpoints.
7802 static const MCPhysReg ScratchRegs[] = {
7803 AArch64::X16, AArch64::X17, AArch64::LR, 0
7809 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7810 EVT VT = N->getValueType(0);
7811 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7812 // it with shift to let it be lowered to UBFX.
7813 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7814 isa<ConstantSDNode>(N->getOperand(1))) {
7815 uint64_t TruncMask = N->getConstantOperandVal(1);
7816 if (isMask_64(TruncMask) &&
7817 N->getOperand(0).getOpcode() == ISD::SRL &&
7818 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7824 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7826 assert(Ty->isIntegerTy());
7828 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7832 int64_t Val = Imm.getSExtValue();
7833 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7836 if ((int64_t)Val < 0)
7839 Val &= (1LL << 32) - 1;
7841 unsigned LZ = countLeadingZeros((uint64_t)Val);
7842 unsigned Shift = (63 - LZ) / 16;
7843 // MOVZ is free so return true for one or fewer MOVK.
7847 /// Turn vector tests of the signbit in the form of:
7848 /// xor (sra X, elt_size(X)-1), -1
7851 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7852 const AArch64Subtarget *Subtarget) {
7853 EVT VT = N->getValueType(0);
7854 if (!Subtarget->hasNEON() || !VT.isVector())
7857 // There must be a shift right algebraic before the xor, and the xor must be a
7859 SDValue Shift = N->getOperand(0);
7860 SDValue Ones = N->getOperand(1);
7861 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7862 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7865 // The shift should be smearing the sign bit across each vector element.
7866 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7867 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7868 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7871 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7874 // Generate SUBS and CSEL for integer abs.
7875 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7876 EVT VT = N->getValueType(0);
7878 SDValue N0 = N->getOperand(0);
7879 SDValue N1 = N->getOperand(1);
7882 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7883 // and change it to SUB and CSEL.
7884 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7885 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7886 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7887 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7888 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7889 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7891 // Generate SUBS & CSEL.
7893 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7894 N0.getOperand(0), DAG.getConstant(0, DL, VT));
7895 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7896 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7897 SDValue(Cmp.getNode(), 1));
7902 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7903 TargetLowering::DAGCombinerInfo &DCI,
7904 const AArch64Subtarget *Subtarget) {
7905 if (DCI.isBeforeLegalizeOps())
7908 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7911 return performIntegerAbsCombine(N, DAG);
7915 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7917 std::vector<SDNode *> *Created) const {
7918 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7919 if (isIntDivCheap(N->getValueType(0), Attr))
7920 return SDValue(N,0); // Lower SDIV as SDIV
7922 // fold (sdiv X, pow2)
7923 EVT VT = N->getValueType(0);
7924 if ((VT != MVT::i32 && VT != MVT::i64) ||
7925 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7929 SDValue N0 = N->getOperand(0);
7930 unsigned Lg2 = Divisor.countTrailingZeros();
7931 SDValue Zero = DAG.getConstant(0, DL, VT);
7932 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7934 // Add (N0 < 0) ? Pow2 - 1 : 0;
7936 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7937 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7938 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7941 Created->push_back(Cmp.getNode());
7942 Created->push_back(Add.getNode());
7943 Created->push_back(CSel.getNode());
7948 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7950 // If we're dividing by a positive value, we're done. Otherwise, we must
7951 // negate the result.
7952 if (Divisor.isNonNegative())
7956 Created->push_back(SRA.getNode());
7957 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7960 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7961 TargetLowering::DAGCombinerInfo &DCI,
7962 const AArch64Subtarget *Subtarget) {
7963 if (DCI.isBeforeLegalizeOps())
7966 // The below optimizations require a constant RHS.
7967 if (!isa<ConstantSDNode>(N->getOperand(1)))
7970 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7971 const APInt &ConstValue = C->getAPIntValue();
7973 // Multiplication of a power of two plus/minus one can be done more
7974 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7975 // future CPUs have a cheaper MADD instruction, this may need to be
7976 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7977 // 64-bit is 5 cycles, so this is always a win.
7978 // More aggressively, some multiplications N0 * C can be lowered to
7979 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7980 // e.g. 6=3*2=(2+1)*2.
7981 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7982 // which equals to (1+2)*16-(1+2).
7983 SDValue N0 = N->getOperand(0);
7984 // TrailingZeroes is used to test if the mul can be lowered to
7986 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7987 if (TrailingZeroes) {
7988 // Conservatively do not lower to shift+add+shift if the mul might be
7989 // folded into smul or umul.
7990 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7991 isZeroExtended(N0.getNode(), DAG)))
7993 // Conservatively do not lower to shift+add+shift if the mul might be
7994 // folded into madd or msub.
7995 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7996 N->use_begin()->getOpcode() == ISD::SUB))
7999 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8000 // and shift+add+shift.
8001 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8003 unsigned ShiftAmt, AddSubOpc;
8004 // Is the shifted value the LHS operand of the add/sub?
8005 bool ShiftValUseIsN0 = true;
8006 // Do we need to negate the result?
8007 bool NegateResult = false;
8009 if (ConstValue.isNonNegative()) {
8010 // (mul x, 2^N + 1) => (add (shl x, N), x)
8011 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8012 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8013 APInt SCVMinus1 = ShiftedConstValue - 1;
8014 APInt CVPlus1 = ConstValue + 1;
8015 if (SCVMinus1.isPowerOf2()) {
8016 ShiftAmt = SCVMinus1.logBase2();
8017 AddSubOpc = ISD::ADD;
8018 } else if (CVPlus1.isPowerOf2()) {
8019 ShiftAmt = CVPlus1.logBase2();
8020 AddSubOpc = ISD::SUB;
8024 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8025 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8026 APInt CVNegPlus1 = -ConstValue + 1;
8027 APInt CVNegMinus1 = -ConstValue - 1;
8028 if (CVNegPlus1.isPowerOf2()) {
8029 ShiftAmt = CVNegPlus1.logBase2();
8030 AddSubOpc = ISD::SUB;
8031 ShiftValUseIsN0 = false;
8032 } else if (CVNegMinus1.isPowerOf2()) {
8033 ShiftAmt = CVNegMinus1.logBase2();
8034 AddSubOpc = ISD::ADD;
8035 NegateResult = true;
8041 EVT VT = N->getValueType(0);
8042 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8043 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8045 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8046 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8047 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8048 assert(!(NegateResult && TrailingZeroes) &&
8049 "NegateResult and TrailingZeroes cannot both be true for now.");
8050 // Negate the result.
8052 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8053 // Shift the result.
8055 return DAG.getNode(ISD::SHL, DL, VT, Res,
8056 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8060 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8061 SelectionDAG &DAG) {
8062 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8063 // optimize away operation when it's from a constant.
8065 // The general transformation is:
8066 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8067 // AND(VECTOR_CMP(x,y), constant2)
8068 // constant2 = UNARYOP(constant)
8070 // Early exit if this isn't a vector operation, the operand of the
8071 // unary operation isn't a bitwise AND, or if the sizes of the operations
8073 EVT VT = N->getValueType(0);
8074 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8075 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8076 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8079 // Now check that the other operand of the AND is a constant. We could
8080 // make the transformation for non-constant splats as well, but it's unclear
8081 // that would be a benefit as it would not eliminate any operations, just
8082 // perform one more step in scalar code before moving to the vector unit.
8083 if (BuildVectorSDNode *BV =
8084 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8085 // Bail out if the vector isn't a constant.
8086 if (!BV->isConstant())
8089 // Everything checks out. Build up the new and improved node.
8091 EVT IntVT = BV->getValueType(0);
8092 // Create a new constant of the appropriate type for the transformed
8094 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8095 // The AND node needs bitcasts to/from an integer vector type around it.
8096 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8097 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8098 N->getOperand(0)->getOperand(0), MaskConst);
8099 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8106 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8107 const AArch64Subtarget *Subtarget) {
8108 // First try to optimize away the conversion when it's conditionally from
8109 // a constant. Vectors only.
8110 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8113 EVT VT = N->getValueType(0);
8114 if (VT != MVT::f32 && VT != MVT::f64)
8117 // Only optimize when the source and destination types have the same width.
8118 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8121 // If the result of an integer load is only used by an integer-to-float
8122 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8123 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8124 SDValue N0 = N->getOperand(0);
8125 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8126 // Do not change the width of a volatile load.
8127 !cast<LoadSDNode>(N0)->isVolatile()) {
8128 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8129 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8130 LN0->getPointerInfo(), LN0->getAlignment(),
8131 LN0->getMemOperand()->getFlags());
8133 // Make sure successors of the original load stay after it by updating them
8134 // to use the new Chain.
8135 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8138 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8139 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8145 /// Fold a floating-point multiply by power of two into floating-point to
8146 /// fixed-point conversion.
8147 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8148 TargetLowering::DAGCombinerInfo &DCI,
8149 const AArch64Subtarget *Subtarget) {
8150 if (!Subtarget->hasNEON())
8153 SDValue Op = N->getOperand(0);
8154 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8155 Op.getOpcode() != ISD::FMUL)
8158 SDValue ConstVec = Op->getOperand(1);
8159 if (!isa<BuildVectorSDNode>(ConstVec))
8162 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8163 uint32_t FloatBits = FloatTy.getSizeInBits();
8164 if (FloatBits != 32 && FloatBits != 64)
8167 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8168 uint32_t IntBits = IntTy.getSizeInBits();
8169 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8172 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8173 if (IntBits > FloatBits)
8176 BitVector UndefElements;
8177 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8178 int32_t Bits = IntBits == 64 ? 64 : 32;
8179 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8180 if (C == -1 || C == 0 || C > Bits)
8184 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8189 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8192 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8196 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8199 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8200 "Illegal vector type after legalization");
8203 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8204 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8205 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8207 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8208 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8209 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8210 // We can handle smaller integers by generating an extra trunc.
8211 if (IntBits < FloatBits)
8212 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8217 /// Fold a floating-point divide by power of two into fixed-point to
8218 /// floating-point conversion.
8219 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
8220 TargetLowering::DAGCombinerInfo &DCI,
8221 const AArch64Subtarget *Subtarget) {
8222 if (!Subtarget->hasNEON())
8225 SDValue Op = N->getOperand(0);
8226 unsigned Opc = Op->getOpcode();
8227 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8228 !Op.getOperand(0).getValueType().isSimple() ||
8229 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8232 SDValue ConstVec = N->getOperand(1);
8233 if (!isa<BuildVectorSDNode>(ConstVec))
8236 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8237 int32_t IntBits = IntTy.getSizeInBits();
8238 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8241 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8242 int32_t FloatBits = FloatTy.getSizeInBits();
8243 if (FloatBits != 32 && FloatBits != 64)
8246 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8247 if (IntBits > FloatBits)
8250 BitVector UndefElements;
8251 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8252 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8253 if (C == -1 || C == 0 || C > FloatBits)
8257 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8262 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8265 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8269 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8273 SDValue ConvInput = Op.getOperand(0);
8274 bool IsSigned = Opc == ISD::SINT_TO_FP;
8275 if (IntBits < FloatBits)
8276 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8279 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8280 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8281 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8282 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8283 DAG.getConstant(C, DL, MVT::i32));
8286 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8287 /// searches for and classifies those shifts.
8288 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8290 if (N.getOpcode() == ISD::SHL)
8292 else if (N.getOpcode() == ISD::SRL)
8297 if (!isa<ConstantSDNode>(N.getOperand(1)))
8300 ShiftAmount = N->getConstantOperandVal(1);
8301 Src = N->getOperand(0);
8305 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8306 /// registers viewed as a high/low pair. This function looks for the pattern:
8307 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8308 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
8310 static SDValue tryCombineToEXTR(SDNode *N,
8311 TargetLowering::DAGCombinerInfo &DCI) {
8312 SelectionDAG &DAG = DCI.DAG;
8314 EVT VT = N->getValueType(0);
8316 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8318 if (VT != MVT::i32 && VT != MVT::i64)
8322 uint32_t ShiftLHS = 0;
8323 bool LHSFromHi = false;
8324 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8328 uint32_t ShiftRHS = 0;
8329 bool RHSFromHi = false;
8330 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8333 // If they're both trying to come from the high part of the register, they're
8334 // not really an EXTR.
8335 if (LHSFromHi == RHSFromHi)
8338 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8342 std::swap(LHS, RHS);
8343 std::swap(ShiftLHS, ShiftRHS);
8346 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8347 DAG.getConstant(ShiftRHS, DL, MVT::i64));
8350 static SDValue tryCombineToBSL(SDNode *N,
8351 TargetLowering::DAGCombinerInfo &DCI) {
8352 EVT VT = N->getValueType(0);
8353 SelectionDAG &DAG = DCI.DAG;
8359 SDValue N0 = N->getOperand(0);
8360 if (N0.getOpcode() != ISD::AND)
8363 SDValue N1 = N->getOperand(1);
8364 if (N1.getOpcode() != ISD::AND)
8367 // We only have to look for constant vectors here since the general, variable
8368 // case can be handled in TableGen.
8369 unsigned Bits = VT.getScalarSizeInBits();
8370 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8371 for (int i = 1; i >= 0; --i)
8372 for (int j = 1; j >= 0; --j) {
8373 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8374 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8378 bool FoundMatch = true;
8379 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8380 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8381 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8383 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8390 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8391 N0->getOperand(1 - i), N1->getOperand(1 - j));
8397 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8398 const AArch64Subtarget *Subtarget) {
8399 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8400 SelectionDAG &DAG = DCI.DAG;
8401 EVT VT = N->getValueType(0);
8403 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8406 if (SDValue Res = tryCombineToEXTR(N, DCI))
8409 if (SDValue Res = tryCombineToBSL(N, DCI))
8415 static SDValue performSRLCombine(SDNode *N,
8416 TargetLowering::DAGCombinerInfo &DCI) {
8417 SelectionDAG &DAG = DCI.DAG;
8418 EVT VT = N->getValueType(0);
8419 if (VT != MVT::i32 && VT != MVT::i64)
8422 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8423 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8424 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8425 SDValue N0 = N->getOperand(0);
8426 if (N0.getOpcode() == ISD::BSWAP) {
8428 SDValue N1 = N->getOperand(1);
8429 SDValue N00 = N0.getOperand(0);
8430 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8431 uint64_t ShiftAmt = C->getZExtValue();
8432 if (VT == MVT::i32 && ShiftAmt == 16 &&
8433 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8434 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8435 if (VT == MVT::i64 && ShiftAmt == 32 &&
8436 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8437 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8443 static SDValue performBitcastCombine(SDNode *N,
8444 TargetLowering::DAGCombinerInfo &DCI,
8445 SelectionDAG &DAG) {
8446 // Wait 'til after everything is legalized to try this. That way we have
8447 // legal vector types and such.
8448 if (DCI.isBeforeLegalizeOps())
8451 // Remove extraneous bitcasts around an extract_subvector.
8453 // (v4i16 (bitconvert
8454 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8456 // (extract_subvector ((v8i16 ...), (i64 4)))
8458 // Only interested in 64-bit vectors as the ultimate result.
8459 EVT VT = N->getValueType(0);
8462 if (VT.getSimpleVT().getSizeInBits() != 64)
8464 // Is the operand an extract_subvector starting at the beginning or halfway
8465 // point of the vector? A low half may also come through as an
8466 // EXTRACT_SUBREG, so look for that, too.
8467 SDValue Op0 = N->getOperand(0);
8468 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8469 !(Op0->isMachineOpcode() &&
8470 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8472 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8473 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8474 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8476 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8477 if (idx != AArch64::dsub)
8479 // The dsub reference is equivalent to a lane zero subvector reference.
8482 // Look through the bitcast of the input to the extract.
8483 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8485 SDValue Source = Op0->getOperand(0)->getOperand(0);
8486 // If the source type has twice the number of elements as our destination
8487 // type, we know this is an extract of the high or low half of the vector.
8488 EVT SVT = Source->getValueType(0);
8489 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8492 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8494 // Create the simplified form to just extract the low or high half of the
8495 // vector directly rather than bothering with the bitcasts.
8497 unsigned NumElements = VT.getVectorNumElements();
8499 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8500 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8502 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8503 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8509 static SDValue performConcatVectorsCombine(SDNode *N,
8510 TargetLowering::DAGCombinerInfo &DCI,
8511 SelectionDAG &DAG) {
8513 EVT VT = N->getValueType(0);
8514 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8516 // Optimize concat_vectors of truncated vectors, where the intermediate
8517 // type is illegal, to avoid said illegality, e.g.,
8518 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8519 // (v2i16 (truncate (v2i64)))))
8521 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8522 // (v4i32 (bitcast (v2i64))),
8524 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8525 // on both input and result type, so we might generate worse code.
8526 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8527 if (N->getNumOperands() == 2 &&
8528 N0->getOpcode() == ISD::TRUNCATE &&
8529 N1->getOpcode() == ISD::TRUNCATE) {
8530 SDValue N00 = N0->getOperand(0);
8531 SDValue N10 = N1->getOperand(0);
8532 EVT N00VT = N00.getValueType();
8534 if (N00VT == N10.getValueType() &&
8535 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8536 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8537 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8538 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8539 for (size_t i = 0; i < Mask.size(); ++i)
8541 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8542 DAG.getVectorShuffle(
8544 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8545 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8549 // Wait 'til after everything is legalized to try this. That way we have
8550 // legal vector types and such.
8551 if (DCI.isBeforeLegalizeOps())
8554 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8555 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8556 // canonicalise to that.
8557 if (N0 == N1 && VT.getVectorNumElements() == 2) {
8558 assert(VT.getScalarSizeInBits() == 64);
8559 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8560 DAG.getConstant(0, dl, MVT::i64));
8563 // Canonicalise concat_vectors so that the right-hand vector has as few
8564 // bit-casts as possible before its real operation. The primary matching
8565 // destination for these operations will be the narrowing "2" instructions,
8566 // which depend on the operation being performed on this right-hand vector.
8568 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8570 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8572 if (N1->getOpcode() != ISD::BITCAST)
8574 SDValue RHS = N1->getOperand(0);
8575 MVT RHSTy = RHS.getValueType().getSimpleVT();
8576 // If the RHS is not a vector, this is not the pattern we're looking for.
8577 if (!RHSTy.isVector())
8580 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8582 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8583 RHSTy.getVectorNumElements() * 2);
8584 return DAG.getNode(ISD::BITCAST, dl, VT,
8585 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8586 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8590 static SDValue tryCombineFixedPointConvert(SDNode *N,
8591 TargetLowering::DAGCombinerInfo &DCI,
8592 SelectionDAG &DAG) {
8593 // Wait 'til after everything is legalized to try this. That way we have
8594 // legal vector types and such.
8595 if (DCI.isBeforeLegalizeOps())
8597 // Transform a scalar conversion of a value from a lane extract into a
8598 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8599 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8600 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8602 // The second form interacts better with instruction selection and the
8603 // register allocator to avoid cross-class register copies that aren't
8604 // coalescable due to a lane reference.
8606 // Check the operand and see if it originates from a lane extract.
8607 SDValue Op1 = N->getOperand(1);
8608 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8609 // Yep, no additional predication needed. Perform the transform.
8610 SDValue IID = N->getOperand(0);
8611 SDValue Shift = N->getOperand(2);
8612 SDValue Vec = Op1.getOperand(0);
8613 SDValue Lane = Op1.getOperand(1);
8614 EVT ResTy = N->getValueType(0);
8618 // The vector width should be 128 bits by the time we get here, even
8619 // if it started as 64 bits (the extract_vector handling will have
8621 assert(Vec.getValueSizeInBits() == 128 &&
8622 "unexpected vector size on extract_vector_elt!");
8623 if (Vec.getValueType() == MVT::v4i32)
8624 VecResTy = MVT::v4f32;
8625 else if (Vec.getValueType() == MVT::v2i64)
8626 VecResTy = MVT::v2f64;
8628 llvm_unreachable("unexpected vector type!");
8631 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8632 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8637 // AArch64 high-vector "long" operations are formed by performing the non-high
8638 // version on an extract_subvector of each operand which gets the high half:
8640 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8642 // However, there are cases which don't have an extract_high explicitly, but
8643 // have another operation that can be made compatible with one for free. For
8646 // (dupv64 scalar) --> (extract_high (dup128 scalar))
8648 // This routine does the actual conversion of such DUPs, once outer routines
8649 // have determined that everything else is in order.
8650 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8652 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8653 switch (N.getOpcode()) {
8654 case AArch64ISD::DUP:
8655 case AArch64ISD::DUPLANE8:
8656 case AArch64ISD::DUPLANE16:
8657 case AArch64ISD::DUPLANE32:
8658 case AArch64ISD::DUPLANE64:
8659 case AArch64ISD::MOVI:
8660 case AArch64ISD::MOVIshift:
8661 case AArch64ISD::MOVIedit:
8662 case AArch64ISD::MOVImsl:
8663 case AArch64ISD::MVNIshift:
8664 case AArch64ISD::MVNImsl:
8667 // FMOV could be supported, but isn't very useful, as it would only occur
8668 // if you passed a bitcast' floating point immediate to an eligible long
8669 // integer op (addl, smull, ...).
8673 MVT NarrowTy = N.getSimpleValueType();
8674 if (!NarrowTy.is64BitVector())
8677 MVT ElementTy = NarrowTy.getVectorElementType();
8678 unsigned NumElems = NarrowTy.getVectorNumElements();
8679 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8682 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8683 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8684 DAG.getConstant(NumElems, dl, MVT::i64));
8687 static bool isEssentiallyExtractSubvector(SDValue N) {
8688 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8691 return N.getOpcode() == ISD::BITCAST &&
8692 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8695 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8696 struct GenericSetCCInfo {
8697 const SDValue *Opnd0;
8698 const SDValue *Opnd1;
8702 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8703 struct AArch64SetCCInfo {
8705 AArch64CC::CondCode CC;
8708 /// \brief Helper structure to keep track of SetCC information.
8710 GenericSetCCInfo Generic;
8711 AArch64SetCCInfo AArch64;
8714 /// \brief Helper structure to be able to read SetCC information. If set to
8715 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8716 /// GenericSetCCInfo.
8717 struct SetCCInfoAndKind {
8722 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8724 /// AArch64 lowered one.
8725 /// \p SetCCInfo is filled accordingly.
8726 /// \post SetCCInfo is meanginfull only when this function returns true.
8727 /// \return True when Op is a kind of SET_CC operation.
8728 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8729 // If this is a setcc, this is straight forward.
8730 if (Op.getOpcode() == ISD::SETCC) {
8731 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8732 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8733 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8734 SetCCInfo.IsAArch64 = false;
8737 // Otherwise, check if this is a matching csel instruction.
8741 if (Op.getOpcode() != AArch64ISD::CSEL)
8743 // Set the information about the operands.
8744 // TODO: we want the operands of the Cmp not the csel
8745 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8746 SetCCInfo.IsAArch64 = true;
8747 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8748 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8750 // Check that the operands matches the constraints:
8751 // (1) Both operands must be constants.
8752 // (2) One must be 1 and the other must be 0.
8753 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8754 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8757 if (!TValue || !FValue)
8761 if (!TValue->isOne()) {
8762 // Update the comparison when we are interested in !cc.
8763 std::swap(TValue, FValue);
8764 SetCCInfo.Info.AArch64.CC =
8765 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8767 return TValue->isOne() && FValue->isNullValue();
8770 // Returns true if Op is setcc or zext of setcc.
8771 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8772 if (isSetCC(Op, Info))
8774 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8775 isSetCC(Op->getOperand(0), Info));
8778 // The folding we want to perform is:
8779 // (add x, [zext] (setcc cc ...) )
8781 // (csel x, (add x, 1), !cc ...)
8783 // The latter will get matched to a CSINC instruction.
8784 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8785 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8786 SDValue LHS = Op->getOperand(0);
8787 SDValue RHS = Op->getOperand(1);
8788 SetCCInfoAndKind InfoAndKind;
8790 // If neither operand is a SET_CC, give up.
8791 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8792 std::swap(LHS, RHS);
8793 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8797 // FIXME: This could be generatized to work for FP comparisons.
8798 EVT CmpVT = InfoAndKind.IsAArch64
8799 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8800 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8801 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8807 if (InfoAndKind.IsAArch64) {
8808 CCVal = DAG.getConstant(
8809 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8811 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8813 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8814 *InfoAndKind.Info.Generic.Opnd1,
8815 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8818 EVT VT = Op->getValueType(0);
8819 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8820 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8823 // The basic add/sub long vector instructions have variants with "2" on the end
8824 // which act on the high-half of their inputs. They are normally matched by
8827 // (add (zeroext (extract_high LHS)),
8828 // (zeroext (extract_high RHS)))
8829 // -> uaddl2 vD, vN, vM
8831 // However, if one of the extracts is something like a duplicate, this
8832 // instruction can still be used profitably. This function puts the DAG into a
8833 // more appropriate form for those patterns to trigger.
8834 static SDValue performAddSubLongCombine(SDNode *N,
8835 TargetLowering::DAGCombinerInfo &DCI,
8836 SelectionDAG &DAG) {
8837 if (DCI.isBeforeLegalizeOps())
8840 MVT VT = N->getSimpleValueType(0);
8841 if (!VT.is128BitVector()) {
8842 if (N->getOpcode() == ISD::ADD)
8843 return performSetccAddFolding(N, DAG);
8847 // Make sure both branches are extended in the same way.
8848 SDValue LHS = N->getOperand(0);
8849 SDValue RHS = N->getOperand(1);
8850 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8851 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8852 LHS.getOpcode() != RHS.getOpcode())
8855 unsigned ExtType = LHS.getOpcode();
8857 // It's not worth doing if at least one of the inputs isn't already an
8858 // extract, but we don't know which it'll be so we have to try both.
8859 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8860 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8864 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8865 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8866 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8870 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8873 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8876 // Massage DAGs which we can use the high-half "long" operations on into
8877 // something isel will recognize better. E.g.
8879 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8880 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8881 // (extract_high (v2i64 (dup128 scalar)))))
8883 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8884 TargetLowering::DAGCombinerInfo &DCI,
8885 SelectionDAG &DAG) {
8886 if (DCI.isBeforeLegalizeOps())
8889 SDValue LHS = N->getOperand(1);
8890 SDValue RHS = N->getOperand(2);
8891 assert(LHS.getValueType().is64BitVector() &&
8892 RHS.getValueType().is64BitVector() &&
8893 "unexpected shape for long operation");
8895 // Either node could be a DUP, but it's not worth doing both of them (you'd
8896 // just as well use the non-high version) so look for a corresponding extract
8897 // operation on the other "wing".
8898 if (isEssentiallyExtractSubvector(LHS)) {
8899 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8902 } else if (isEssentiallyExtractSubvector(RHS)) {
8903 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8908 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8909 N->getOperand(0), LHS, RHS);
8912 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8913 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8914 unsigned ElemBits = ElemTy.getSizeInBits();
8916 int64_t ShiftAmount;
8917 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8918 APInt SplatValue, SplatUndef;
8919 unsigned SplatBitSize;
8921 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8922 HasAnyUndefs, ElemBits) ||
8923 SplatBitSize != ElemBits)
8926 ShiftAmount = SplatValue.getSExtValue();
8927 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8928 ShiftAmount = CVN->getSExtValue();
8936 llvm_unreachable("Unknown shift intrinsic");
8937 case Intrinsic::aarch64_neon_sqshl:
8938 Opcode = AArch64ISD::SQSHL_I;
8939 IsRightShift = false;
8941 case Intrinsic::aarch64_neon_uqshl:
8942 Opcode = AArch64ISD::UQSHL_I;
8943 IsRightShift = false;
8945 case Intrinsic::aarch64_neon_srshl:
8946 Opcode = AArch64ISD::SRSHR_I;
8947 IsRightShift = true;
8949 case Intrinsic::aarch64_neon_urshl:
8950 Opcode = AArch64ISD::URSHR_I;
8951 IsRightShift = true;
8953 case Intrinsic::aarch64_neon_sqshlu:
8954 Opcode = AArch64ISD::SQSHLU_I;
8955 IsRightShift = false;
8959 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8961 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8962 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8963 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8965 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8966 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8972 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8973 // the intrinsics must be legal and take an i32, this means there's almost
8974 // certainly going to be a zext in the DAG which we can eliminate.
8975 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8976 SDValue AndN = N->getOperand(2);
8977 if (AndN.getOpcode() != ISD::AND)
8980 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8981 if (!CMask || CMask->getZExtValue() != Mask)
8984 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8985 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8988 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8989 SelectionDAG &DAG) {
8991 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8992 DAG.getNode(Opc, dl,
8993 N->getOperand(1).getSimpleValueType(),
8995 DAG.getConstant(0, dl, MVT::i64));
8998 static SDValue performIntrinsicCombine(SDNode *N,
8999 TargetLowering::DAGCombinerInfo &DCI,
9000 const AArch64Subtarget *Subtarget) {
9001 SelectionDAG &DAG = DCI.DAG;
9002 unsigned IID = getIntrinsicID(N);
9006 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9007 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9008 return tryCombineFixedPointConvert(N, DCI, DAG);
9009 case Intrinsic::aarch64_neon_saddv:
9010 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9011 case Intrinsic::aarch64_neon_uaddv:
9012 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9013 case Intrinsic::aarch64_neon_sminv:
9014 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9015 case Intrinsic::aarch64_neon_uminv:
9016 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9017 case Intrinsic::aarch64_neon_smaxv:
9018 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9019 case Intrinsic::aarch64_neon_umaxv:
9020 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9021 case Intrinsic::aarch64_neon_fmax:
9022 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
9023 N->getOperand(1), N->getOperand(2));
9024 case Intrinsic::aarch64_neon_fmin:
9025 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
9026 N->getOperand(1), N->getOperand(2));
9027 case Intrinsic::aarch64_neon_fmaxnm:
9028 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9029 N->getOperand(1), N->getOperand(2));
9030 case Intrinsic::aarch64_neon_fminnm:
9031 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9032 N->getOperand(1), N->getOperand(2));
9033 case Intrinsic::aarch64_neon_smull:
9034 case Intrinsic::aarch64_neon_umull:
9035 case Intrinsic::aarch64_neon_pmull:
9036 case Intrinsic::aarch64_neon_sqdmull:
9037 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9038 case Intrinsic::aarch64_neon_sqshl:
9039 case Intrinsic::aarch64_neon_uqshl:
9040 case Intrinsic::aarch64_neon_sqshlu:
9041 case Intrinsic::aarch64_neon_srshl:
9042 case Intrinsic::aarch64_neon_urshl:
9043 return tryCombineShiftImm(IID, N, DAG);
9044 case Intrinsic::aarch64_crc32b:
9045 case Intrinsic::aarch64_crc32cb:
9046 return tryCombineCRC32(0xff, N, DAG);
9047 case Intrinsic::aarch64_crc32h:
9048 case Intrinsic::aarch64_crc32ch:
9049 return tryCombineCRC32(0xffff, N, DAG);
9054 static SDValue performExtendCombine(SDNode *N,
9055 TargetLowering::DAGCombinerInfo &DCI,
9056 SelectionDAG &DAG) {
9057 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9058 // we can convert that DUP into another extract_high (of a bigger DUP), which
9059 // helps the backend to decide that an sabdl2 would be useful, saving a real
9060 // extract_high operation.
9061 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9062 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9063 SDNode *ABDNode = N->getOperand(0).getNode();
9064 unsigned IID = getIntrinsicID(ABDNode);
9065 if (IID == Intrinsic::aarch64_neon_sabd ||
9066 IID == Intrinsic::aarch64_neon_uabd) {
9067 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9068 if (!NewABD.getNode())
9071 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9076 // This is effectively a custom type legalization for AArch64.
9078 // Type legalization will split an extend of a small, legal, type to a larger
9079 // illegal type by first splitting the destination type, often creating
9080 // illegal source types, which then get legalized in isel-confusing ways,
9081 // leading to really terrible codegen. E.g.,
9082 // %result = v8i32 sext v8i8 %value
9084 // %losrc = extract_subreg %value, ...
9085 // %hisrc = extract_subreg %value, ...
9086 // %lo = v4i32 sext v4i8 %losrc
9087 // %hi = v4i32 sext v4i8 %hisrc
9088 // Things go rapidly downhill from there.
9090 // For AArch64, the [sz]ext vector instructions can only go up one element
9091 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9092 // take two instructions.
9094 // This implies that the most efficient way to do the extend from v8i8
9095 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9096 // the normal splitting to happen for the v8i16->v8i32.
9098 // This is pre-legalization to catch some cases where the default
9099 // type legalization will create ill-tempered code.
9100 if (!DCI.isBeforeLegalizeOps())
9103 // We're only interested in cleaning things up for non-legal vector types
9104 // here. If both the source and destination are legal, things will just
9105 // work naturally without any fiddling.
9106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9107 EVT ResVT = N->getValueType(0);
9108 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9110 // If the vector type isn't a simple VT, it's beyond the scope of what
9111 // we're worried about here. Let legalization do its thing and hope for
9113 SDValue Src = N->getOperand(0);
9114 EVT SrcVT = Src->getValueType(0);
9115 if (!ResVT.isSimple() || !SrcVT.isSimple())
9118 // If the source VT is a 64-bit vector, we can play games and get the
9119 // better results we want.
9120 if (SrcVT.getSizeInBits() != 64)
9123 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9124 unsigned ElementCount = SrcVT.getVectorNumElements();
9125 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9127 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9129 // Now split the rest of the operation into two halves, each with a 64
9133 unsigned NumElements = ResVT.getVectorNumElements();
9134 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9135 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9136 ResVT.getVectorElementType(), NumElements / 2);
9138 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9139 LoVT.getVectorNumElements());
9140 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9141 DAG.getConstant(0, DL, MVT::i64));
9142 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9143 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9144 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9145 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9147 // Now combine the parts back together so we still have a single result
9148 // like the combiner expects.
9149 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9152 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9153 SDValue SplatVal, unsigned NumVecElts) {
9154 unsigned OrigAlignment = St.getAlignment();
9155 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
9157 // Create scalar stores. This is at least as good as the code sequence for a
9158 // split unaligned store which is a dup.s, ext.b, and two stores.
9159 // Most of the time the three stores should be replaced by store pair
9160 // instructions (stp).
9162 SDValue BasePtr = St.getBasePtr();
9163 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
9165 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
9166 OrigAlignment, St.getMemOperand()->getFlags());
9168 unsigned Offset = EltOffset;
9169 while (--NumVecElts) {
9170 unsigned Alignment = MinAlign(OrigAlignment, Offset);
9171 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9172 DAG.getConstant(Offset, DL, MVT::i64));
9173 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
9174 PtrInfo.getWithOffset(Offset), Alignment,
9175 St.getMemOperand()->getFlags());
9176 Offset += EltOffset;
9181 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9182 /// load store optimizer pass will merge them to store pair stores. This should
9183 /// be better than a movi to create the vector zero followed by a vector store
9184 /// if the zero constant is not re-used, since one instructions and one register
9185 /// live range will be removed.
9187 /// For example, the final generated code should be:
9189 /// stp xzr, xzr, [x0]
9196 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9197 SDValue StVal = St.getValue();
9198 EVT VT = StVal.getValueType();
9200 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9201 // 2, 3 or 4 i32 elements.
9202 int NumVecElts = VT.getVectorNumElements();
9203 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9204 VT.getVectorElementType().getSizeInBits() == 64) ||
9205 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9206 VT.getVectorElementType().getSizeInBits() == 32)))
9209 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9212 // If the zero constant has more than one use then the vector store could be
9213 // better since the constant mov will be amortized and stp q instructions
9214 // should be able to be formed.
9215 if (!StVal.hasOneUse())
9218 // If the immediate offset of the address operand is too large for the stp
9219 // instruction, then bail out.
9220 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9221 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
9222 if (Offset < -512 || Offset > 504)
9226 for (int I = 0; I < NumVecElts; ++I) {
9227 SDValue EltVal = StVal.getOperand(I);
9228 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9232 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9233 // undoing this transformation.
9234 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9235 ? DAG.getRegister(AArch64::WZR, MVT::i32)
9236 : DAG.getRegister(AArch64::XZR, MVT::i64);
9237 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9240 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9241 /// value. The load store optimizer pass will merge them to store pair stores.
9242 /// This has better performance than a splat of the scalar followed by a split
9243 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9244 /// followed by an ext.b and two stores.
9245 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9246 SDValue StVal = St.getValue();
9247 EVT VT = StVal.getValueType();
9249 // Don't replace floating point stores, they possibly won't be transformed to
9250 // stp because of the store pair suppress pass.
9251 if (VT.isFloatingPoint())
9254 // We can express a splat as store pair(s) for 2 or 4 elements.
9255 unsigned NumVecElts = VT.getVectorNumElements();
9256 if (NumVecElts != 4 && NumVecElts != 2)
9259 // Check that this is a splat.
9260 // Make sure that each of the relevant vector element locations are inserted
9261 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9262 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9264 for (unsigned I = 0; I < NumVecElts; ++I) {
9265 // Check for insert vector elements.
9266 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9269 // Check that same value is inserted at each vector element.
9271 SplatVal = StVal.getOperand(1);
9272 else if (StVal.getOperand(1) != SplatVal)
9275 // Check insert element index.
9276 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9279 uint64_t IndexVal = CIndex->getZExtValue();
9280 if (IndexVal >= NumVecElts)
9282 IndexNotInserted.reset(IndexVal);
9284 StVal = StVal.getOperand(0);
9286 // Check that all vector element locations were inserted to.
9287 if (IndexNotInserted.any())
9290 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9293 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9295 const AArch64Subtarget *Subtarget) {
9296 if (!DCI.isBeforeLegalize())
9299 StoreSDNode *S = cast<StoreSDNode>(N);
9300 if (S->isVolatile())
9303 SDValue StVal = S->getValue();
9304 EVT VT = StVal.getValueType();
9308 // If we get a splat of zeros, convert this vector store to a store of
9309 // scalars. They will be merged into store pairs of xzr thereby removing one
9310 // instruction and one register.
9311 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9312 return ReplacedZeroSplat;
9314 // FIXME: The logic for deciding if an unaligned store should be split should
9315 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9316 // a call to that function here.
9318 if (!Subtarget->isMisaligned128StoreSlow())
9321 // Don't split at -Oz.
9322 if (DAG.getMachineFunction().getFunction()->optForMinSize())
9325 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9326 // those up regresses performance on micro-benchmarks and olden/bh.
9327 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9330 // Split unaligned 16B stores. They are terrible for performance.
9331 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9332 // extensions can use this to mark that it does not want splitting to happen
9333 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9334 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9335 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9336 S->getAlignment() <= 2)
9339 // If we get a splat of a scalar convert this vector store to a store of
9340 // scalars. They will be merged into store pairs thereby removing two
9342 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9343 return ReplacedSplat;
9346 unsigned NumElts = VT.getVectorNumElements() / 2;
9347 // Split VT into two.
9349 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9350 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9351 DAG.getConstant(0, DL, MVT::i64));
9352 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9353 DAG.getConstant(NumElts, DL, MVT::i64));
9354 SDValue BasePtr = S->getBasePtr();
9356 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9357 S->getAlignment(), S->getMemOperand()->getFlags());
9358 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9359 DAG.getConstant(8, DL, MVT::i64));
9360 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9361 S->getPointerInfo(), S->getAlignment(),
9362 S->getMemOperand()->getFlags());
9365 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9366 /// post-increment LD1R.
9367 static SDValue performPostLD1Combine(SDNode *N,
9368 TargetLowering::DAGCombinerInfo &DCI,
9370 if (DCI.isBeforeLegalizeOps())
9373 SelectionDAG &DAG = DCI.DAG;
9374 EVT VT = N->getValueType(0);
9376 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9377 SDNode *LD = N->getOperand(LoadIdx).getNode();
9378 // If it is not LOAD, can not do such combine.
9379 if (LD->getOpcode() != ISD::LOAD)
9382 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9383 EVT MemVT = LoadSDN->getMemoryVT();
9384 // Check if memory operand is the same type as the vector element.
9385 if (MemVT != VT.getVectorElementType())
9388 // Check if there are other uses. If so, do not combine as it will introduce
9390 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9392 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9398 SDValue Addr = LD->getOperand(1);
9399 SDValue Vector = N->getOperand(0);
9400 // Search for a use of the address operand that is an increment.
9401 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9402 Addr.getNode()->use_end(); UI != UE; ++UI) {
9404 if (User->getOpcode() != ISD::ADD
9405 || UI.getUse().getResNo() != Addr.getResNo())
9408 // Check that the add is independent of the load. Otherwise, folding it
9409 // would create a cycle.
9410 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9412 // Also check that add is not used in the vector operand. This would also
9414 if (User->isPredecessorOf(Vector.getNode()))
9417 // If the increment is a constant, it must match the memory ref size.
9418 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9419 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9420 uint32_t IncVal = CInc->getZExtValue();
9421 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9422 if (IncVal != NumBytes)
9424 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9427 // Finally, check that the vector doesn't depend on the load.
9428 // Again, this would create a cycle.
9429 // The load depending on the vector is fine, as that's the case for the
9430 // LD1*post we'll eventually generate anyway.
9431 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9434 SmallVector<SDValue, 8> Ops;
9435 Ops.push_back(LD->getOperand(0)); // Chain
9437 Ops.push_back(Vector); // The vector to be inserted
9438 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9440 Ops.push_back(Addr);
9443 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9444 SDVTList SDTys = DAG.getVTList(Tys);
9445 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9446 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9448 LoadSDN->getMemOperand());
9451 SDValue NewResults[] = {
9452 SDValue(LD, 0), // The result of load
9453 SDValue(UpdN.getNode(), 2) // Chain
9455 DCI.CombineTo(LD, NewResults);
9456 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9457 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9464 /// Simplify \Addr given that the top byte of it is ignored by HW during
9465 /// address translation.
9466 static bool performTBISimplification(SDValue Addr,
9467 TargetLowering::DAGCombinerInfo &DCI,
9468 SelectionDAG &DAG) {
9469 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9471 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9472 DCI.isBeforeLegalizeOps());
9473 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9474 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
9475 DCI.CommitTargetLoweringOpt(TLO);
9481 static SDValue performSTORECombine(SDNode *N,
9482 TargetLowering::DAGCombinerInfo &DCI,
9484 const AArch64Subtarget *Subtarget) {
9485 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9488 if (Subtarget->supportsAddressTopByteIgnored() &&
9489 performTBISimplification(N->getOperand(2), DCI, DAG))
9490 return SDValue(N, 0);
9495 /// This function handles the log2-shuffle pattern produced by the
9496 /// LoopVectorizer for the across vector reduction. It consists of
9497 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9498 /// are reduced, where s is an induction variable from 0 to
9499 /// log2(NumVectorElements).
9500 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9502 SelectionDAG &DAG) {
9503 EVT VTy = OpV->getOperand(0).getValueType();
9504 if (!VTy.isVector())
9507 int NumVecElts = VTy.getVectorNumElements();
9508 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9509 if (NumVecElts != 4)
9512 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9516 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
9517 SDValue PreOp = OpV;
9518 // Iterate over each step of the across vector reduction.
9519 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
9520 SDValue CurOp = PreOp.getOperand(0);
9521 SDValue Shuffle = PreOp.getOperand(1);
9522 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
9523 // Try to swap the 1st and 2nd operand as add and min/max instructions
9525 CurOp = PreOp.getOperand(1);
9526 Shuffle = PreOp.getOperand(0);
9527 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9531 // Check if the input vector is fed by the operator we want to handle,
9532 // except the last step; the very first input vector is not necessarily
9533 // the same operator we are handling.
9534 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9537 // Check if it forms one step of the across vector reduction.
9539 // %cur = add %1, %0
9540 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9541 // %pre = add %cur, %shuffle
9542 if (Shuffle.getOperand(0) != CurOp)
9545 int NumMaskElts = 1 << CurStep;
9546 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9547 // Check mask values in each step.
9548 // We expect the shuffle mask in each step follows a specific pattern
9549 // denoted here by the <M, U> form, where M is a sequence of integers
9550 // starting from NumMaskElts, increasing by 1, and the number integers
9551 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9552 // of undef in U should be NumVecElts - NumMaskElts.
9553 // E.g., for <8 x i16>, mask values in each step should be :
9554 // step 0 : <1,u,u,u,u,u,u,u>
9555 // step 1 : <2,3,u,u,u,u,u,u>
9556 // step 2 : <4,5,6,7,u,u,u,u>
9557 for (int i = 0; i < NumVecElts; ++i)
9558 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9559 (i >= NumMaskElts && !(Mask[i] < 0)))
9565 bool IsIntrinsic = false;
9569 llvm_unreachable("Unexpected operator for across vector reduction");
9571 Opcode = AArch64ISD::UADDV;
9574 Opcode = AArch64ISD::SMAXV;
9577 Opcode = AArch64ISD::UMAXV;
9580 Opcode = AArch64ISD::SMINV;
9583 Opcode = AArch64ISD::UMINV;
9586 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9590 Opcode = Intrinsic::aarch64_neon_fminnmv;
9597 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9598 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9600 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9601 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9602 DAG.getConstant(0, DL, MVT::i64));
9605 /// Target-specific DAG combine for the across vector min/max reductions.
9606 /// This function specifically handles the final clean-up step of the vector
9607 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9608 /// pattern, which narrows down and finds the final min/max value from all
9609 /// elements of the vector.
9610 /// For example, for a <16 x i8> vector :
9611 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9612 /// %smax0 = smax %arr, svn0
9613 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9614 /// %smax1 = smax %smax0, %svn1
9615 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9616 /// %smax2 = smax %smax1, svn2
9617 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9618 /// %sc = setcc %smax2, %svn3, gt
9619 /// %n0 = extract_vector_elt %sc, #0
9620 /// %n1 = extract_vector_elt %smax2, #0
9621 /// %n2 = extract_vector_elt $smax2, #1
9622 /// %result = select %n0, %n1, n2
9625 /// %result = extract_vector_elt %1, 0
9627 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9628 const AArch64Subtarget *Subtarget) {
9629 if (!Subtarget->hasNEON())
9632 SDValue N0 = N->getOperand(0);
9633 SDValue IfTrue = N->getOperand(1);
9634 SDValue IfFalse = N->getOperand(2);
9636 // Check if the SELECT merges up the final result of the min/max
9638 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9639 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9640 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9643 // Expect N0 is fed by SETCC.
9644 SDValue SetCC = N0.getOperand(0);
9645 EVT SetCCVT = SetCC.getValueType();
9646 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9647 SetCCVT.getVectorElementType() != MVT::i1)
9650 SDValue VectorOp = SetCC.getOperand(0);
9651 unsigned Op = VectorOp->getOpcode();
9652 // Check if the input vector is fed by the operator we want to handle.
9653 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9654 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
9657 EVT VTy = VectorOp.getValueType();
9658 if (!VTy.isVector())
9661 if (VTy.getSizeInBits() < 64)
9664 EVT EltTy = VTy.getVectorElementType();
9665 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9666 if (EltTy != MVT::f32)
9669 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9673 // Check if extracting from the same vector.
9675 // %sc = setcc %vector, %svn1, gt
9676 // %n0 = extract_vector_elt %sc, #0
9677 // %n1 = extract_vector_elt %vector, #0
9678 // %n2 = extract_vector_elt $vector, #1
9679 if (!(VectorOp == IfTrue->getOperand(0) &&
9680 VectorOp == IfFalse->getOperand(0)))
9683 // Check if the condition code is matched with the operator type.
9684 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9685 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9686 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9687 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
9688 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9689 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9690 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9691 CC != ISD::SETGE) ||
9692 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9693 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9697 // Expect to check only lane 0 from the vector SETCC.
9698 if (!isNullConstant(N0.getOperand(1)))
9701 // Expect to extract the true value from lane 0.
9702 if (!isNullConstant(IfTrue.getOperand(1)))
9705 // Expect to extract the false value from lane 1.
9706 if (!isOneConstant(IfFalse.getOperand(1)))
9709 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9712 /// Target-specific DAG combine for the across vector add reduction.
9713 /// This function specifically handles the final clean-up step of the vector
9714 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9715 /// pattern, which adds all elements of a vector together.
9716 /// For example, for a <4 x i32> vector :
9717 /// %1 = vector_shuffle %0, <2,3,u,u>
9719 /// %3 = vector_shuffle %2, <1,u,u,u>
9721 /// %result = extract_vector_elt %4, 0
9724 /// %result = extract_vector_elt %0, 0
9726 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9727 const AArch64Subtarget *Subtarget) {
9728 if (!Subtarget->hasNEON())
9730 SDValue N0 = N->getOperand(0);
9731 SDValue N1 = N->getOperand(1);
9733 // Check if the input vector is fed by the ADD.
9734 if (N0->getOpcode() != ISD::ADD)
9737 // The vector extract idx must constant zero because we only expect the final
9738 // result of the reduction is placed in lane 0.
9739 if (!isNullConstant(N1))
9742 EVT VTy = N0.getValueType();
9743 if (!VTy.isVector())
9746 EVT EltTy = VTy.getVectorElementType();
9747 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9750 if (VTy.getSizeInBits() < 64)
9753 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9756 /// Target-specific DAG combine function for NEON load/store intrinsics
9757 /// to merge base address updates.
9758 static SDValue performNEONPostLDSTCombine(SDNode *N,
9759 TargetLowering::DAGCombinerInfo &DCI,
9760 SelectionDAG &DAG) {
9761 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9764 unsigned AddrOpIdx = N->getNumOperands() - 1;
9765 SDValue Addr = N->getOperand(AddrOpIdx);
9767 // Search for a use of the address operand that is an increment.
9768 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9769 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9771 if (User->getOpcode() != ISD::ADD ||
9772 UI.getUse().getResNo() != Addr.getResNo())
9775 // Check that the add is independent of the load/store. Otherwise, folding
9776 // it would create a cycle.
9777 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9780 // Find the new opcode for the updating load/store.
9781 bool IsStore = false;
9782 bool IsLaneOp = false;
9783 bool IsDupOp = false;
9784 unsigned NewOpc = 0;
9785 unsigned NumVecs = 0;
9786 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9788 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9789 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9791 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9793 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9795 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9796 NumVecs = 2; IsStore = true; break;
9797 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9798 NumVecs = 3; IsStore = true; break;
9799 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9800 NumVecs = 4; IsStore = true; break;
9801 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9803 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9805 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9807 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9808 NumVecs = 2; IsStore = true; break;
9809 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9810 NumVecs = 3; IsStore = true; break;
9811 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9812 NumVecs = 4; IsStore = true; break;
9813 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9814 NumVecs = 2; IsDupOp = true; break;
9815 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9816 NumVecs = 3; IsDupOp = true; break;
9817 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9818 NumVecs = 4; IsDupOp = true; break;
9819 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9820 NumVecs = 2; IsLaneOp = true; break;
9821 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9822 NumVecs = 3; IsLaneOp = true; break;
9823 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9824 NumVecs = 4; IsLaneOp = true; break;
9825 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9826 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9827 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9828 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9829 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9830 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9835 VecTy = N->getOperand(2).getValueType();
9837 VecTy = N->getValueType(0);
9839 // If the increment is a constant, it must match the memory ref size.
9840 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9841 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9842 uint32_t IncVal = CInc->getZExtValue();
9843 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9844 if (IsLaneOp || IsDupOp)
9845 NumBytes /= VecTy.getVectorNumElements();
9846 if (IncVal != NumBytes)
9848 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9850 SmallVector<SDValue, 8> Ops;
9851 Ops.push_back(N->getOperand(0)); // Incoming chain
9852 // Load lane and store have vector list as input.
9853 if (IsLaneOp || IsStore)
9854 for (unsigned i = 2; i < AddrOpIdx; ++i)
9855 Ops.push_back(N->getOperand(i));
9856 Ops.push_back(Addr); // Base register
9861 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9863 for (n = 0; n < NumResultVecs; ++n)
9865 Tys[n++] = MVT::i64; // Type of write back register
9866 Tys[n] = MVT::Other; // Type of the chain
9867 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9869 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9870 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9871 MemInt->getMemoryVT(),
9872 MemInt->getMemOperand());
9875 std::vector<SDValue> NewResults;
9876 for (unsigned i = 0; i < NumResultVecs; ++i) {
9877 NewResults.push_back(SDValue(UpdN.getNode(), i));
9879 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9880 DCI.CombineTo(N, NewResults);
9881 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9888 // Checks to see if the value is the prescribed width and returns information
9889 // about its extension mode.
9891 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9892 ExtType = ISD::NON_EXTLOAD;
9893 switch(V.getNode()->getOpcode()) {
9897 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9898 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9899 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9900 ExtType = LoadNode->getExtensionType();
9905 case ISD::AssertSext: {
9906 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9907 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9908 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9909 ExtType = ISD::SEXTLOAD;
9914 case ISD::AssertZext: {
9915 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9916 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9917 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9918 ExtType = ISD::ZEXTLOAD;
9924 case ISD::TargetConstant: {
9925 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9933 // This function does a whole lot of voodoo to determine if the tests are
9934 // equivalent without and with a mask. Essentially what happens is that given a
9937 // +-------------+ +-------------+ +-------------+ +-------------+
9938 // | Input | | AddConstant | | CompConstant| | CC |
9939 // +-------------+ +-------------+ +-------------+ +-------------+
9941 // V V | +----------+
9942 // +-------------+ +----+ | |
9943 // | ADD | |0xff| | |
9944 // +-------------+ +----+ | |
9947 // +-------------+ | |
9949 // +-------------+ | |
9958 // The AND node may be safely removed for some combinations of inputs. In
9959 // particular we need to take into account the extension type of the Input,
9960 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9961 // width of the input (this can work for any width inputs, the above graph is
9962 // specific to 8 bits.
9964 // The specific equations were worked out by generating output tables for each
9965 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9966 // problem was simplified by working with 4 bit inputs, which means we only
9967 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9968 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9969 // patterns present in both extensions (0,7). For every distinct set of
9970 // AddConstant and CompConstants bit patterns we can consider the masked and
9971 // unmasked versions to be equivalent if the result of this function is true for
9972 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9975 // and w10, w8, #0x0f
9977 // cset w9, AArch64CC
9979 // cset w11, AArch64CC
9984 // Since the above function shows when the outputs are equivalent it defines
9985 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9986 // would be expensive to run during compiles. The equations below were written
9987 // in a test harness that confirmed they gave equivalent outputs to the above
9988 // for all inputs function, so they can be used determine if the removal is
9991 // isEquivalentMaskless() is the code for testing if the AND can be removed
9992 // factored out of the DAG recognition as the DAG can take several forms.
9994 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9995 ISD::LoadExtType ExtType, int AddConstant,
9997 // By being careful about our equations and only writing the in term
9998 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9999 // make them generally applicable to all bit widths.
10000 int MaxUInt = (1 << width);
10002 // For the purposes of these comparisons sign extending the type is
10003 // equivalent to zero extending the add and displacing it by half the integer
10004 // width. Provided we are careful and make sure our equations are valid over
10005 // the whole range we can just adjust the input and avoid writing equations
10006 // for sign extended inputs.
10007 if (ExtType == ISD::SEXTLOAD)
10008 AddConstant -= (1 << (width-1));
10011 case AArch64CC::LE:
10012 case AArch64CC::GT:
10013 if ((AddConstant == 0) ||
10014 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10015 (AddConstant >= 0 && CompConstant < 0) ||
10016 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10019 case AArch64CC::LT:
10020 case AArch64CC::GE:
10021 if ((AddConstant == 0) ||
10022 (AddConstant >= 0 && CompConstant <= 0) ||
10023 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10026 case AArch64CC::HI:
10027 case AArch64CC::LS:
10028 if ((AddConstant >= 0 && CompConstant < 0) ||
10029 (AddConstant <= 0 && CompConstant >= -1 &&
10030 CompConstant < AddConstant + MaxUInt))
10033 case AArch64CC::PL:
10034 case AArch64CC::MI:
10035 if ((AddConstant == 0) ||
10036 (AddConstant > 0 && CompConstant <= 0) ||
10037 (AddConstant < 0 && CompConstant <= AddConstant))
10040 case AArch64CC::LO:
10041 case AArch64CC::HS:
10042 if ((AddConstant >= 0 && CompConstant <= 0) ||
10043 (AddConstant <= 0 && CompConstant >= 0 &&
10044 CompConstant <= AddConstant + MaxUInt))
10047 case AArch64CC::EQ:
10048 case AArch64CC::NE:
10049 if ((AddConstant > 0 && CompConstant < 0) ||
10050 (AddConstant < 0 && CompConstant >= 0 &&
10051 CompConstant < AddConstant + MaxUInt) ||
10052 (AddConstant >= 0 && CompConstant >= 0 &&
10053 CompConstant >= AddConstant) ||
10054 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
10057 case AArch64CC::VS:
10058 case AArch64CC::VC:
10059 case AArch64CC::AL:
10060 case AArch64CC::NV:
10062 case AArch64CC::Invalid:
10070 SDValue performCONDCombine(SDNode *N,
10071 TargetLowering::DAGCombinerInfo &DCI,
10072 SelectionDAG &DAG, unsigned CCIndex,
10073 unsigned CmpIndex) {
10074 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10075 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10076 unsigned CondOpcode = SubsNode->getOpcode();
10078 if (CondOpcode != AArch64ISD::SUBS)
10081 // There is a SUBS feeding this condition. Is it fed by a mask we can
10084 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10085 unsigned MaskBits = 0;
10087 if (AndNode->getOpcode() != ISD::AND)
10090 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10091 uint32_t CNV = CN->getZExtValue();
10094 else if (CNV == 65535)
10101 SDValue AddValue = AndNode->getOperand(0);
10103 if (AddValue.getOpcode() != ISD::ADD)
10106 // The basic dag structure is correct, grab the inputs and validate them.
10108 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10109 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10110 SDValue SubsInputValue = SubsNode->getOperand(1);
10112 // The mask is present and the provenance of all the values is a smaller type,
10113 // lets see if the mask is superfluous.
10115 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10116 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10119 ISD::LoadExtType ExtType;
10121 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10122 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10123 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10126 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10127 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10128 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10131 // The AND is not necessary, remove it.
10133 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10134 SubsNode->getValueType(1));
10135 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10137 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10138 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10140 return SDValue(N, 0);
10143 // Optimize compare with zero and branch.
10144 static SDValue performBRCONDCombine(SDNode *N,
10145 TargetLowering::DAGCombinerInfo &DCI,
10146 SelectionDAG &DAG) {
10147 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10149 SDValue Chain = N->getOperand(0);
10150 SDValue Dest = N->getOperand(1);
10151 SDValue CCVal = N->getOperand(2);
10152 SDValue Cmp = N->getOperand(3);
10154 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10155 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10156 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10159 unsigned CmpOpc = Cmp.getOpcode();
10160 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10163 // Only attempt folding if there is only one use of the flag and no use of the
10165 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10168 SDValue LHS = Cmp.getOperand(0);
10169 SDValue RHS = Cmp.getOperand(1);
10171 assert(LHS.getValueType() == RHS.getValueType() &&
10172 "Expected the value type to be the same for both operands!");
10173 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10176 if (isNullConstant(LHS))
10177 std::swap(LHS, RHS);
10179 if (!isNullConstant(RHS))
10182 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10183 LHS.getOpcode() == ISD::SRL)
10186 // Fold the compare into the branch instruction.
10188 if (CC == AArch64CC::EQ)
10189 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10191 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10193 // Do not add new nodes to DAG combiner worklist.
10194 DCI.CombineTo(N, BR, false);
10199 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10200 // as well as whether the test should be inverted. This code is required to
10201 // catch these cases (as opposed to standard dag combines) because
10202 // AArch64ISD::TBZ is matched during legalization.
10203 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10204 SelectionDAG &DAG) {
10206 if (!Op->hasOneUse())
10209 // We don't handle undef/constant-fold cases below, as they should have
10210 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10213 // (tbz (trunc x), b) -> (tbz x, b)
10214 // This case is just here to enable more of the below cases to be caught.
10215 if (Op->getOpcode() == ISD::TRUNCATE &&
10216 Bit < Op->getValueType(0).getSizeInBits()) {
10217 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10220 if (Op->getNumOperands() != 2)
10223 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10227 switch (Op->getOpcode()) {
10231 // (tbz (and x, m), b) -> (tbz x, b)
10233 if ((C->getZExtValue() >> Bit) & 1)
10234 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10237 // (tbz (shl x, c), b) -> (tbz x, b-c)
10239 if (C->getZExtValue() <= Bit &&
10240 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10241 Bit = Bit - C->getZExtValue();
10242 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10246 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10248 Bit = Bit + C->getZExtValue();
10249 if (Bit >= Op->getValueType(0).getSizeInBits())
10250 Bit = Op->getValueType(0).getSizeInBits() - 1;
10251 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10253 // (tbz (srl x, c), b) -> (tbz x, b+c)
10255 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10256 Bit = Bit + C->getZExtValue();
10257 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10261 // (tbz (xor x, -1), b) -> (tbnz x, b)
10263 if ((C->getZExtValue() >> Bit) & 1)
10265 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10269 // Optimize test single bit zero/non-zero and branch.
10270 static SDValue performTBZCombine(SDNode *N,
10271 TargetLowering::DAGCombinerInfo &DCI,
10272 SelectionDAG &DAG) {
10273 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10274 bool Invert = false;
10275 SDValue TestSrc = N->getOperand(1);
10276 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10278 if (TestSrc == NewTestSrc)
10281 unsigned NewOpc = N->getOpcode();
10283 if (NewOpc == AArch64ISD::TBZ)
10284 NewOpc = AArch64ISD::TBNZ;
10286 assert(NewOpc == AArch64ISD::TBNZ);
10287 NewOpc = AArch64ISD::TBZ;
10292 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10293 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10296 // vselect (v1i1 setcc) ->
10297 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
10298 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10299 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10301 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10302 SDValue N0 = N->getOperand(0);
10303 EVT CCVT = N0.getValueType();
10305 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10306 CCVT.getVectorElementType() != MVT::i1)
10309 EVT ResVT = N->getValueType(0);
10310 EVT CmpVT = N0.getOperand(0).getValueType();
10311 // Only combine when the result type is of the same size as the compared
10313 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10316 SDValue IfTrue = N->getOperand(1);
10317 SDValue IfFalse = N->getOperand(2);
10319 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10320 N0.getOperand(0), N0.getOperand(1),
10321 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10322 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10326 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10327 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10328 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10329 /// with a vector one followed by a DUP shuffle on the result.
10330 static SDValue performSelectCombine(SDNode *N,
10331 TargetLowering::DAGCombinerInfo &DCI) {
10332 SelectionDAG &DAG = DCI.DAG;
10333 SDValue N0 = N->getOperand(0);
10334 EVT ResVT = N->getValueType(0);
10336 if (N0.getOpcode() != ISD::SETCC)
10339 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10340 // scalar SetCCResultType. We also don't expect vectors, because we assume
10341 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10342 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10343 "Scalar-SETCC feeding SELECT has unexpected result type!");
10345 // If NumMaskElts == 0, the comparison is larger than select result. The
10346 // largest real NEON comparison is 64-bits per lane, which means the result is
10347 // at most 32-bits and an illegal vector. Just bail out for now.
10348 EVT SrcVT = N0.getOperand(0).getValueType();
10350 // Don't try to do this optimization when the setcc itself has i1 operands.
10351 // There are no legal vectors of i1, so this would be pointless.
10352 if (SrcVT == MVT::i1)
10355 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10356 if (!ResVT.isVector() || NumMaskElts == 0)
10359 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10360 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10362 // Also bail out if the vector CCVT isn't the same size as ResVT.
10363 // This can happen if the SETCC operand size doesn't divide the ResVT size
10364 // (e.g., f64 vs v3f32).
10365 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10368 // Make sure we didn't create illegal types, if we're not supposed to.
10369 assert(DCI.isBeforeLegalize() ||
10370 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10372 // First perform a vector comparison, where lane 0 is the one we're interested
10376 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10378 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10379 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10381 // Now duplicate the comparison mask we want across all other lanes.
10382 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10383 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10384 Mask = DAG.getNode(ISD::BITCAST, DL,
10385 ResVT.changeVectorElementTypeToInteger(), Mask);
10387 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10390 /// Get rid of unnecessary NVCASTs (that don't change the type).
10391 static SDValue performNVCASTCombine(SDNode *N) {
10392 if (N->getValueType(0) == N->getOperand(0).getValueType())
10393 return N->getOperand(0);
10398 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10399 DAGCombinerInfo &DCI) const {
10400 SelectionDAG &DAG = DCI.DAG;
10401 switch (N->getOpcode()) {
10406 return performAddSubLongCombine(N, DCI, DAG);
10408 return performXorCombine(N, DAG, DCI, Subtarget);
10410 return performMulCombine(N, DAG, DCI, Subtarget);
10411 case ISD::SINT_TO_FP:
10412 case ISD::UINT_TO_FP:
10413 return performIntToFpCombine(N, DAG, Subtarget);
10414 case ISD::FP_TO_SINT:
10415 case ISD::FP_TO_UINT:
10416 return performFpToIntCombine(N, DAG, DCI, Subtarget);
10418 return performFDivCombine(N, DAG, DCI, Subtarget);
10420 return performORCombine(N, DCI, Subtarget);
10422 return performSRLCombine(N, DCI);
10423 case ISD::INTRINSIC_WO_CHAIN:
10424 return performIntrinsicCombine(N, DCI, Subtarget);
10425 case ISD::ANY_EXTEND:
10426 case ISD::ZERO_EXTEND:
10427 case ISD::SIGN_EXTEND:
10428 return performExtendCombine(N, DCI, DAG);
10430 return performBitcastCombine(N, DCI, DAG);
10431 case ISD::CONCAT_VECTORS:
10432 return performConcatVectorsCombine(N, DCI, DAG);
10433 case ISD::SELECT: {
10434 SDValue RV = performSelectCombine(N, DCI);
10436 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10440 return performVSelectCombine(N, DCI.DAG);
10442 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10443 return SDValue(N, 0);
10446 return performSTORECombine(N, DCI, DAG, Subtarget);
10447 case AArch64ISD::BRCOND:
10448 return performBRCONDCombine(N, DCI, DAG);
10449 case AArch64ISD::TBNZ:
10450 case AArch64ISD::TBZ:
10451 return performTBZCombine(N, DCI, DAG);
10452 case AArch64ISD::CSEL:
10453 return performCONDCombine(N, DCI, DAG, 2, 3);
10454 case AArch64ISD::DUP:
10455 return performPostLD1Combine(N, DCI, false);
10456 case AArch64ISD::NVCAST:
10457 return performNVCASTCombine(N);
10458 case ISD::INSERT_VECTOR_ELT:
10459 return performPostLD1Combine(N, DCI, true);
10460 case ISD::EXTRACT_VECTOR_ELT:
10461 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
10462 case ISD::INTRINSIC_VOID:
10463 case ISD::INTRINSIC_W_CHAIN:
10464 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10465 case Intrinsic::aarch64_neon_ld2:
10466 case Intrinsic::aarch64_neon_ld3:
10467 case Intrinsic::aarch64_neon_ld4:
10468 case Intrinsic::aarch64_neon_ld1x2:
10469 case Intrinsic::aarch64_neon_ld1x3:
10470 case Intrinsic::aarch64_neon_ld1x4:
10471 case Intrinsic::aarch64_neon_ld2lane:
10472 case Intrinsic::aarch64_neon_ld3lane:
10473 case Intrinsic::aarch64_neon_ld4lane:
10474 case Intrinsic::aarch64_neon_ld2r:
10475 case Intrinsic::aarch64_neon_ld3r:
10476 case Intrinsic::aarch64_neon_ld4r:
10477 case Intrinsic::aarch64_neon_st2:
10478 case Intrinsic::aarch64_neon_st3:
10479 case Intrinsic::aarch64_neon_st4:
10480 case Intrinsic::aarch64_neon_st1x2:
10481 case Intrinsic::aarch64_neon_st1x3:
10482 case Intrinsic::aarch64_neon_st1x4:
10483 case Intrinsic::aarch64_neon_st2lane:
10484 case Intrinsic::aarch64_neon_st3lane:
10485 case Intrinsic::aarch64_neon_st4lane:
10486 return performNEONPostLDSTCombine(N, DCI, DAG);
10494 // Check if the return value is used as only a return value, as otherwise
10495 // we can't perform a tail-call. In particular, we need to check for
10496 // target ISD nodes that are returns and any other "odd" constructs
10497 // that the generic analysis code won't necessarily catch.
10498 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10499 SDValue &Chain) const {
10500 if (N->getNumValues() != 1)
10502 if (!N->hasNUsesOfValue(1, 0))
10505 SDValue TCChain = Chain;
10506 SDNode *Copy = *N->use_begin();
10507 if (Copy->getOpcode() == ISD::CopyToReg) {
10508 // If the copy has a glue operand, we conservatively assume it isn't safe to
10509 // perform a tail call.
10510 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10513 TCChain = Copy->getOperand(0);
10514 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10517 bool HasRet = false;
10518 for (SDNode *Node : Copy->uses()) {
10519 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10531 // Return whether the an instruction can potentially be optimized to a tail
10532 // call. This will cause the optimizers to attempt to move, or duplicate,
10533 // return instructions to help enable tail call optimizations for this
10535 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10536 return CI->isTailCall();
10539 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10541 ISD::MemIndexedMode &AM,
10543 SelectionDAG &DAG) const {
10544 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10547 Base = Op->getOperand(0);
10548 // All of the indexed addressing mode instructions take a signed
10549 // 9 bit immediate offset.
10550 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10551 int64_t RHSC = RHS->getSExtValue();
10552 if (Op->getOpcode() == ISD::SUB)
10553 RHSC = -(uint64_t)RHSC;
10554 if (!isInt<9>(RHSC))
10556 IsInc = (Op->getOpcode() == ISD::ADD);
10557 Offset = Op->getOperand(1);
10563 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10565 ISD::MemIndexedMode &AM,
10566 SelectionDAG &DAG) const {
10569 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10570 VT = LD->getMemoryVT();
10571 Ptr = LD->getBasePtr();
10572 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10573 VT = ST->getMemoryVT();
10574 Ptr = ST->getBasePtr();
10579 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10581 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10585 bool AArch64TargetLowering::getPostIndexedAddressParts(
10586 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10587 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10590 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10591 VT = LD->getMemoryVT();
10592 Ptr = LD->getBasePtr();
10593 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10594 VT = ST->getMemoryVT();
10595 Ptr = ST->getBasePtr();
10600 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10602 // Post-indexing updates the base, so it's not a valid transform
10603 // if that's not the same as the load's pointer.
10606 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10610 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10611 SelectionDAG &DAG) {
10613 SDValue Op = N->getOperand(0);
10615 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10619 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10620 DAG.getUNDEF(MVT::i32), Op,
10621 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10623 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10624 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10627 static void ReplaceReductionResults(SDNode *N,
10628 SmallVectorImpl<SDValue> &Results,
10629 SelectionDAG &DAG, unsigned InterOp,
10630 unsigned AcrossOp) {
10634 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10635 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10636 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10637 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10638 Results.push_back(SplitVal);
10641 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10643 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10644 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10645 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10646 DAG.getConstant(64, DL, MVT::i64)));
10647 return std::make_pair(Lo, Hi);
10650 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10651 SmallVectorImpl<SDValue> & Results,
10652 SelectionDAG &DAG) {
10653 assert(N->getValueType(0) == MVT::i128 &&
10654 "AtomicCmpSwap on types less than 128 should be legal");
10655 auto Desired = splitInt128(N->getOperand(2), DAG);
10656 auto New = splitInt128(N->getOperand(3), DAG);
10657 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10658 New.first, New.second, N->getOperand(0)};
10659 SDNode *CmpSwap = DAG.getMachineNode(
10660 AArch64::CMP_SWAP_128, SDLoc(N),
10661 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10663 MachineFunction &MF = DAG.getMachineFunction();
10664 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10665 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10666 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10668 Results.push_back(SDValue(CmpSwap, 0));
10669 Results.push_back(SDValue(CmpSwap, 1));
10670 Results.push_back(SDValue(CmpSwap, 3));
10673 void AArch64TargetLowering::ReplaceNodeResults(
10674 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10675 switch (N->getOpcode()) {
10677 llvm_unreachable("Don't know how to custom expand this");
10679 ReplaceBITCASTResults(N, Results, DAG);
10681 case AArch64ISD::SADDV:
10682 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10684 case AArch64ISD::UADDV:
10685 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10687 case AArch64ISD::SMINV:
10688 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10690 case AArch64ISD::UMINV:
10691 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10693 case AArch64ISD::SMAXV:
10694 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10696 case AArch64ISD::UMAXV:
10697 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10699 case ISD::FP_TO_UINT:
10700 case ISD::FP_TO_SINT:
10701 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10702 // Let normal code take care of it by not adding anything to Results.
10704 case ISD::ATOMIC_CMP_SWAP:
10705 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10710 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10711 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10712 return TargetLowering::useLoadStackGuardNode();
10716 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10717 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10718 // reciprocal if there are three or more FDIVs.
10722 TargetLoweringBase::LegalizeTypeAction
10723 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10724 MVT SVT = VT.getSimpleVT();
10725 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10726 // v4i16, v2i32 instead of to promote.
10727 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10728 || SVT == MVT::v1f32)
10729 return TypeWidenVector;
10731 return TargetLoweringBase::getPreferredVectorAction(VT);
10734 // Loads and stores less than 128-bits are already atomic; ones above that
10735 // are doomed anyway, so defer to the default libcall and blame the OS when
10736 // things go wrong.
10737 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10738 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10739 return Size == 128;
10742 // Loads and stores less than 128-bits are already atomic; ones above that
10743 // are doomed anyway, so defer to the default libcall and blame the OS when
10744 // things go wrong.
10745 TargetLowering::AtomicExpansionKind
10746 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10747 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10748 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10751 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10752 TargetLowering::AtomicExpansionKind
10753 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10754 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10755 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10758 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10759 AtomicCmpXchgInst *AI) const {
10760 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10761 // implement cmpxchg without spilling. If the address being exchanged is also
10762 // on the stack and close enough to the spill slot, this can lead to a
10763 // situation where the monitor always gets cleared and the atomic operation
10764 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10765 return getTargetMachine().getOptLevel() != 0;
10768 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10769 AtomicOrdering Ord) const {
10770 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10771 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10772 bool IsAcquire = isAcquireOrStronger(Ord);
10774 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10775 // intrinsic must return {i64, i64} and we have to recombine them into a
10776 // single i128 here.
10777 if (ValTy->getPrimitiveSizeInBits() == 128) {
10778 Intrinsic::ID Int =
10779 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10780 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10782 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10783 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10785 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10786 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10787 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10788 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10789 return Builder.CreateOr(
10790 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10793 Type *Tys[] = { Addr->getType() };
10794 Intrinsic::ID Int =
10795 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10796 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10798 return Builder.CreateTruncOrBitCast(
10799 Builder.CreateCall(Ldxr, Addr),
10800 cast<PointerType>(Addr->getType())->getElementType());
10803 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10804 IRBuilder<> &Builder) const {
10805 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10806 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10809 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10810 Value *Val, Value *Addr,
10811 AtomicOrdering Ord) const {
10812 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10813 bool IsRelease = isReleaseOrStronger(Ord);
10815 // Since the intrinsics must have legal type, the i128 intrinsics take two
10816 // parameters: "i64, i64". We must marshal Val into the appropriate form
10817 // before the call.
10818 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10819 Intrinsic::ID Int =
10820 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10821 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10822 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10824 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10825 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10826 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10827 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10830 Intrinsic::ID Int =
10831 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10832 Type *Tys[] = { Addr->getType() };
10833 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10835 return Builder.CreateCall(Stxr,
10836 {Builder.CreateZExtOrBitCast(
10837 Val, Stxr->getFunctionType()->getParamType(0)),
10841 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10842 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10843 return Ty->isArrayTy();
10846 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10851 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
10852 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10853 Function *ThreadPointerFunc =
10854 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10855 return IRB.CreatePointerCast(
10856 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
10857 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10860 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10861 // Android provides a fixed TLS slot for the stack cookie. See the definition
10862 // of TLS_SLOT_STACK_GUARD in
10863 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10864 if (Subtarget->isTargetAndroid())
10865 return UseTlsOffset(IRB, 0x28);
10867 // Fuchsia is similar.
10868 // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10869 if (Subtarget->isTargetFuchsia())
10870 return UseTlsOffset(IRB, -0x10);
10872 return TargetLowering::getIRStackGuard(IRB);
10875 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10876 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10877 // definition of TLS_SLOT_SAFESTACK in
10878 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10879 if (Subtarget->isTargetAndroid())
10880 return UseTlsOffset(IRB, 0x48);
10882 // Fuchsia is similar.
10883 // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10884 if (Subtarget->isTargetFuchsia())
10885 return UseTlsOffset(IRB, -0x8);
10887 return TargetLowering::getSafeStackPointerLocation(IRB);
10890 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10891 const Instruction &AndI) const {
10892 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10893 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10894 // may be beneficial to sink in other cases, but we would have to check that
10895 // the cmp would not get folded into the br to form a cbz for these to be
10897 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10900 return Mask->getUniqueInteger().isPowerOf2();
10903 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10904 // Update IsSplitCSR in AArch64unctionInfo.
10905 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10906 AFI->setIsSplitCSR(true);
10909 void AArch64TargetLowering::insertCopiesSplitCSR(
10910 MachineBasicBlock *Entry,
10911 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10912 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10913 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10917 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10918 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10919 MachineBasicBlock::iterator MBBI = Entry->begin();
10920 for (const MCPhysReg *I = IStart; *I; ++I) {
10921 const TargetRegisterClass *RC = nullptr;
10922 if (AArch64::GPR64RegClass.contains(*I))
10923 RC = &AArch64::GPR64RegClass;
10924 else if (AArch64::FPR64RegClass.contains(*I))
10925 RC = &AArch64::FPR64RegClass;
10927 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10929 unsigned NewVR = MRI->createVirtualRegister(RC);
10930 // Create copy from CSR to a virtual register.
10931 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10932 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10933 // nounwind. If we want to generalize this later, we may need to emit
10934 // CFI pseudo-instructions.
10935 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10936 Attribute::NoUnwind) &&
10937 "Function should be nounwind in insertCopiesSplitCSR!");
10938 Entry->addLiveIn(*I);
10939 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10942 // Insert the copy-back instructions right before the terminator.
10943 for (auto *Exit : Exits)
10944 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10945 TII->get(TargetOpcode::COPY), *I)
10950 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
10951 // Integer division on AArch64 is expensive. However, when aggressively
10952 // optimizing for code size, we prefer to use a div instruction, as it is
10953 // usually smaller than the alternative sequence.
10954 // The exception to this is vector division. Since AArch64 doesn't have vector
10955 // integer division, leaving the division as-is is a loss even in terms of
10956 // size, because it will have to be scalarized, while the alternative code
10957 // sequence can be performed in vector form.
10959 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
10960 return OptSize && !VT.isVector();
10964 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10965 if (Subtarget->isTargetDarwin())
10966 return getPointerTy(DL).getSizeInBits();
10968 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;