1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the AArch64TargetLowering class.
11 //===----------------------------------------------------------------------===//
13 #include "AArch64ExpandImm.h"
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RuntimeLibcalls.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetCallingConv.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/Intrinsics.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/OperandTraits.h"
62 #include "llvm/IR/PatternMatch.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/Use.h"
65 #include "llvm/IR/Value.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/KnownBits.h"
74 #include "llvm/Support/MachineValueType.h"
75 #include "llvm/Support/MathExtras.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include "llvm/Target/TargetMachine.h"
78 #include "llvm/Target/TargetOptions.h"
92 using namespace llvm::PatternMatch
;
94 #define DEBUG_TYPE "aarch64-lower"
96 STATISTIC(NumTailCalls
, "Number of tail calls");
97 STATISTIC(NumShiftInserts
, "Number of vector shift inserts");
98 STATISTIC(NumOptimizedImms
, "Number of times immediates were optimized");
101 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden
,
102 cl::desc("Allow AArch64 SLI/SRI formation"),
105 // FIXME: The necessary dtprel relocations don't seem to be supported
106 // well in the GNU bfd and gold linkers at the moment. Therefore, by
107 // default, for now, fall back to GeneralDynamic code generation.
108 cl::opt
<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109 "aarch64-elf-ldtls-generation", cl::Hidden
,
110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
114 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden
,
115 cl::desc("Enable AArch64 logical imm instruction "
119 /// Value type used for condition codes.
120 static const MVT MVT_CC
= MVT::i32
;
122 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine
&TM
,
123 const AArch64Subtarget
&STI
)
124 : TargetLowering(TM
), Subtarget(&STI
) {
125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126 // we have to make something up. Arbitrarily, choose ZeroOrOne.
127 setBooleanContents(ZeroOrOneBooleanContent
);
128 // When comparing vectors the result sets the different elements in the
129 // vector to all-one or all-zero.
130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent
);
132 // Set up the register classes.
133 addRegisterClass(MVT::i32
, &AArch64::GPR32allRegClass
);
134 addRegisterClass(MVT::i64
, &AArch64::GPR64allRegClass
);
136 if (Subtarget
->hasFPARMv8()) {
137 addRegisterClass(MVT::f16
, &AArch64::FPR16RegClass
);
138 addRegisterClass(MVT::f32
, &AArch64::FPR32RegClass
);
139 addRegisterClass(MVT::f64
, &AArch64::FPR64RegClass
);
140 addRegisterClass(MVT::f128
, &AArch64::FPR128RegClass
);
143 if (Subtarget
->hasNEON()) {
144 addRegisterClass(MVT::v16i8
, &AArch64::FPR8RegClass
);
145 addRegisterClass(MVT::v8i16
, &AArch64::FPR16RegClass
);
146 // Someone set us up the NEON.
147 addDRTypeForNEON(MVT::v2f32
);
148 addDRTypeForNEON(MVT::v8i8
);
149 addDRTypeForNEON(MVT::v4i16
);
150 addDRTypeForNEON(MVT::v2i32
);
151 addDRTypeForNEON(MVT::v1i64
);
152 addDRTypeForNEON(MVT::v1f64
);
153 addDRTypeForNEON(MVT::v4f16
);
155 addQRTypeForNEON(MVT::v4f32
);
156 addQRTypeForNEON(MVT::v2f64
);
157 addQRTypeForNEON(MVT::v16i8
);
158 addQRTypeForNEON(MVT::v8i16
);
159 addQRTypeForNEON(MVT::v4i32
);
160 addQRTypeForNEON(MVT::v2i64
);
161 addQRTypeForNEON(MVT::v8f16
);
164 // Compute derived properties from the register classes
165 computeRegisterProperties(Subtarget
->getRegisterInfo());
167 // Provide all sorts of operation actions
168 setOperationAction(ISD::GlobalAddress
, MVT::i64
, Custom
);
169 setOperationAction(ISD::GlobalTLSAddress
, MVT::i64
, Custom
);
170 setOperationAction(ISD::SETCC
, MVT::i32
, Custom
);
171 setOperationAction(ISD::SETCC
, MVT::i64
, Custom
);
172 setOperationAction(ISD::SETCC
, MVT::f16
, Custom
);
173 setOperationAction(ISD::SETCC
, MVT::f32
, Custom
);
174 setOperationAction(ISD::SETCC
, MVT::f64
, Custom
);
175 setOperationAction(ISD::BITREVERSE
, MVT::i32
, Legal
);
176 setOperationAction(ISD::BITREVERSE
, MVT::i64
, Legal
);
177 setOperationAction(ISD::BRCOND
, MVT::Other
, Expand
);
178 setOperationAction(ISD::BR_CC
, MVT::i32
, Custom
);
179 setOperationAction(ISD::BR_CC
, MVT::i64
, Custom
);
180 setOperationAction(ISD::BR_CC
, MVT::f16
, Custom
);
181 setOperationAction(ISD::BR_CC
, MVT::f32
, Custom
);
182 setOperationAction(ISD::BR_CC
, MVT::f64
, Custom
);
183 setOperationAction(ISD::SELECT
, MVT::i32
, Custom
);
184 setOperationAction(ISD::SELECT
, MVT::i64
, Custom
);
185 setOperationAction(ISD::SELECT
, MVT::f16
, Custom
);
186 setOperationAction(ISD::SELECT
, MVT::f32
, Custom
);
187 setOperationAction(ISD::SELECT
, MVT::f64
, Custom
);
188 setOperationAction(ISD::SELECT_CC
, MVT::i32
, Custom
);
189 setOperationAction(ISD::SELECT_CC
, MVT::i64
, Custom
);
190 setOperationAction(ISD::SELECT_CC
, MVT::f16
, Custom
);
191 setOperationAction(ISD::SELECT_CC
, MVT::f32
, Custom
);
192 setOperationAction(ISD::SELECT_CC
, MVT::f64
, Custom
);
193 setOperationAction(ISD::BR_JT
, MVT::Other
, Custom
);
194 setOperationAction(ISD::JumpTable
, MVT::i64
, Custom
);
196 setOperationAction(ISD::SHL_PARTS
, MVT::i64
, Custom
);
197 setOperationAction(ISD::SRA_PARTS
, MVT::i64
, Custom
);
198 setOperationAction(ISD::SRL_PARTS
, MVT::i64
, Custom
);
200 setOperationAction(ISD::FREM
, MVT::f32
, Expand
);
201 setOperationAction(ISD::FREM
, MVT::f64
, Expand
);
202 setOperationAction(ISD::FREM
, MVT::f80
, Expand
);
204 setOperationAction(ISD::BUILD_PAIR
, MVT::i64
, Expand
);
206 // Custom lowering hooks are needed for XOR
207 // to fold it into CSINC/CSINV.
208 setOperationAction(ISD::XOR
, MVT::i32
, Custom
);
209 setOperationAction(ISD::XOR
, MVT::i64
, Custom
);
211 // Virtually no operation on f128 is legal, but LLVM can't expand them when
212 // there's a valid register class, so we need custom operations in most cases.
213 setOperationAction(ISD::FABS
, MVT::f128
, Expand
);
214 setOperationAction(ISD::FADD
, MVT::f128
, Custom
);
215 setOperationAction(ISD::FCOPYSIGN
, MVT::f128
, Expand
);
216 setOperationAction(ISD::FCOS
, MVT::f128
, Expand
);
217 setOperationAction(ISD::FDIV
, MVT::f128
, Custom
);
218 setOperationAction(ISD::FMA
, MVT::f128
, Expand
);
219 setOperationAction(ISD::FMUL
, MVT::f128
, Custom
);
220 setOperationAction(ISD::FNEG
, MVT::f128
, Expand
);
221 setOperationAction(ISD::FPOW
, MVT::f128
, Expand
);
222 setOperationAction(ISD::FREM
, MVT::f128
, Expand
);
223 setOperationAction(ISD::FRINT
, MVT::f128
, Expand
);
224 setOperationAction(ISD::FSIN
, MVT::f128
, Expand
);
225 setOperationAction(ISD::FSINCOS
, MVT::f128
, Expand
);
226 setOperationAction(ISD::FSQRT
, MVT::f128
, Expand
);
227 setOperationAction(ISD::FSUB
, MVT::f128
, Custom
);
228 setOperationAction(ISD::FTRUNC
, MVT::f128
, Expand
);
229 setOperationAction(ISD::SETCC
, MVT::f128
, Custom
);
230 setOperationAction(ISD::BR_CC
, MVT::f128
, Custom
);
231 setOperationAction(ISD::SELECT
, MVT::f128
, Custom
);
232 setOperationAction(ISD::SELECT_CC
, MVT::f128
, Custom
);
233 setOperationAction(ISD::FP_EXTEND
, MVT::f128
, Custom
);
235 // Lowering for many of the conversions is actually specified by the non-f128
236 // type. The LowerXXX function will be trivial when f128 isn't involved.
237 setOperationAction(ISD::FP_TO_SINT
, MVT::i32
, Custom
);
238 setOperationAction(ISD::FP_TO_SINT
, MVT::i64
, Custom
);
239 setOperationAction(ISD::FP_TO_SINT
, MVT::i128
, Custom
);
240 setOperationAction(ISD::FP_TO_UINT
, MVT::i32
, Custom
);
241 setOperationAction(ISD::FP_TO_UINT
, MVT::i64
, Custom
);
242 setOperationAction(ISD::FP_TO_UINT
, MVT::i128
, Custom
);
243 setOperationAction(ISD::SINT_TO_FP
, MVT::i32
, Custom
);
244 setOperationAction(ISD::SINT_TO_FP
, MVT::i64
, Custom
);
245 setOperationAction(ISD::SINT_TO_FP
, MVT::i128
, Custom
);
246 setOperationAction(ISD::UINT_TO_FP
, MVT::i32
, Custom
);
247 setOperationAction(ISD::UINT_TO_FP
, MVT::i64
, Custom
);
248 setOperationAction(ISD::UINT_TO_FP
, MVT::i128
, Custom
);
249 setOperationAction(ISD::FP_ROUND
, MVT::f32
, Custom
);
250 setOperationAction(ISD::FP_ROUND
, MVT::f64
, Custom
);
252 // Variable arguments.
253 setOperationAction(ISD::VASTART
, MVT::Other
, Custom
);
254 setOperationAction(ISD::VAARG
, MVT::Other
, Custom
);
255 setOperationAction(ISD::VACOPY
, MVT::Other
, Custom
);
256 setOperationAction(ISD::VAEND
, MVT::Other
, Expand
);
258 // Variable-sized objects.
259 setOperationAction(ISD::STACKSAVE
, MVT::Other
, Expand
);
260 setOperationAction(ISD::STACKRESTORE
, MVT::Other
, Expand
);
262 if (Subtarget
->isTargetWindows())
263 setOperationAction(ISD::DYNAMIC_STACKALLOC
, MVT::i64
, Custom
);
265 setOperationAction(ISD::DYNAMIC_STACKALLOC
, MVT::i64
, Expand
);
267 // Constant pool entries
268 setOperationAction(ISD::ConstantPool
, MVT::i64
, Custom
);
271 setOperationAction(ISD::BlockAddress
, MVT::i64
, Custom
);
273 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
274 setOperationAction(ISD::ADDC
, MVT::i32
, Custom
);
275 setOperationAction(ISD::ADDE
, MVT::i32
, Custom
);
276 setOperationAction(ISD::SUBC
, MVT::i32
, Custom
);
277 setOperationAction(ISD::SUBE
, MVT::i32
, Custom
);
278 setOperationAction(ISD::ADDC
, MVT::i64
, Custom
);
279 setOperationAction(ISD::ADDE
, MVT::i64
, Custom
);
280 setOperationAction(ISD::SUBC
, MVT::i64
, Custom
);
281 setOperationAction(ISD::SUBE
, MVT::i64
, Custom
);
283 // AArch64 lacks both left-rotate and popcount instructions.
284 setOperationAction(ISD::ROTL
, MVT::i32
, Expand
);
285 setOperationAction(ISD::ROTL
, MVT::i64
, Expand
);
286 for (MVT VT
: MVT::vector_valuetypes()) {
287 setOperationAction(ISD::ROTL
, VT
, Expand
);
288 setOperationAction(ISD::ROTR
, VT
, Expand
);
291 // AArch64 doesn't have {U|S}MUL_LOHI.
292 setOperationAction(ISD::UMUL_LOHI
, MVT::i64
, Expand
);
293 setOperationAction(ISD::SMUL_LOHI
, MVT::i64
, Expand
);
295 setOperationAction(ISD::CTPOP
, MVT::i32
, Custom
);
296 setOperationAction(ISD::CTPOP
, MVT::i64
, Custom
);
298 setOperationAction(ISD::SDIVREM
, MVT::i32
, Expand
);
299 setOperationAction(ISD::SDIVREM
, MVT::i64
, Expand
);
300 for (MVT VT
: MVT::vector_valuetypes()) {
301 setOperationAction(ISD::SDIVREM
, VT
, Expand
);
302 setOperationAction(ISD::UDIVREM
, VT
, Expand
);
304 setOperationAction(ISD::SREM
, MVT::i32
, Expand
);
305 setOperationAction(ISD::SREM
, MVT::i64
, Expand
);
306 setOperationAction(ISD::UDIVREM
, MVT::i32
, Expand
);
307 setOperationAction(ISD::UDIVREM
, MVT::i64
, Expand
);
308 setOperationAction(ISD::UREM
, MVT::i32
, Expand
);
309 setOperationAction(ISD::UREM
, MVT::i64
, Expand
);
311 // Custom lower Add/Sub/Mul with overflow.
312 setOperationAction(ISD::SADDO
, MVT::i32
, Custom
);
313 setOperationAction(ISD::SADDO
, MVT::i64
, Custom
);
314 setOperationAction(ISD::UADDO
, MVT::i32
, Custom
);
315 setOperationAction(ISD::UADDO
, MVT::i64
, Custom
);
316 setOperationAction(ISD::SSUBO
, MVT::i32
, Custom
);
317 setOperationAction(ISD::SSUBO
, MVT::i64
, Custom
);
318 setOperationAction(ISD::USUBO
, MVT::i32
, Custom
);
319 setOperationAction(ISD::USUBO
, MVT::i64
, Custom
);
320 setOperationAction(ISD::SMULO
, MVT::i32
, Custom
);
321 setOperationAction(ISD::SMULO
, MVT::i64
, Custom
);
322 setOperationAction(ISD::UMULO
, MVT::i32
, Custom
);
323 setOperationAction(ISD::UMULO
, MVT::i64
, Custom
);
325 setOperationAction(ISD::FSIN
, MVT::f32
, Expand
);
326 setOperationAction(ISD::FSIN
, MVT::f64
, Expand
);
327 setOperationAction(ISD::FCOS
, MVT::f32
, Expand
);
328 setOperationAction(ISD::FCOS
, MVT::f64
, Expand
);
329 setOperationAction(ISD::FPOW
, MVT::f32
, Expand
);
330 setOperationAction(ISD::FPOW
, MVT::f64
, Expand
);
331 setOperationAction(ISD::FCOPYSIGN
, MVT::f64
, Custom
);
332 setOperationAction(ISD::FCOPYSIGN
, MVT::f32
, Custom
);
333 if (Subtarget
->hasFullFP16())
334 setOperationAction(ISD::FCOPYSIGN
, MVT::f16
, Custom
);
336 setOperationAction(ISD::FCOPYSIGN
, MVT::f16
, Promote
);
338 setOperationAction(ISD::FREM
, MVT::f16
, Promote
);
339 setOperationAction(ISD::FREM
, MVT::v4f16
, Expand
);
340 setOperationAction(ISD::FREM
, MVT::v8f16
, Expand
);
341 setOperationAction(ISD::FPOW
, MVT::f16
, Promote
);
342 setOperationAction(ISD::FPOW
, MVT::v4f16
, Expand
);
343 setOperationAction(ISD::FPOW
, MVT::v8f16
, Expand
);
344 setOperationAction(ISD::FPOWI
, MVT::f16
, Promote
);
345 setOperationAction(ISD::FPOWI
, MVT::v4f16
, Expand
);
346 setOperationAction(ISD::FPOWI
, MVT::v8f16
, Expand
);
347 setOperationAction(ISD::FCOS
, MVT::f16
, Promote
);
348 setOperationAction(ISD::FCOS
, MVT::v4f16
, Expand
);
349 setOperationAction(ISD::FCOS
, MVT::v8f16
, Expand
);
350 setOperationAction(ISD::FSIN
, MVT::f16
, Promote
);
351 setOperationAction(ISD::FSIN
, MVT::v4f16
, Expand
);
352 setOperationAction(ISD::FSIN
, MVT::v8f16
, Expand
);
353 setOperationAction(ISD::FSINCOS
, MVT::f16
, Promote
);
354 setOperationAction(ISD::FSINCOS
, MVT::v4f16
, Expand
);
355 setOperationAction(ISD::FSINCOS
, MVT::v8f16
, Expand
);
356 setOperationAction(ISD::FEXP
, MVT::f16
, Promote
);
357 setOperationAction(ISD::FEXP
, MVT::v4f16
, Expand
);
358 setOperationAction(ISD::FEXP
, MVT::v8f16
, Expand
);
359 setOperationAction(ISD::FEXP2
, MVT::f16
, Promote
);
360 setOperationAction(ISD::FEXP2
, MVT::v4f16
, Expand
);
361 setOperationAction(ISD::FEXP2
, MVT::v8f16
, Expand
);
362 setOperationAction(ISD::FLOG
, MVT::f16
, Promote
);
363 setOperationAction(ISD::FLOG
, MVT::v4f16
, Expand
);
364 setOperationAction(ISD::FLOG
, MVT::v8f16
, Expand
);
365 setOperationAction(ISD::FLOG2
, MVT::f16
, Promote
);
366 setOperationAction(ISD::FLOG2
, MVT::v4f16
, Expand
);
367 setOperationAction(ISD::FLOG2
, MVT::v8f16
, Expand
);
368 setOperationAction(ISD::FLOG10
, MVT::f16
, Promote
);
369 setOperationAction(ISD::FLOG10
, MVT::v4f16
, Expand
);
370 setOperationAction(ISD::FLOG10
, MVT::v8f16
, Expand
);
372 if (!Subtarget
->hasFullFP16()) {
373 setOperationAction(ISD::SELECT
, MVT::f16
, Promote
);
374 setOperationAction(ISD::SELECT_CC
, MVT::f16
, Promote
);
375 setOperationAction(ISD::SETCC
, MVT::f16
, Promote
);
376 setOperationAction(ISD::BR_CC
, MVT::f16
, Promote
);
377 setOperationAction(ISD::FADD
, MVT::f16
, Promote
);
378 setOperationAction(ISD::FSUB
, MVT::f16
, Promote
);
379 setOperationAction(ISD::FMUL
, MVT::f16
, Promote
);
380 setOperationAction(ISD::FDIV
, MVT::f16
, Promote
);
381 setOperationAction(ISD::FMA
, MVT::f16
, Promote
);
382 setOperationAction(ISD::FNEG
, MVT::f16
, Promote
);
383 setOperationAction(ISD::FABS
, MVT::f16
, Promote
);
384 setOperationAction(ISD::FCEIL
, MVT::f16
, Promote
);
385 setOperationAction(ISD::FSQRT
, MVT::f16
, Promote
);
386 setOperationAction(ISD::FFLOOR
, MVT::f16
, Promote
);
387 setOperationAction(ISD::FNEARBYINT
, MVT::f16
, Promote
);
388 setOperationAction(ISD::FRINT
, MVT::f16
, Promote
);
389 setOperationAction(ISD::FROUND
, MVT::f16
, Promote
);
390 setOperationAction(ISD::FTRUNC
, MVT::f16
, Promote
);
391 setOperationAction(ISD::FMINNUM
, MVT::f16
, Promote
);
392 setOperationAction(ISD::FMAXNUM
, MVT::f16
, Promote
);
393 setOperationAction(ISD::FMINIMUM
, MVT::f16
, Promote
);
394 setOperationAction(ISD::FMAXIMUM
, MVT::f16
, Promote
);
396 // promote v4f16 to v4f32 when that is known to be safe.
397 setOperationAction(ISD::FADD
, MVT::v4f16
, Promote
);
398 setOperationAction(ISD::FSUB
, MVT::v4f16
, Promote
);
399 setOperationAction(ISD::FMUL
, MVT::v4f16
, Promote
);
400 setOperationAction(ISD::FDIV
, MVT::v4f16
, Promote
);
401 setOperationAction(ISD::FP_EXTEND
, MVT::v4f16
, Promote
);
402 setOperationAction(ISD::FP_ROUND
, MVT::v4f16
, Promote
);
403 AddPromotedToType(ISD::FADD
, MVT::v4f16
, MVT::v4f32
);
404 AddPromotedToType(ISD::FSUB
, MVT::v4f16
, MVT::v4f32
);
405 AddPromotedToType(ISD::FMUL
, MVT::v4f16
, MVT::v4f32
);
406 AddPromotedToType(ISD::FDIV
, MVT::v4f16
, MVT::v4f32
);
407 AddPromotedToType(ISD::FP_EXTEND
, MVT::v4f16
, MVT::v4f32
);
408 AddPromotedToType(ISD::FP_ROUND
, MVT::v4f16
, MVT::v4f32
);
410 setOperationAction(ISD::FABS
, MVT::v4f16
, Expand
);
411 setOperationAction(ISD::FNEG
, MVT::v4f16
, Expand
);
412 setOperationAction(ISD::FROUND
, MVT::v4f16
, Expand
);
413 setOperationAction(ISD::FMA
, MVT::v4f16
, Expand
);
414 setOperationAction(ISD::SETCC
, MVT::v4f16
, Expand
);
415 setOperationAction(ISD::BR_CC
, MVT::v4f16
, Expand
);
416 setOperationAction(ISD::SELECT
, MVT::v4f16
, Expand
);
417 setOperationAction(ISD::SELECT_CC
, MVT::v4f16
, Expand
);
418 setOperationAction(ISD::FTRUNC
, MVT::v4f16
, Expand
);
419 setOperationAction(ISD::FCOPYSIGN
, MVT::v4f16
, Expand
);
420 setOperationAction(ISD::FFLOOR
, MVT::v4f16
, Expand
);
421 setOperationAction(ISD::FCEIL
, MVT::v4f16
, Expand
);
422 setOperationAction(ISD::FRINT
, MVT::v4f16
, Expand
);
423 setOperationAction(ISD::FNEARBYINT
, MVT::v4f16
, Expand
);
424 setOperationAction(ISD::FSQRT
, MVT::v4f16
, Expand
);
426 setOperationAction(ISD::FABS
, MVT::v8f16
, Expand
);
427 setOperationAction(ISD::FADD
, MVT::v8f16
, Expand
);
428 setOperationAction(ISD::FCEIL
, MVT::v8f16
, Expand
);
429 setOperationAction(ISD::FCOPYSIGN
, MVT::v8f16
, Expand
);
430 setOperationAction(ISD::FDIV
, MVT::v8f16
, Expand
);
431 setOperationAction(ISD::FFLOOR
, MVT::v8f16
, Expand
);
432 setOperationAction(ISD::FMA
, MVT::v8f16
, Expand
);
433 setOperationAction(ISD::FMUL
, MVT::v8f16
, Expand
);
434 setOperationAction(ISD::FNEARBYINT
, MVT::v8f16
, Expand
);
435 setOperationAction(ISD::FNEG
, MVT::v8f16
, Expand
);
436 setOperationAction(ISD::FROUND
, MVT::v8f16
, Expand
);
437 setOperationAction(ISD::FRINT
, MVT::v8f16
, Expand
);
438 setOperationAction(ISD::FSQRT
, MVT::v8f16
, Expand
);
439 setOperationAction(ISD::FSUB
, MVT::v8f16
, Expand
);
440 setOperationAction(ISD::FTRUNC
, MVT::v8f16
, Expand
);
441 setOperationAction(ISD::SETCC
, MVT::v8f16
, Expand
);
442 setOperationAction(ISD::BR_CC
, MVT::v8f16
, Expand
);
443 setOperationAction(ISD::SELECT
, MVT::v8f16
, Expand
);
444 setOperationAction(ISD::SELECT_CC
, MVT::v8f16
, Expand
);
445 setOperationAction(ISD::FP_EXTEND
, MVT::v8f16
, Expand
);
448 // AArch64 has implementations of a lot of rounding-like FP operations.
449 for (MVT Ty
: {MVT::f32
, MVT::f64
}) {
450 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
451 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
452 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
453 setOperationAction(ISD::FRINT
, Ty
, Legal
);
454 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
455 setOperationAction(ISD::FROUND
, Ty
, Legal
);
456 setOperationAction(ISD::FMINNUM
, Ty
, Legal
);
457 setOperationAction(ISD::FMAXNUM
, Ty
, Legal
);
458 setOperationAction(ISD::FMINIMUM
, Ty
, Legal
);
459 setOperationAction(ISD::FMAXIMUM
, Ty
, Legal
);
460 setOperationAction(ISD::LROUND
, Ty
, Legal
);
461 setOperationAction(ISD::LLROUND
, Ty
, Legal
);
462 setOperationAction(ISD::LRINT
, Ty
, Legal
);
463 setOperationAction(ISD::LLRINT
, Ty
, Legal
);
466 if (Subtarget
->hasFullFP16()) {
467 setOperationAction(ISD::FNEARBYINT
, MVT::f16
, Legal
);
468 setOperationAction(ISD::FFLOOR
, MVT::f16
, Legal
);
469 setOperationAction(ISD::FCEIL
, MVT::f16
, Legal
);
470 setOperationAction(ISD::FRINT
, MVT::f16
, Legal
);
471 setOperationAction(ISD::FTRUNC
, MVT::f16
, Legal
);
472 setOperationAction(ISD::FROUND
, MVT::f16
, Legal
);
473 setOperationAction(ISD::FMINNUM
, MVT::f16
, Legal
);
474 setOperationAction(ISD::FMAXNUM
, MVT::f16
, Legal
);
475 setOperationAction(ISD::FMINIMUM
, MVT::f16
, Legal
);
476 setOperationAction(ISD::FMAXIMUM
, MVT::f16
, Legal
);
479 setOperationAction(ISD::PREFETCH
, MVT::Other
, Custom
);
481 setOperationAction(ISD::FLT_ROUNDS_
, MVT::i32
, Custom
);
483 setOperationAction(ISD::ATOMIC_CMP_SWAP
, MVT::i128
, Custom
);
484 setOperationAction(ISD::ATOMIC_LOAD_SUB
, MVT::i32
, Custom
);
485 setOperationAction(ISD::ATOMIC_LOAD_SUB
, MVT::i64
, Custom
);
486 setOperationAction(ISD::ATOMIC_LOAD_AND
, MVT::i32
, Custom
);
487 setOperationAction(ISD::ATOMIC_LOAD_AND
, MVT::i64
, Custom
);
489 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
490 // This requires the Performance Monitors extension.
491 if (Subtarget
->hasPerfMon())
492 setOperationAction(ISD::READCYCLECOUNTER
, MVT::i64
, Legal
);
494 if (getLibcallName(RTLIB::SINCOS_STRET_F32
) != nullptr &&
495 getLibcallName(RTLIB::SINCOS_STRET_F64
) != nullptr) {
496 // Issue __sincos_stret if available.
497 setOperationAction(ISD::FSINCOS
, MVT::f64
, Custom
);
498 setOperationAction(ISD::FSINCOS
, MVT::f32
, Custom
);
500 setOperationAction(ISD::FSINCOS
, MVT::f64
, Expand
);
501 setOperationAction(ISD::FSINCOS
, MVT::f32
, Expand
);
504 // Make floating-point constants legal for the large code model, so they don't
505 // become loads from the constant pool.
506 if (Subtarget
->isTargetMachO() && TM
.getCodeModel() == CodeModel::Large
) {
507 setOperationAction(ISD::ConstantFP
, MVT::f32
, Legal
);
508 setOperationAction(ISD::ConstantFP
, MVT::f64
, Legal
);
511 // AArch64 does not have floating-point extending loads, i1 sign-extending
512 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
513 for (MVT VT
: MVT::fp_valuetypes()) {
514 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f16
, Expand
);
515 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f32
, Expand
);
516 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f64
, Expand
);
517 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f80
, Expand
);
519 for (MVT VT
: MVT::integer_valuetypes())
520 setLoadExtAction(ISD::SEXTLOAD
, VT
, MVT::i1
, Expand
);
522 setTruncStoreAction(MVT::f32
, MVT::f16
, Expand
);
523 setTruncStoreAction(MVT::f64
, MVT::f32
, Expand
);
524 setTruncStoreAction(MVT::f64
, MVT::f16
, Expand
);
525 setTruncStoreAction(MVT::f128
, MVT::f80
, Expand
);
526 setTruncStoreAction(MVT::f128
, MVT::f64
, Expand
);
527 setTruncStoreAction(MVT::f128
, MVT::f32
, Expand
);
528 setTruncStoreAction(MVT::f128
, MVT::f16
, Expand
);
530 setOperationAction(ISD::BITCAST
, MVT::i16
, Custom
);
531 setOperationAction(ISD::BITCAST
, MVT::f16
, Custom
);
533 // Indexed loads and stores are supported.
534 for (unsigned im
= (unsigned)ISD::PRE_INC
;
535 im
!= (unsigned)ISD::LAST_INDEXED_MODE
; ++im
) {
536 setIndexedLoadAction(im
, MVT::i8
, Legal
);
537 setIndexedLoadAction(im
, MVT::i16
, Legal
);
538 setIndexedLoadAction(im
, MVT::i32
, Legal
);
539 setIndexedLoadAction(im
, MVT::i64
, Legal
);
540 setIndexedLoadAction(im
, MVT::f64
, Legal
);
541 setIndexedLoadAction(im
, MVT::f32
, Legal
);
542 setIndexedLoadAction(im
, MVT::f16
, Legal
);
543 setIndexedStoreAction(im
, MVT::i8
, Legal
);
544 setIndexedStoreAction(im
, MVT::i16
, Legal
);
545 setIndexedStoreAction(im
, MVT::i32
, Legal
);
546 setIndexedStoreAction(im
, MVT::i64
, Legal
);
547 setIndexedStoreAction(im
, MVT::f64
, Legal
);
548 setIndexedStoreAction(im
, MVT::f32
, Legal
);
549 setIndexedStoreAction(im
, MVT::f16
, Legal
);
553 setOperationAction(ISD::TRAP
, MVT::Other
, Legal
);
554 if (Subtarget
->isTargetWindows())
555 setOperationAction(ISD::DEBUGTRAP
, MVT::Other
, Legal
);
557 // We combine OR nodes for bitfield operations.
558 setTargetDAGCombine(ISD::OR
);
559 // Try to create BICs for vector ANDs.
560 setTargetDAGCombine(ISD::AND
);
562 // Vector add and sub nodes may conceal a high-half opportunity.
563 // Also, try to fold ADD into CSINC/CSINV..
564 setTargetDAGCombine(ISD::ADD
);
565 setTargetDAGCombine(ISD::SUB
);
566 setTargetDAGCombine(ISD::SRL
);
567 setTargetDAGCombine(ISD::XOR
);
568 setTargetDAGCombine(ISD::SINT_TO_FP
);
569 setTargetDAGCombine(ISD::UINT_TO_FP
);
571 setTargetDAGCombine(ISD::FP_TO_SINT
);
572 setTargetDAGCombine(ISD::FP_TO_UINT
);
573 setTargetDAGCombine(ISD::FDIV
);
575 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN
);
577 setTargetDAGCombine(ISD::ANY_EXTEND
);
578 setTargetDAGCombine(ISD::ZERO_EXTEND
);
579 setTargetDAGCombine(ISD::SIGN_EXTEND
);
580 setTargetDAGCombine(ISD::BITCAST
);
581 setTargetDAGCombine(ISD::CONCAT_VECTORS
);
582 setTargetDAGCombine(ISD::STORE
);
583 if (Subtarget
->supportsAddressTopByteIgnored())
584 setTargetDAGCombine(ISD::LOAD
);
586 setTargetDAGCombine(ISD::MUL
);
588 setTargetDAGCombine(ISD::SELECT
);
589 setTargetDAGCombine(ISD::VSELECT
);
591 setTargetDAGCombine(ISD::INTRINSIC_VOID
);
592 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN
);
593 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT
);
595 setTargetDAGCombine(ISD::GlobalAddress
);
597 // In case of strict alignment, avoid an excessive number of byte wide stores.
598 MaxStoresPerMemsetOptSize
= 8;
599 MaxStoresPerMemset
= Subtarget
->requiresStrictAlign()
600 ? MaxStoresPerMemsetOptSize
: 32;
602 MaxGluedStoresPerMemcpy
= 4;
603 MaxStoresPerMemcpyOptSize
= 4;
604 MaxStoresPerMemcpy
= Subtarget
->requiresStrictAlign()
605 ? MaxStoresPerMemcpyOptSize
: 16;
607 MaxStoresPerMemmoveOptSize
= MaxStoresPerMemmove
= 4;
609 setStackPointerRegisterToSaveRestore(AArch64::SP
);
611 setSchedulingPreference(Sched::Hybrid
);
613 EnableExtLdPromotion
= true;
615 // Set required alignment.
616 setMinFunctionAlignment(2);
617 // Set preferred alignments.
618 setPrefFunctionAlignment(STI
.getPrefFunctionAlignment());
619 setPrefLoopAlignment(STI
.getPrefLoopAlignment());
621 // Only change the limit for entries in a jump table if specified by
622 // the sub target, but not at the command line.
623 unsigned MaxJT
= STI
.getMaximumJumpTableSize();
624 if (MaxJT
&& getMaximumJumpTableSize() == UINT_MAX
)
625 setMaximumJumpTableSize(MaxJT
);
627 setHasExtractBitsInsn(true);
629 setOperationAction(ISD::INTRINSIC_WO_CHAIN
, MVT::Other
, Custom
);
631 if (Subtarget
->hasNEON()) {
632 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
633 // silliness like this:
634 setOperationAction(ISD::FABS
, MVT::v1f64
, Expand
);
635 setOperationAction(ISD::FADD
, MVT::v1f64
, Expand
);
636 setOperationAction(ISD::FCEIL
, MVT::v1f64
, Expand
);
637 setOperationAction(ISD::FCOPYSIGN
, MVT::v1f64
, Expand
);
638 setOperationAction(ISD::FCOS
, MVT::v1f64
, Expand
);
639 setOperationAction(ISD::FDIV
, MVT::v1f64
, Expand
);
640 setOperationAction(ISD::FFLOOR
, MVT::v1f64
, Expand
);
641 setOperationAction(ISD::FMA
, MVT::v1f64
, Expand
);
642 setOperationAction(ISD::FMUL
, MVT::v1f64
, Expand
);
643 setOperationAction(ISD::FNEARBYINT
, MVT::v1f64
, Expand
);
644 setOperationAction(ISD::FNEG
, MVT::v1f64
, Expand
);
645 setOperationAction(ISD::FPOW
, MVT::v1f64
, Expand
);
646 setOperationAction(ISD::FREM
, MVT::v1f64
, Expand
);
647 setOperationAction(ISD::FROUND
, MVT::v1f64
, Expand
);
648 setOperationAction(ISD::FRINT
, MVT::v1f64
, Expand
);
649 setOperationAction(ISD::FSIN
, MVT::v1f64
, Expand
);
650 setOperationAction(ISD::FSINCOS
, MVT::v1f64
, Expand
);
651 setOperationAction(ISD::FSQRT
, MVT::v1f64
, Expand
);
652 setOperationAction(ISD::FSUB
, MVT::v1f64
, Expand
);
653 setOperationAction(ISD::FTRUNC
, MVT::v1f64
, Expand
);
654 setOperationAction(ISD::SETCC
, MVT::v1f64
, Expand
);
655 setOperationAction(ISD::BR_CC
, MVT::v1f64
, Expand
);
656 setOperationAction(ISD::SELECT
, MVT::v1f64
, Expand
);
657 setOperationAction(ISD::SELECT_CC
, MVT::v1f64
, Expand
);
658 setOperationAction(ISD::FP_EXTEND
, MVT::v1f64
, Expand
);
660 setOperationAction(ISD::FP_TO_SINT
, MVT::v1i64
, Expand
);
661 setOperationAction(ISD::FP_TO_UINT
, MVT::v1i64
, Expand
);
662 setOperationAction(ISD::SINT_TO_FP
, MVT::v1i64
, Expand
);
663 setOperationAction(ISD::UINT_TO_FP
, MVT::v1i64
, Expand
);
664 setOperationAction(ISD::FP_ROUND
, MVT::v1f64
, Expand
);
666 setOperationAction(ISD::MUL
, MVT::v1i64
, Expand
);
668 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
669 // elements smaller than i32, so promote the input to i32 first.
670 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v4i8
, MVT::v4i32
);
671 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v4i8
, MVT::v4i32
);
672 // i8 vector elements also need promotion to i32 for v8i8
673 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v8i8
, MVT::v8i32
);
674 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v8i8
, MVT::v8i32
);
675 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
676 setOperationAction(ISD::SINT_TO_FP
, MVT::v2i32
, Custom
);
677 setOperationAction(ISD::UINT_TO_FP
, MVT::v2i32
, Custom
);
678 setOperationAction(ISD::SINT_TO_FP
, MVT::v2i64
, Custom
);
679 setOperationAction(ISD::UINT_TO_FP
, MVT::v2i64
, Custom
);
680 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
681 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
682 setOperationAction(ISD::SINT_TO_FP
, MVT::v4i32
, Custom
);
683 setOperationAction(ISD::UINT_TO_FP
, MVT::v4i32
, Custom
);
685 if (Subtarget
->hasFullFP16()) {
686 setOperationAction(ISD::SINT_TO_FP
, MVT::v4i16
, Custom
);
687 setOperationAction(ISD::UINT_TO_FP
, MVT::v4i16
, Custom
);
688 setOperationAction(ISD::SINT_TO_FP
, MVT::v8i16
, Custom
);
689 setOperationAction(ISD::UINT_TO_FP
, MVT::v8i16
, Custom
);
691 // when AArch64 doesn't have fullfp16 support, promote the input
693 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v4i16
, MVT::v4i32
);
694 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v4i16
, MVT::v4i32
);
695 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v8i16
, MVT::v8i32
);
696 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v8i16
, MVT::v8i32
);
699 setOperationAction(ISD::CTLZ
, MVT::v1i64
, Expand
);
700 setOperationAction(ISD::CTLZ
, MVT::v2i64
, Expand
);
702 // AArch64 doesn't have MUL.2d:
703 setOperationAction(ISD::MUL
, MVT::v2i64
, Expand
);
704 // Custom handling for some quad-vector types to detect MULL.
705 setOperationAction(ISD::MUL
, MVT::v8i16
, Custom
);
706 setOperationAction(ISD::MUL
, MVT::v4i32
, Custom
);
707 setOperationAction(ISD::MUL
, MVT::v2i64
, Custom
);
710 for (MVT VT
: { MVT::v8i8
, MVT::v4i16
, MVT::v2i32
,
711 MVT::v16i8
, MVT::v8i16
, MVT::v4i32
, MVT::v2i64
}) {
712 setOperationAction(ISD::VECREDUCE_ADD
, VT
, Custom
);
713 setOperationAction(ISD::VECREDUCE_SMAX
, VT
, Custom
);
714 setOperationAction(ISD::VECREDUCE_SMIN
, VT
, Custom
);
715 setOperationAction(ISD::VECREDUCE_UMAX
, VT
, Custom
);
716 setOperationAction(ISD::VECREDUCE_UMIN
, VT
, Custom
);
718 for (MVT VT
: { MVT::v4f16
, MVT::v2f32
,
719 MVT::v8f16
, MVT::v4f32
, MVT::v2f64
}) {
720 setOperationAction(ISD::VECREDUCE_FMAX
, VT
, Custom
);
721 setOperationAction(ISD::VECREDUCE_FMIN
, VT
, Custom
);
724 setOperationAction(ISD::ANY_EXTEND
, MVT::v4i32
, Legal
);
725 setTruncStoreAction(MVT::v2i32
, MVT::v2i16
, Expand
);
726 // Likewise, narrowing and extending vector loads/stores aren't handled
728 for (MVT VT
: MVT::vector_valuetypes()) {
729 setOperationAction(ISD::SIGN_EXTEND_INREG
, VT
, Expand
);
731 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
) {
732 setOperationAction(ISD::MULHS
, VT
, Legal
);
733 setOperationAction(ISD::MULHU
, VT
, Legal
);
735 setOperationAction(ISD::MULHS
, VT
, Expand
);
736 setOperationAction(ISD::MULHU
, VT
, Expand
);
738 setOperationAction(ISD::SMUL_LOHI
, VT
, Expand
);
739 setOperationAction(ISD::UMUL_LOHI
, VT
, Expand
);
741 setOperationAction(ISD::BSWAP
, VT
, Expand
);
742 setOperationAction(ISD::CTTZ
, VT
, Expand
);
744 for (MVT InnerVT
: MVT::vector_valuetypes()) {
745 setTruncStoreAction(VT
, InnerVT
, Expand
);
746 setLoadExtAction(ISD::SEXTLOAD
, VT
, InnerVT
, Expand
);
747 setLoadExtAction(ISD::ZEXTLOAD
, VT
, InnerVT
, Expand
);
748 setLoadExtAction(ISD::EXTLOAD
, VT
, InnerVT
, Expand
);
752 // AArch64 has implementations of a lot of rounding-like FP operations.
753 for (MVT Ty
: {MVT::v2f32
, MVT::v4f32
, MVT::v2f64
}) {
754 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
755 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
756 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
757 setOperationAction(ISD::FRINT
, Ty
, Legal
);
758 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
759 setOperationAction(ISD::FROUND
, Ty
, Legal
);
762 if (Subtarget
->hasFullFP16()) {
763 for (MVT Ty
: {MVT::v4f16
, MVT::v8f16
}) {
764 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
765 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
766 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
767 setOperationAction(ISD::FRINT
, Ty
, Legal
);
768 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
769 setOperationAction(ISD::FROUND
, Ty
, Legal
);
773 setTruncStoreAction(MVT::v4i16
, MVT::v4i8
, Custom
);
776 PredictableSelectIsExpensive
= Subtarget
->predictableSelectIsExpensive();
779 void AArch64TargetLowering::addTypeForNEON(MVT VT
, MVT PromotedBitwiseVT
) {
780 assert(VT
.isVector() && "VT should be a vector type");
782 if (VT
.isFloatingPoint()) {
783 MVT PromoteTo
= EVT(VT
).changeVectorElementTypeToInteger().getSimpleVT();
784 setOperationPromotedToType(ISD::LOAD
, VT
, PromoteTo
);
785 setOperationPromotedToType(ISD::STORE
, VT
, PromoteTo
);
788 // Mark vector float intrinsics as expand.
789 if (VT
== MVT::v2f32
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
) {
790 setOperationAction(ISD::FSIN
, VT
, Expand
);
791 setOperationAction(ISD::FCOS
, VT
, Expand
);
792 setOperationAction(ISD::FPOW
, VT
, Expand
);
793 setOperationAction(ISD::FLOG
, VT
, Expand
);
794 setOperationAction(ISD::FLOG2
, VT
, Expand
);
795 setOperationAction(ISD::FLOG10
, VT
, Expand
);
796 setOperationAction(ISD::FEXP
, VT
, Expand
);
797 setOperationAction(ISD::FEXP2
, VT
, Expand
);
799 // But we do support custom-lowering for FCOPYSIGN.
800 setOperationAction(ISD::FCOPYSIGN
, VT
, Custom
);
803 setOperationAction(ISD::EXTRACT_VECTOR_ELT
, VT
, Custom
);
804 setOperationAction(ISD::INSERT_VECTOR_ELT
, VT
, Custom
);
805 setOperationAction(ISD::BUILD_VECTOR
, VT
, Custom
);
806 setOperationAction(ISD::VECTOR_SHUFFLE
, VT
, Custom
);
807 setOperationAction(ISD::EXTRACT_SUBVECTOR
, VT
, Custom
);
808 setOperationAction(ISD::SRA
, VT
, Custom
);
809 setOperationAction(ISD::SRL
, VT
, Custom
);
810 setOperationAction(ISD::SHL
, VT
, Custom
);
811 setOperationAction(ISD::OR
, VT
, Custom
);
812 setOperationAction(ISD::SETCC
, VT
, Custom
);
813 setOperationAction(ISD::CONCAT_VECTORS
, VT
, Legal
);
815 setOperationAction(ISD::SELECT
, VT
, Expand
);
816 setOperationAction(ISD::SELECT_CC
, VT
, Expand
);
817 setOperationAction(ISD::VSELECT
, VT
, Expand
);
818 for (MVT InnerVT
: MVT::all_valuetypes())
819 setLoadExtAction(ISD::EXTLOAD
, InnerVT
, VT
, Expand
);
821 // CNT supports only B element sizes, then use UADDLP to widen.
822 if (VT
!= MVT::v8i8
&& VT
!= MVT::v16i8
)
823 setOperationAction(ISD::CTPOP
, VT
, Custom
);
825 setOperationAction(ISD::UDIV
, VT
, Expand
);
826 setOperationAction(ISD::SDIV
, VT
, Expand
);
827 setOperationAction(ISD::UREM
, VT
, Expand
);
828 setOperationAction(ISD::SREM
, VT
, Expand
);
829 setOperationAction(ISD::FREM
, VT
, Expand
);
831 setOperationAction(ISD::FP_TO_SINT
, VT
, Custom
);
832 setOperationAction(ISD::FP_TO_UINT
, VT
, Custom
);
834 if (!VT
.isFloatingPoint())
835 setOperationAction(ISD::ABS
, VT
, Legal
);
837 // [SU][MIN|MAX] are available for all NEON types apart from i64.
838 if (!VT
.isFloatingPoint() && VT
!= MVT::v2i64
&& VT
!= MVT::v1i64
)
839 for (unsigned Opcode
: {ISD::SMIN
, ISD::SMAX
, ISD::UMIN
, ISD::UMAX
})
840 setOperationAction(Opcode
, VT
, Legal
);
842 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
843 if (VT
.isFloatingPoint() &&
844 (VT
.getVectorElementType() != MVT::f16
|| Subtarget
->hasFullFP16()))
845 for (unsigned Opcode
:
846 {ISD::FMINIMUM
, ISD::FMAXIMUM
, ISD::FMINNUM
, ISD::FMAXNUM
})
847 setOperationAction(Opcode
, VT
, Legal
);
849 if (Subtarget
->isLittleEndian()) {
850 for (unsigned im
= (unsigned)ISD::PRE_INC
;
851 im
!= (unsigned)ISD::LAST_INDEXED_MODE
; ++im
) {
852 setIndexedLoadAction(im
, VT
, Legal
);
853 setIndexedStoreAction(im
, VT
, Legal
);
858 void AArch64TargetLowering::addDRTypeForNEON(MVT VT
) {
859 addRegisterClass(VT
, &AArch64::FPR64RegClass
);
860 addTypeForNEON(VT
, MVT::v2i32
);
863 void AArch64TargetLowering::addQRTypeForNEON(MVT VT
) {
864 addRegisterClass(VT
, &AArch64::FPR128RegClass
);
865 addTypeForNEON(VT
, MVT::v4i32
);
868 EVT
AArch64TargetLowering::getSetCCResultType(const DataLayout
&, LLVMContext
&,
872 return VT
.changeVectorElementTypeToInteger();
875 static bool optimizeLogicalImm(SDValue Op
, unsigned Size
, uint64_t Imm
,
876 const APInt
&Demanded
,
877 TargetLowering::TargetLoweringOpt
&TLO
,
879 uint64_t OldImm
= Imm
, NewImm
, Enc
;
880 uint64_t Mask
= ((uint64_t)(-1LL) >> (64 - Size
)), OrigMask
= Mask
;
882 // Return if the immediate is already all zeros, all ones, a bimm32 or a
884 if (Imm
== 0 || Imm
== Mask
||
885 AArch64_AM::isLogicalImmediate(Imm
& Mask
, Size
))
888 unsigned EltSize
= Size
;
889 uint64_t DemandedBits
= Demanded
.getZExtValue();
891 // Clear bits that are not demanded.
895 // The goal here is to set the non-demanded bits in a way that minimizes
896 // the number of switching between 0 and 1. In order to achieve this goal,
897 // we set the non-demanded bits to the value of the preceding demanded bits.
898 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
899 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
900 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
901 // The final result is 0b11000011.
902 uint64_t NonDemandedBits
= ~DemandedBits
;
903 uint64_t InvertedImm
= ~Imm
& DemandedBits
;
904 uint64_t RotatedImm
=
905 ((InvertedImm
<< 1) | (InvertedImm
>> (EltSize
- 1) & 1)) &
907 uint64_t Sum
= RotatedImm
+ NonDemandedBits
;
908 bool Carry
= NonDemandedBits
& ~Sum
& (1ULL << (EltSize
- 1));
909 uint64_t Ones
= (Sum
+ Carry
) & NonDemandedBits
;
910 NewImm
= (Imm
| Ones
) & Mask
;
912 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
913 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
914 // we halve the element size and continue the search.
915 if (isShiftedMask_64(NewImm
) || isShiftedMask_64(~(NewImm
| ~Mask
)))
918 // We cannot shrink the element size any further if it is 2-bits.
924 uint64_t Hi
= Imm
>> EltSize
, DemandedBitsHi
= DemandedBits
>> EltSize
;
926 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
927 if (((Imm
^ Hi
) & (DemandedBits
& DemandedBitsHi
) & Mask
) != 0)
930 // Merge the upper and lower halves of Imm and DemandedBits.
932 DemandedBits
|= DemandedBitsHi
;
937 // Replicate the element across the register width.
938 while (EltSize
< Size
) {
939 NewImm
|= NewImm
<< EltSize
;
944 assert(((OldImm
^ NewImm
) & Demanded
.getZExtValue()) == 0 &&
945 "demanded bits should never be altered");
946 assert(OldImm
!= NewImm
&& "the new imm shouldn't be equal to the old imm");
948 // Create the new constant immediate node.
949 EVT VT
= Op
.getValueType();
953 // If the new constant immediate is all-zeros or all-ones, let the target
954 // independent DAG combine optimize this node.
955 if (NewImm
== 0 || NewImm
== OrigMask
) {
956 New
= TLO
.DAG
.getNode(Op
.getOpcode(), DL
, VT
, Op
.getOperand(0),
957 TLO
.DAG
.getConstant(NewImm
, DL
, VT
));
958 // Otherwise, create a machine node so that target independent DAG combine
959 // doesn't undo this optimization.
961 Enc
= AArch64_AM::encodeLogicalImmediate(NewImm
, Size
);
962 SDValue EncConst
= TLO
.DAG
.getTargetConstant(Enc
, DL
, VT
);
964 TLO
.DAG
.getMachineNode(NewOpc
, DL
, VT
, Op
.getOperand(0), EncConst
), 0);
967 return TLO
.CombineTo(Op
, New
);
970 bool AArch64TargetLowering::targetShrinkDemandedConstant(
971 SDValue Op
, const APInt
&Demanded
, TargetLoweringOpt
&TLO
) const {
972 // Delay this optimization to as late as possible.
976 if (!EnableOptimizeLogicalImm
)
979 EVT VT
= Op
.getValueType();
983 unsigned Size
= VT
.getSizeInBits();
984 assert((Size
== 32 || Size
== 64) &&
985 "i32 or i64 is expected after legalization.");
987 // Exit early if we demand all bits.
988 if (Demanded
.countPopulation() == Size
)
992 switch (Op
.getOpcode()) {
996 NewOpc
= Size
== 32 ? AArch64::ANDWri
: AArch64::ANDXri
;
999 NewOpc
= Size
== 32 ? AArch64::ORRWri
: AArch64::ORRXri
;
1002 NewOpc
= Size
== 32 ? AArch64::EORWri
: AArch64::EORXri
;
1005 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
1008 uint64_t Imm
= C
->getZExtValue();
1009 return optimizeLogicalImm(Op
, Size
, Imm
, Demanded
, TLO
, NewOpc
);
1012 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1013 /// Mask are known to be either zero or one and return them Known.
1014 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1015 const SDValue Op
, KnownBits
&Known
,
1016 const APInt
&DemandedElts
, const SelectionDAG
&DAG
, unsigned Depth
) const {
1017 switch (Op
.getOpcode()) {
1020 case AArch64ISD::CSEL
: {
1022 Known
= DAG
.computeKnownBits(Op
->getOperand(0), Depth
+ 1);
1023 Known2
= DAG
.computeKnownBits(Op
->getOperand(1), Depth
+ 1);
1024 Known
.Zero
&= Known2
.Zero
;
1025 Known
.One
&= Known2
.One
;
1028 case ISD::INTRINSIC_W_CHAIN
: {
1029 ConstantSDNode
*CN
= cast
<ConstantSDNode
>(Op
->getOperand(1));
1030 Intrinsic::ID IntID
= static_cast<Intrinsic::ID
>(CN
->getZExtValue());
1033 case Intrinsic::aarch64_ldaxr
:
1034 case Intrinsic::aarch64_ldxr
: {
1035 unsigned BitWidth
= Known
.getBitWidth();
1036 EVT VT
= cast
<MemIntrinsicSDNode
>(Op
)->getMemoryVT();
1037 unsigned MemBits
= VT
.getScalarSizeInBits();
1038 Known
.Zero
|= APInt::getHighBitsSet(BitWidth
, BitWidth
- MemBits
);
1044 case ISD::INTRINSIC_WO_CHAIN
:
1045 case ISD::INTRINSIC_VOID
: {
1046 unsigned IntNo
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
1050 case Intrinsic::aarch64_neon_umaxv
:
1051 case Intrinsic::aarch64_neon_uminv
: {
1052 // Figure out the datatype of the vector operand. The UMINV instruction
1053 // will zero extend the result, so we can mark as known zero all the
1054 // bits larger than the element datatype. 32-bit or larget doesn't need
1055 // this as those are legal types and will be handled by isel directly.
1056 MVT VT
= Op
.getOperand(1).getValueType().getSimpleVT();
1057 unsigned BitWidth
= Known
.getBitWidth();
1058 if (VT
== MVT::v8i8
|| VT
== MVT::v16i8
) {
1059 assert(BitWidth
>= 8 && "Unexpected width!");
1060 APInt Mask
= APInt::getHighBitsSet(BitWidth
, BitWidth
- 8);
1062 } else if (VT
== MVT::v4i16
|| VT
== MVT::v8i16
) {
1063 assert(BitWidth
>= 16 && "Unexpected width!");
1064 APInt Mask
= APInt::getHighBitsSet(BitWidth
, BitWidth
- 16);
1074 MVT
AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout
&DL
,
1079 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1080 EVT VT
, unsigned AddrSpace
, unsigned Align
, MachineMemOperand::Flags Flags
,
1082 if (Subtarget
->requiresStrictAlign())
1086 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1087 *Fast
= !Subtarget
->isMisaligned128StoreSlow() || VT
.getStoreSize() != 16 ||
1088 // See comments in performSTORECombine() for more details about
1089 // these conditions.
1091 // Code that uses clang vector extensions can mark that it
1092 // wants unaligned accesses to be treated as fast by
1093 // underspecifying alignment to be 1 or 2.
1096 // Disregard v2i64. Memcpy lowering produces those and splitting
1097 // them regresses performance on micro-benchmarks and olden/bh.
1103 // Same as above but handling LLTs instead.
1104 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1105 LLT Ty
, unsigned AddrSpace
, unsigned Align
, MachineMemOperand::Flags Flags
,
1107 if (Subtarget
->requiresStrictAlign())
1111 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1112 *Fast
= !Subtarget
->isMisaligned128StoreSlow() ||
1113 Ty
.getSizeInBytes() != 16 ||
1114 // See comments in performSTORECombine() for more details about
1115 // these conditions.
1117 // Code that uses clang vector extensions can mark that it
1118 // wants unaligned accesses to be treated as fast by
1119 // underspecifying alignment to be 1 or 2.
1122 // Disregard v2i64. Memcpy lowering produces those and splitting
1123 // them regresses performance on micro-benchmarks and olden/bh.
1124 Ty
== LLT::vector(2, 64);
1130 AArch64TargetLowering::createFastISel(FunctionLoweringInfo
&funcInfo
,
1131 const TargetLibraryInfo
*libInfo
) const {
1132 return AArch64::createFastISel(funcInfo
, libInfo
);
1135 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode
) const {
1136 switch ((AArch64ISD::NodeType
)Opcode
) {
1137 case AArch64ISD::FIRST_NUMBER
: break;
1138 case AArch64ISD::CALL
: return "AArch64ISD::CALL";
1139 case AArch64ISD::ADRP
: return "AArch64ISD::ADRP";
1140 case AArch64ISD::ADR
: return "AArch64ISD::ADR";
1141 case AArch64ISD::ADDlow
: return "AArch64ISD::ADDlow";
1142 case AArch64ISD::LOADgot
: return "AArch64ISD::LOADgot";
1143 case AArch64ISD::RET_FLAG
: return "AArch64ISD::RET_FLAG";
1144 case AArch64ISD::BRCOND
: return "AArch64ISD::BRCOND";
1145 case AArch64ISD::CSEL
: return "AArch64ISD::CSEL";
1146 case AArch64ISD::FCSEL
: return "AArch64ISD::FCSEL";
1147 case AArch64ISD::CSINV
: return "AArch64ISD::CSINV";
1148 case AArch64ISD::CSNEG
: return "AArch64ISD::CSNEG";
1149 case AArch64ISD::CSINC
: return "AArch64ISD::CSINC";
1150 case AArch64ISD::THREAD_POINTER
: return "AArch64ISD::THREAD_POINTER";
1151 case AArch64ISD::TLSDESC_CALLSEQ
: return "AArch64ISD::TLSDESC_CALLSEQ";
1152 case AArch64ISD::ADC
: return "AArch64ISD::ADC";
1153 case AArch64ISD::SBC
: return "AArch64ISD::SBC";
1154 case AArch64ISD::ADDS
: return "AArch64ISD::ADDS";
1155 case AArch64ISD::SUBS
: return "AArch64ISD::SUBS";
1156 case AArch64ISD::ADCS
: return "AArch64ISD::ADCS";
1157 case AArch64ISD::SBCS
: return "AArch64ISD::SBCS";
1158 case AArch64ISD::ANDS
: return "AArch64ISD::ANDS";
1159 case AArch64ISD::CCMP
: return "AArch64ISD::CCMP";
1160 case AArch64ISD::CCMN
: return "AArch64ISD::CCMN";
1161 case AArch64ISD::FCCMP
: return "AArch64ISD::FCCMP";
1162 case AArch64ISD::FCMP
: return "AArch64ISD::FCMP";
1163 case AArch64ISD::DUP
: return "AArch64ISD::DUP";
1164 case AArch64ISD::DUPLANE8
: return "AArch64ISD::DUPLANE8";
1165 case AArch64ISD::DUPLANE16
: return "AArch64ISD::DUPLANE16";
1166 case AArch64ISD::DUPLANE32
: return "AArch64ISD::DUPLANE32";
1167 case AArch64ISD::DUPLANE64
: return "AArch64ISD::DUPLANE64";
1168 case AArch64ISD::MOVI
: return "AArch64ISD::MOVI";
1169 case AArch64ISD::MOVIshift
: return "AArch64ISD::MOVIshift";
1170 case AArch64ISD::MOVIedit
: return "AArch64ISD::MOVIedit";
1171 case AArch64ISD::MOVImsl
: return "AArch64ISD::MOVImsl";
1172 case AArch64ISD::FMOV
: return "AArch64ISD::FMOV";
1173 case AArch64ISD::MVNIshift
: return "AArch64ISD::MVNIshift";
1174 case AArch64ISD::MVNImsl
: return "AArch64ISD::MVNImsl";
1175 case AArch64ISD::BICi
: return "AArch64ISD::BICi";
1176 case AArch64ISD::ORRi
: return "AArch64ISD::ORRi";
1177 case AArch64ISD::BSL
: return "AArch64ISD::BSL";
1178 case AArch64ISD::NEG
: return "AArch64ISD::NEG";
1179 case AArch64ISD::EXTR
: return "AArch64ISD::EXTR";
1180 case AArch64ISD::ZIP1
: return "AArch64ISD::ZIP1";
1181 case AArch64ISD::ZIP2
: return "AArch64ISD::ZIP2";
1182 case AArch64ISD::UZP1
: return "AArch64ISD::UZP1";
1183 case AArch64ISD::UZP2
: return "AArch64ISD::UZP2";
1184 case AArch64ISD::TRN1
: return "AArch64ISD::TRN1";
1185 case AArch64ISD::TRN2
: return "AArch64ISD::TRN2";
1186 case AArch64ISD::REV16
: return "AArch64ISD::REV16";
1187 case AArch64ISD::REV32
: return "AArch64ISD::REV32";
1188 case AArch64ISD::REV64
: return "AArch64ISD::REV64";
1189 case AArch64ISD::EXT
: return "AArch64ISD::EXT";
1190 case AArch64ISD::VSHL
: return "AArch64ISD::VSHL";
1191 case AArch64ISD::VLSHR
: return "AArch64ISD::VLSHR";
1192 case AArch64ISD::VASHR
: return "AArch64ISD::VASHR";
1193 case AArch64ISD::CMEQ
: return "AArch64ISD::CMEQ";
1194 case AArch64ISD::CMGE
: return "AArch64ISD::CMGE";
1195 case AArch64ISD::CMGT
: return "AArch64ISD::CMGT";
1196 case AArch64ISD::CMHI
: return "AArch64ISD::CMHI";
1197 case AArch64ISD::CMHS
: return "AArch64ISD::CMHS";
1198 case AArch64ISD::FCMEQ
: return "AArch64ISD::FCMEQ";
1199 case AArch64ISD::FCMGE
: return "AArch64ISD::FCMGE";
1200 case AArch64ISD::FCMGT
: return "AArch64ISD::FCMGT";
1201 case AArch64ISD::CMEQz
: return "AArch64ISD::CMEQz";
1202 case AArch64ISD::CMGEz
: return "AArch64ISD::CMGEz";
1203 case AArch64ISD::CMGTz
: return "AArch64ISD::CMGTz";
1204 case AArch64ISD::CMLEz
: return "AArch64ISD::CMLEz";
1205 case AArch64ISD::CMLTz
: return "AArch64ISD::CMLTz";
1206 case AArch64ISD::FCMEQz
: return "AArch64ISD::FCMEQz";
1207 case AArch64ISD::FCMGEz
: return "AArch64ISD::FCMGEz";
1208 case AArch64ISD::FCMGTz
: return "AArch64ISD::FCMGTz";
1209 case AArch64ISD::FCMLEz
: return "AArch64ISD::FCMLEz";
1210 case AArch64ISD::FCMLTz
: return "AArch64ISD::FCMLTz";
1211 case AArch64ISD::SADDV
: return "AArch64ISD::SADDV";
1212 case AArch64ISD::UADDV
: return "AArch64ISD::UADDV";
1213 case AArch64ISD::SMINV
: return "AArch64ISD::SMINV";
1214 case AArch64ISD::UMINV
: return "AArch64ISD::UMINV";
1215 case AArch64ISD::SMAXV
: return "AArch64ISD::SMAXV";
1216 case AArch64ISD::UMAXV
: return "AArch64ISD::UMAXV";
1217 case AArch64ISD::NOT
: return "AArch64ISD::NOT";
1218 case AArch64ISD::BIT
: return "AArch64ISD::BIT";
1219 case AArch64ISD::CBZ
: return "AArch64ISD::CBZ";
1220 case AArch64ISD::CBNZ
: return "AArch64ISD::CBNZ";
1221 case AArch64ISD::TBZ
: return "AArch64ISD::TBZ";
1222 case AArch64ISD::TBNZ
: return "AArch64ISD::TBNZ";
1223 case AArch64ISD::TC_RETURN
: return "AArch64ISD::TC_RETURN";
1224 case AArch64ISD::PREFETCH
: return "AArch64ISD::PREFETCH";
1225 case AArch64ISD::SITOF
: return "AArch64ISD::SITOF";
1226 case AArch64ISD::UITOF
: return "AArch64ISD::UITOF";
1227 case AArch64ISD::NVCAST
: return "AArch64ISD::NVCAST";
1228 case AArch64ISD::SQSHL_I
: return "AArch64ISD::SQSHL_I";
1229 case AArch64ISD::UQSHL_I
: return "AArch64ISD::UQSHL_I";
1230 case AArch64ISD::SRSHR_I
: return "AArch64ISD::SRSHR_I";
1231 case AArch64ISD::URSHR_I
: return "AArch64ISD::URSHR_I";
1232 case AArch64ISD::SQSHLU_I
: return "AArch64ISD::SQSHLU_I";
1233 case AArch64ISD::WrapperLarge
: return "AArch64ISD::WrapperLarge";
1234 case AArch64ISD::LD2post
: return "AArch64ISD::LD2post";
1235 case AArch64ISD::LD3post
: return "AArch64ISD::LD3post";
1236 case AArch64ISD::LD4post
: return "AArch64ISD::LD4post";
1237 case AArch64ISD::ST2post
: return "AArch64ISD::ST2post";
1238 case AArch64ISD::ST3post
: return "AArch64ISD::ST3post";
1239 case AArch64ISD::ST4post
: return "AArch64ISD::ST4post";
1240 case AArch64ISD::LD1x2post
: return "AArch64ISD::LD1x2post";
1241 case AArch64ISD::LD1x3post
: return "AArch64ISD::LD1x3post";
1242 case AArch64ISD::LD1x4post
: return "AArch64ISD::LD1x4post";
1243 case AArch64ISD::ST1x2post
: return "AArch64ISD::ST1x2post";
1244 case AArch64ISD::ST1x3post
: return "AArch64ISD::ST1x3post";
1245 case AArch64ISD::ST1x4post
: return "AArch64ISD::ST1x4post";
1246 case AArch64ISD::LD1DUPpost
: return "AArch64ISD::LD1DUPpost";
1247 case AArch64ISD::LD2DUPpost
: return "AArch64ISD::LD2DUPpost";
1248 case AArch64ISD::LD3DUPpost
: return "AArch64ISD::LD3DUPpost";
1249 case AArch64ISD::LD4DUPpost
: return "AArch64ISD::LD4DUPpost";
1250 case AArch64ISD::LD1LANEpost
: return "AArch64ISD::LD1LANEpost";
1251 case AArch64ISD::LD2LANEpost
: return "AArch64ISD::LD2LANEpost";
1252 case AArch64ISD::LD3LANEpost
: return "AArch64ISD::LD3LANEpost";
1253 case AArch64ISD::LD4LANEpost
: return "AArch64ISD::LD4LANEpost";
1254 case AArch64ISD::ST2LANEpost
: return "AArch64ISD::ST2LANEpost";
1255 case AArch64ISD::ST3LANEpost
: return "AArch64ISD::ST3LANEpost";
1256 case AArch64ISD::ST4LANEpost
: return "AArch64ISD::ST4LANEpost";
1257 case AArch64ISD::SMULL
: return "AArch64ISD::SMULL";
1258 case AArch64ISD::UMULL
: return "AArch64ISD::UMULL";
1259 case AArch64ISD::FRECPE
: return "AArch64ISD::FRECPE";
1260 case AArch64ISD::FRECPS
: return "AArch64ISD::FRECPS";
1261 case AArch64ISD::FRSQRTE
: return "AArch64ISD::FRSQRTE";
1262 case AArch64ISD::FRSQRTS
: return "AArch64ISD::FRSQRTS";
1263 case AArch64ISD::STG
: return "AArch64ISD::STG";
1264 case AArch64ISD::STZG
: return "AArch64ISD::STZG";
1265 case AArch64ISD::ST2G
: return "AArch64ISD::ST2G";
1266 case AArch64ISD::STZ2G
: return "AArch64ISD::STZ2G";
1272 AArch64TargetLowering::EmitF128CSEL(MachineInstr
&MI
,
1273 MachineBasicBlock
*MBB
) const {
1274 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1278 // [... previous instrs leading to comparison ...]
1284 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1286 MachineFunction
*MF
= MBB
->getParent();
1287 const TargetInstrInfo
*TII
= Subtarget
->getInstrInfo();
1288 const BasicBlock
*LLVM_BB
= MBB
->getBasicBlock();
1289 DebugLoc DL
= MI
.getDebugLoc();
1290 MachineFunction::iterator It
= ++MBB
->getIterator();
1292 unsigned DestReg
= MI
.getOperand(0).getReg();
1293 unsigned IfTrueReg
= MI
.getOperand(1).getReg();
1294 unsigned IfFalseReg
= MI
.getOperand(2).getReg();
1295 unsigned CondCode
= MI
.getOperand(3).getImm();
1296 bool NZCVKilled
= MI
.getOperand(4).isKill();
1298 MachineBasicBlock
*TrueBB
= MF
->CreateMachineBasicBlock(LLVM_BB
);
1299 MachineBasicBlock
*EndBB
= MF
->CreateMachineBasicBlock(LLVM_BB
);
1300 MF
->insert(It
, TrueBB
);
1301 MF
->insert(It
, EndBB
);
1303 // Transfer rest of current basic-block to EndBB
1304 EndBB
->splice(EndBB
->begin(), MBB
, std::next(MachineBasicBlock::iterator(MI
)),
1306 EndBB
->transferSuccessorsAndUpdatePHIs(MBB
);
1308 BuildMI(MBB
, DL
, TII
->get(AArch64::Bcc
)).addImm(CondCode
).addMBB(TrueBB
);
1309 BuildMI(MBB
, DL
, TII
->get(AArch64::B
)).addMBB(EndBB
);
1310 MBB
->addSuccessor(TrueBB
);
1311 MBB
->addSuccessor(EndBB
);
1313 // TrueBB falls through to the end.
1314 TrueBB
->addSuccessor(EndBB
);
1317 TrueBB
->addLiveIn(AArch64::NZCV
);
1318 EndBB
->addLiveIn(AArch64::NZCV
);
1321 BuildMI(*EndBB
, EndBB
->begin(), DL
, TII
->get(AArch64::PHI
), DestReg
)
1327 MI
.eraseFromParent();
1331 MachineBasicBlock
*AArch64TargetLowering::EmitLoweredCatchRet(
1332 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1333 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1334 BB
->getParent()->getFunction().getPersonalityFn())) &&
1335 "SEH does not use catchret!");
1339 MachineBasicBlock
*AArch64TargetLowering::EmitLoweredCatchPad(
1340 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1341 MI
.eraseFromParent();
1345 MachineBasicBlock
*AArch64TargetLowering::EmitInstrWithCustomInserter(
1346 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1347 switch (MI
.getOpcode()) {
1352 llvm_unreachable("Unexpected instruction for custom inserter!");
1354 case AArch64::F128CSEL
:
1355 return EmitF128CSEL(MI
, BB
);
1357 case TargetOpcode::STACKMAP
:
1358 case TargetOpcode::PATCHPOINT
:
1359 return emitPatchPoint(MI
, BB
);
1361 case AArch64::CATCHRET
:
1362 return EmitLoweredCatchRet(MI
, BB
);
1363 case AArch64::CATCHPAD
:
1364 return EmitLoweredCatchPad(MI
, BB
);
1368 //===----------------------------------------------------------------------===//
1369 // AArch64 Lowering private implementation.
1370 //===----------------------------------------------------------------------===//
1372 //===----------------------------------------------------------------------===//
1374 //===----------------------------------------------------------------------===//
1376 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1378 static AArch64CC::CondCode
changeIntCCToAArch64CC(ISD::CondCode CC
) {
1381 llvm_unreachable("Unknown condition code!");
1383 return AArch64CC::NE
;
1385 return AArch64CC::EQ
;
1387 return AArch64CC::GT
;
1389 return AArch64CC::GE
;
1391 return AArch64CC::LT
;
1393 return AArch64CC::LE
;
1395 return AArch64CC::HI
;
1397 return AArch64CC::HS
;
1399 return AArch64CC::LO
;
1401 return AArch64CC::LS
;
1405 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1406 static void changeFPCCToAArch64CC(ISD::CondCode CC
,
1407 AArch64CC::CondCode
&CondCode
,
1408 AArch64CC::CondCode
&CondCode2
) {
1409 CondCode2
= AArch64CC::AL
;
1412 llvm_unreachable("Unknown FP condition!");
1415 CondCode
= AArch64CC::EQ
;
1419 CondCode
= AArch64CC::GT
;
1423 CondCode
= AArch64CC::GE
;
1426 CondCode
= AArch64CC::MI
;
1429 CondCode
= AArch64CC::LS
;
1432 CondCode
= AArch64CC::MI
;
1433 CondCode2
= AArch64CC::GT
;
1436 CondCode
= AArch64CC::VC
;
1439 CondCode
= AArch64CC::VS
;
1442 CondCode
= AArch64CC::EQ
;
1443 CondCode2
= AArch64CC::VS
;
1446 CondCode
= AArch64CC::HI
;
1449 CondCode
= AArch64CC::PL
;
1453 CondCode
= AArch64CC::LT
;
1457 CondCode
= AArch64CC::LE
;
1461 CondCode
= AArch64CC::NE
;
1466 /// Convert a DAG fp condition code to an AArch64 CC.
1467 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1468 /// should be AND'ed instead of OR'ed.
1469 static void changeFPCCToANDAArch64CC(ISD::CondCode CC
,
1470 AArch64CC::CondCode
&CondCode
,
1471 AArch64CC::CondCode
&CondCode2
) {
1472 CondCode2
= AArch64CC::AL
;
1475 changeFPCCToAArch64CC(CC
, CondCode
, CondCode2
);
1476 assert(CondCode2
== AArch64CC::AL
);
1480 // == ((a olt b) || (a ogt b))
1481 // == ((a ord b) && (a une b))
1482 CondCode
= AArch64CC::VC
;
1483 CondCode2
= AArch64CC::NE
;
1487 // == ((a uno b) || (a oeq b))
1488 // == ((a ule b) && (a uge b))
1489 CondCode
= AArch64CC::PL
;
1490 CondCode2
= AArch64CC::LE
;
1495 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1496 /// CC usable with the vector instructions. Fewer operations are available
1497 /// without a real NZCV register, so we have to use less efficient combinations
1498 /// to get the same effect.
1499 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC
,
1500 AArch64CC::CondCode
&CondCode
,
1501 AArch64CC::CondCode
&CondCode2
,
1506 // Mostly the scalar mappings work fine.
1507 changeFPCCToAArch64CC(CC
, CondCode
, CondCode2
);
1513 CondCode
= AArch64CC::MI
;
1514 CondCode2
= AArch64CC::GE
;
1521 // All of the compare-mask comparisons are ordered, but we can switch
1522 // between the two by a double inversion. E.g. ULE == !OGT.
1524 changeFPCCToAArch64CC(getSetCCInverse(CC
, false), CondCode
, CondCode2
);
1529 static bool isLegalArithImmed(uint64_t C
) {
1530 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1531 bool IsLegal
= (C
>> 12 == 0) || ((C
& 0xFFFULL
) == 0 && C
>> 24 == 0);
1532 LLVM_DEBUG(dbgs() << "Is imm " << C
1533 << " legal: " << (IsLegal
? "yes\n" : "no\n"));
1537 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1538 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1539 // can be set differently by this operation. It comes down to whether
1540 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1541 // everything is fine. If not then the optimization is wrong. Thus general
1542 // comparisons are only valid if op2 != 0.
1544 // So, finally, the only LLVM-native comparisons that don't mention C and V
1545 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1546 // the absence of information about op2.
1547 static bool isCMN(SDValue Op
, ISD::CondCode CC
) {
1548 return Op
.getOpcode() == ISD::SUB
&& isNullConstant(Op
.getOperand(0)) &&
1549 (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
);
1552 static SDValue
emitComparison(SDValue LHS
, SDValue RHS
, ISD::CondCode CC
,
1553 const SDLoc
&dl
, SelectionDAG
&DAG
) {
1554 EVT VT
= LHS
.getValueType();
1555 const bool FullFP16
=
1556 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
1558 if (VT
.isFloatingPoint()) {
1559 assert(VT
!= MVT::f128
);
1560 if (VT
== MVT::f16
&& !FullFP16
) {
1561 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, LHS
);
1562 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, RHS
);
1565 return DAG
.getNode(AArch64ISD::FCMP
, dl
, VT
, LHS
, RHS
);
1568 // The CMP instruction is just an alias for SUBS, and representing it as
1569 // SUBS means that it's possible to get CSE with subtract operations.
1570 // A later phase can perform the optimization of setting the destination
1571 // register to WZR/XZR if it ends up being unused.
1572 unsigned Opcode
= AArch64ISD::SUBS
;
1574 if (isCMN(RHS
, CC
)) {
1575 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1576 Opcode
= AArch64ISD::ADDS
;
1577 RHS
= RHS
.getOperand(1);
1578 } else if (isCMN(LHS
, CC
)) {
1579 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1580 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1581 Opcode
= AArch64ISD::ADDS
;
1582 LHS
= LHS
.getOperand(1);
1583 } else if (LHS
.getOpcode() == ISD::AND
&& isNullConstant(RHS
) &&
1584 !isUnsignedIntSetCC(CC
)) {
1585 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1586 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1587 // of the signed comparisons.
1588 Opcode
= AArch64ISD::ANDS
;
1589 RHS
= LHS
.getOperand(1);
1590 LHS
= LHS
.getOperand(0);
1593 return DAG
.getNode(Opcode
, dl
, DAG
.getVTList(VT
, MVT_CC
), LHS
, RHS
)
1597 /// \defgroup AArch64CCMP CMP;CCMP matching
1599 /// These functions deal with the formation of CMP;CCMP;... sequences.
1600 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1601 /// a comparison. They set the NZCV flags to a predefined value if their
1602 /// predicate is false. This allows to express arbitrary conjunctions, for
1603 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1606 /// ccmp B, inv(CB), CA
1607 /// check for CB flags
1609 /// This naturally lets us implement chains of AND operations with SETCC
1610 /// operands. And we can even implement some other situations by transforming
1612 /// - We can implement (NEG SETCC) i.e. negating a single comparison by
1613 /// negating the flags used in a CCMP/FCCMP operations.
1614 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1615 /// by negating the flags we test for afterwards. i.e.
1616 /// NEG (CMP CCMP CCCMP ...) can be implemented.
1617 /// - Note that we can only ever negate all previously processed results.
1618 /// What we can not implement by flipping the flags to test is a negation
1619 /// of two sub-trees (because the negation affects all sub-trees emitted so
1620 /// far, so the 2nd sub-tree we emit would also affect the first).
1621 /// With those tools we can implement some OR operations:
1622 /// - (OR (SETCC A) (SETCC B)) can be implemented via:
1623 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1624 /// - After transforming OR to NEG/AND combinations we may be able to use NEG
1625 /// elimination rules from earlier to implement the whole thing as a
1626 /// CCMP/FCCMP chain.
1628 /// As complete example:
1629 /// or (or (setCA (cmp A)) (setCB (cmp B)))
1630 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1631 /// can be reassociated to:
1632 /// or (and (setCC (cmp C)) setCD (cmp D))
1633 // (or (setCA (cmp A)) (setCB (cmp B)))
1634 /// can be transformed to:
1635 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1636 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1637 /// which can be implemented as:
1639 /// ccmp D, inv(CD), CC
1640 /// ccmp A, CA, inv(CD)
1641 /// ccmp B, CB, inv(CA)
1642 /// check for CB flags
1644 /// A counterexample is "or (and A B) (and C D)" which translates to
1645 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1646 /// can only implement 1 of the inner (not) operations, but not both!
1649 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1650 static SDValue
emitConditionalComparison(SDValue LHS
, SDValue RHS
,
1651 ISD::CondCode CC
, SDValue CCOp
,
1652 AArch64CC::CondCode Predicate
,
1653 AArch64CC::CondCode OutCC
,
1654 const SDLoc
&DL
, SelectionDAG
&DAG
) {
1655 unsigned Opcode
= 0;
1656 const bool FullFP16
=
1657 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
1659 if (LHS
.getValueType().isFloatingPoint()) {
1660 assert(LHS
.getValueType() != MVT::f128
);
1661 if (LHS
.getValueType() == MVT::f16
&& !FullFP16
) {
1662 LHS
= DAG
.getNode(ISD::FP_EXTEND
, DL
, MVT::f32
, LHS
);
1663 RHS
= DAG
.getNode(ISD::FP_EXTEND
, DL
, MVT::f32
, RHS
);
1665 Opcode
= AArch64ISD::FCCMP
;
1666 } else if (RHS
.getOpcode() == ISD::SUB
) {
1667 SDValue SubOp0
= RHS
.getOperand(0);
1668 if (isNullConstant(SubOp0
) && (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
1669 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1670 Opcode
= AArch64ISD::CCMN
;
1671 RHS
= RHS
.getOperand(1);
1675 Opcode
= AArch64ISD::CCMP
;
1677 SDValue Condition
= DAG
.getConstant(Predicate
, DL
, MVT_CC
);
1678 AArch64CC::CondCode InvOutCC
= AArch64CC::getInvertedCondCode(OutCC
);
1679 unsigned NZCV
= AArch64CC::getNZCVToSatisfyCondCode(InvOutCC
);
1680 SDValue NZCVOp
= DAG
.getConstant(NZCV
, DL
, MVT::i32
);
1681 return DAG
.getNode(Opcode
, DL
, MVT_CC
, LHS
, RHS
, NZCVOp
, Condition
, CCOp
);
1684 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1685 /// expressed as a conjunction. See \ref AArch64CCMP.
1686 /// \param CanNegate Set to true if we can negate the whole sub-tree just by
1687 /// changing the conditions on the SETCC tests.
1688 /// (this means we can call emitConjunctionRec() with
1689 /// Negate==true on this sub-tree)
1690 /// \param MustBeFirst Set to true if this subtree needs to be negated and we
1691 /// cannot do the negation naturally. We are required to
1692 /// emit the subtree first in this case.
1693 /// \param WillNegate Is true if are called when the result of this
1694 /// subexpression must be negated. This happens when the
1695 /// outer expression is an OR. We can use this fact to know
1696 /// that we have a double negation (or (or ...) ...) that
1697 /// can be implemented for free.
1698 static bool canEmitConjunction(const SDValue Val
, bool &CanNegate
,
1699 bool &MustBeFirst
, bool WillNegate
,
1700 unsigned Depth
= 0) {
1701 if (!Val
.hasOneUse())
1703 unsigned Opcode
= Val
->getOpcode();
1704 if (Opcode
== ISD::SETCC
) {
1705 if (Val
->getOperand(0).getValueType() == MVT::f128
)
1708 MustBeFirst
= false;
1711 // Protect against exponential runtime and stack overflow.
1714 if (Opcode
== ISD::AND
|| Opcode
== ISD::OR
) {
1715 bool IsOR
= Opcode
== ISD::OR
;
1716 SDValue O0
= Val
->getOperand(0);
1717 SDValue O1
= Val
->getOperand(1);
1720 if (!canEmitConjunction(O0
, CanNegateL
, MustBeFirstL
, IsOR
, Depth
+1))
1724 if (!canEmitConjunction(O1
, CanNegateR
, MustBeFirstR
, IsOR
, Depth
+1))
1727 if (MustBeFirstL
&& MustBeFirstR
)
1731 // For an OR expression we need to be able to naturally negate at least
1732 // one side or we cannot do the transformation at all.
1733 if (!CanNegateL
&& !CanNegateR
)
1735 // If we the result of the OR will be negated and we can naturally negate
1736 // the leafs, then this sub-tree as a whole negates naturally.
1737 CanNegate
= WillNegate
&& CanNegateL
&& CanNegateR
;
1738 // If we cannot naturally negate the whole sub-tree, then this must be
1740 MustBeFirst
= !CanNegate
;
1742 assert(Opcode
== ISD::AND
&& "Must be OR or AND");
1743 // We cannot naturally negate an AND operation.
1745 MustBeFirst
= MustBeFirstL
|| MustBeFirstR
;
1752 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1753 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1754 /// Tries to transform the given i1 producing node @p Val to a series compare
1755 /// and conditional compare operations. @returns an NZCV flags producing node
1756 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1757 /// transformation was not possible.
1758 /// \p Negate is true if we want this sub-tree being negated just by changing
1759 /// SETCC conditions.
1760 static SDValue
emitConjunctionRec(SelectionDAG
&DAG
, SDValue Val
,
1761 AArch64CC::CondCode
&OutCC
, bool Negate
, SDValue CCOp
,
1762 AArch64CC::CondCode Predicate
) {
1763 // We're at a tree leaf, produce a conditional comparison operation.
1764 unsigned Opcode
= Val
->getOpcode();
1765 if (Opcode
== ISD::SETCC
) {
1766 SDValue LHS
= Val
->getOperand(0);
1767 SDValue RHS
= Val
->getOperand(1);
1768 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Val
->getOperand(2))->get();
1769 bool isInteger
= LHS
.getValueType().isInteger();
1771 CC
= getSetCCInverse(CC
, isInteger
);
1773 // Determine OutCC and handle FP special case.
1775 OutCC
= changeIntCCToAArch64CC(CC
);
1777 assert(LHS
.getValueType().isFloatingPoint());
1778 AArch64CC::CondCode ExtraCC
;
1779 changeFPCCToANDAArch64CC(CC
, OutCC
, ExtraCC
);
1780 // Some floating point conditions can't be tested with a single condition
1781 // code. Construct an additional comparison in this case.
1782 if (ExtraCC
!= AArch64CC::AL
) {
1784 if (!CCOp
.getNode())
1785 ExtraCmp
= emitComparison(LHS
, RHS
, CC
, DL
, DAG
);
1787 ExtraCmp
= emitConditionalComparison(LHS
, RHS
, CC
, CCOp
, Predicate
,
1790 Predicate
= ExtraCC
;
1794 // Produce a normal comparison if we are first in the chain
1796 return emitComparison(LHS
, RHS
, CC
, DL
, DAG
);
1797 // Otherwise produce a ccmp.
1798 return emitConditionalComparison(LHS
, RHS
, CC
, CCOp
, Predicate
, OutCC
, DL
,
1801 assert(Val
->hasOneUse() && "Valid conjunction/disjunction tree");
1803 bool IsOR
= Opcode
== ISD::OR
;
1805 SDValue LHS
= Val
->getOperand(0);
1808 bool ValidL
= canEmitConjunction(LHS
, CanNegateL
, MustBeFirstL
, IsOR
);
1809 assert(ValidL
&& "Valid conjunction/disjunction tree");
1812 SDValue RHS
= Val
->getOperand(1);
1815 bool ValidR
= canEmitConjunction(RHS
, CanNegateR
, MustBeFirstR
, IsOR
);
1816 assert(ValidR
&& "Valid conjunction/disjunction tree");
1819 // Swap sub-tree that must come first to the right side.
1821 assert(!MustBeFirstR
&& "Valid conjunction/disjunction tree");
1822 std::swap(LHS
, RHS
);
1823 std::swap(CanNegateL
, CanNegateR
);
1824 std::swap(MustBeFirstL
, MustBeFirstR
);
1830 bool NegateAfterAll
;
1831 if (Opcode
== ISD::OR
) {
1832 // Swap the sub-tree that we can negate naturally to the left.
1834 assert(CanNegateR
&& "at least one side must be negatable");
1835 assert(!MustBeFirstR
&& "invalid conjunction/disjunction tree");
1837 std::swap(LHS
, RHS
);
1839 NegateAfterR
= true;
1841 // Negate the left sub-tree if possible, otherwise negate the result.
1842 NegateR
= CanNegateR
;
1843 NegateAfterR
= !CanNegateR
;
1846 NegateAfterAll
= !Negate
;
1848 assert(Opcode
== ISD::AND
&& "Valid conjunction/disjunction tree");
1849 assert(!Negate
&& "Valid conjunction/disjunction tree");
1853 NegateAfterR
= false;
1854 NegateAfterAll
= false;
1858 AArch64CC::CondCode RHSCC
;
1859 SDValue CmpR
= emitConjunctionRec(DAG
, RHS
, RHSCC
, NegateR
, CCOp
, Predicate
);
1861 RHSCC
= AArch64CC::getInvertedCondCode(RHSCC
);
1862 SDValue CmpL
= emitConjunctionRec(DAG
, LHS
, OutCC
, NegateL
, CmpR
, RHSCC
);
1864 OutCC
= AArch64CC::getInvertedCondCode(OutCC
);
1868 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1869 /// In some cases this is even possible with OR operations in the expression.
1870 /// See \ref AArch64CCMP.
1871 /// \see emitConjunctionRec().
1872 static SDValue
emitConjunction(SelectionDAG
&DAG
, SDValue Val
,
1873 AArch64CC::CondCode
&OutCC
) {
1874 bool DummyCanNegate
;
1875 bool DummyMustBeFirst
;
1876 if (!canEmitConjunction(Val
, DummyCanNegate
, DummyMustBeFirst
, false))
1879 return emitConjunctionRec(DAG
, Val
, OutCC
, false, SDValue(), AArch64CC::AL
);
1884 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1885 /// extension operations.
1886 static unsigned getCmpOperandFoldingProfit(SDValue Op
) {
1887 auto isSupportedExtend
= [&](SDValue V
) {
1888 if (V
.getOpcode() == ISD::SIGN_EXTEND_INREG
)
1891 if (V
.getOpcode() == ISD::AND
)
1892 if (ConstantSDNode
*MaskCst
= dyn_cast
<ConstantSDNode
>(V
.getOperand(1))) {
1893 uint64_t Mask
= MaskCst
->getZExtValue();
1894 return (Mask
== 0xFF || Mask
== 0xFFFF || Mask
== 0xFFFFFFFF);
1900 if (!Op
.hasOneUse())
1903 if (isSupportedExtend(Op
))
1906 unsigned Opc
= Op
.getOpcode();
1907 if (Opc
== ISD::SHL
|| Opc
== ISD::SRL
|| Opc
== ISD::SRA
)
1908 if (ConstantSDNode
*ShiftCst
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))) {
1909 uint64_t Shift
= ShiftCst
->getZExtValue();
1910 if (isSupportedExtend(Op
.getOperand(0)))
1911 return (Shift
<= 4) ? 2 : 1;
1912 EVT VT
= Op
.getValueType();
1913 if ((VT
== MVT::i32
&& Shift
<= 31) || (VT
== MVT::i64
&& Shift
<= 63))
1920 static SDValue
getAArch64Cmp(SDValue LHS
, SDValue RHS
, ISD::CondCode CC
,
1921 SDValue
&AArch64cc
, SelectionDAG
&DAG
,
1923 if (ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(RHS
.getNode())) {
1924 EVT VT
= RHS
.getValueType();
1925 uint64_t C
= RHSC
->getZExtValue();
1926 if (!isLegalArithImmed(C
)) {
1927 // Constant does not fit, try adjusting it by one?
1933 if ((VT
== MVT::i32
&& C
!= 0x80000000 &&
1934 isLegalArithImmed((uint32_t)(C
- 1))) ||
1935 (VT
== MVT::i64
&& C
!= 0x80000000ULL
&&
1936 isLegalArithImmed(C
- 1ULL))) {
1937 CC
= (CC
== ISD::SETLT
) ? ISD::SETLE
: ISD::SETGT
;
1938 C
= (VT
== MVT::i32
) ? (uint32_t)(C
- 1) : C
- 1;
1939 RHS
= DAG
.getConstant(C
, dl
, VT
);
1944 if ((VT
== MVT::i32
&& C
!= 0 &&
1945 isLegalArithImmed((uint32_t)(C
- 1))) ||
1946 (VT
== MVT::i64
&& C
!= 0ULL && isLegalArithImmed(C
- 1ULL))) {
1947 CC
= (CC
== ISD::SETULT
) ? ISD::SETULE
: ISD::SETUGT
;
1948 C
= (VT
== MVT::i32
) ? (uint32_t)(C
- 1) : C
- 1;
1949 RHS
= DAG
.getConstant(C
, dl
, VT
);
1954 if ((VT
== MVT::i32
&& C
!= INT32_MAX
&&
1955 isLegalArithImmed((uint32_t)(C
+ 1))) ||
1956 (VT
== MVT::i64
&& C
!= INT64_MAX
&&
1957 isLegalArithImmed(C
+ 1ULL))) {
1958 CC
= (CC
== ISD::SETLE
) ? ISD::SETLT
: ISD::SETGE
;
1959 C
= (VT
== MVT::i32
) ? (uint32_t)(C
+ 1) : C
+ 1;
1960 RHS
= DAG
.getConstant(C
, dl
, VT
);
1965 if ((VT
== MVT::i32
&& C
!= UINT32_MAX
&&
1966 isLegalArithImmed((uint32_t)(C
+ 1))) ||
1967 (VT
== MVT::i64
&& C
!= UINT64_MAX
&&
1968 isLegalArithImmed(C
+ 1ULL))) {
1969 CC
= (CC
== ISD::SETULE
) ? ISD::SETULT
: ISD::SETUGE
;
1970 C
= (VT
== MVT::i32
) ? (uint32_t)(C
+ 1) : C
+ 1;
1971 RHS
= DAG
.getConstant(C
, dl
, VT
);
1978 // Comparisons are canonicalized so that the RHS operand is simpler than the
1979 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1980 // can fold some shift+extend operations on the RHS operand, so swap the
1981 // operands if that can be done.
1986 // can be turned into:
1987 // cmp w12, w11, lsl #1
1988 if (!isa
<ConstantSDNode
>(RHS
) ||
1989 !isLegalArithImmed(cast
<ConstantSDNode
>(RHS
)->getZExtValue())) {
1990 SDValue TheLHS
= isCMN(LHS
, CC
) ? LHS
.getOperand(1) : LHS
;
1992 if (getCmpOperandFoldingProfit(TheLHS
) > getCmpOperandFoldingProfit(RHS
)) {
1993 std::swap(LHS
, RHS
);
1994 CC
= ISD::getSetCCSwappedOperands(CC
);
1999 AArch64CC::CondCode AArch64CC
;
2000 if ((CC
== ISD::SETEQ
|| CC
== ISD::SETNE
) && isa
<ConstantSDNode
>(RHS
)) {
2001 const ConstantSDNode
*RHSC
= cast
<ConstantSDNode
>(RHS
);
2003 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2004 // For the i8 operand, the largest immediate is 255, so this can be easily
2005 // encoded in the compare instruction. For the i16 operand, however, the
2006 // largest immediate cannot be encoded in the compare.
2007 // Therefore, use a sign extending load and cmn to avoid materializing the
2008 // -1 constant. For example,
2010 // ldrh w0, [x0, #0]
2013 // ldrsh w0, [x0, #0]
2015 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2016 // if and only if (sext LHS) == (sext RHS). The checks are in place to
2017 // ensure both the LHS and RHS are truly zero extended and to make sure the
2018 // transformation is profitable.
2019 if ((RHSC
->getZExtValue() >> 16 == 0) && isa
<LoadSDNode
>(LHS
) &&
2020 cast
<LoadSDNode
>(LHS
)->getExtensionType() == ISD::ZEXTLOAD
&&
2021 cast
<LoadSDNode
>(LHS
)->getMemoryVT() == MVT::i16
&&
2022 LHS
.getNode()->hasNUsesOfValue(1, 0)) {
2023 int16_t ValueofRHS
= cast
<ConstantSDNode
>(RHS
)->getZExtValue();
2024 if (ValueofRHS
< 0 && isLegalArithImmed(-ValueofRHS
)) {
2026 DAG
.getNode(ISD::SIGN_EXTEND_INREG
, dl
, LHS
.getValueType(), LHS
,
2027 DAG
.getValueType(MVT::i16
));
2028 Cmp
= emitComparison(SExt
, DAG
.getConstant(ValueofRHS
, dl
,
2029 RHS
.getValueType()),
2031 AArch64CC
= changeIntCCToAArch64CC(CC
);
2035 if (!Cmp
&& (RHSC
->isNullValue() || RHSC
->isOne())) {
2036 if ((Cmp
= emitConjunction(DAG
, LHS
, AArch64CC
))) {
2037 if ((CC
== ISD::SETNE
) ^ RHSC
->isNullValue())
2038 AArch64CC
= AArch64CC::getInvertedCondCode(AArch64CC
);
2044 Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
2045 AArch64CC
= changeIntCCToAArch64CC(CC
);
2047 AArch64cc
= DAG
.getConstant(AArch64CC
, dl
, MVT_CC
);
2051 static std::pair
<SDValue
, SDValue
>
2052 getAArch64XALUOOp(AArch64CC::CondCode
&CC
, SDValue Op
, SelectionDAG
&DAG
) {
2053 assert((Op
.getValueType() == MVT::i32
|| Op
.getValueType() == MVT::i64
) &&
2054 "Unsupported value type");
2055 SDValue Value
, Overflow
;
2057 SDValue LHS
= Op
.getOperand(0);
2058 SDValue RHS
= Op
.getOperand(1);
2060 switch (Op
.getOpcode()) {
2062 llvm_unreachable("Unknown overflow instruction!");
2064 Opc
= AArch64ISD::ADDS
;
2068 Opc
= AArch64ISD::ADDS
;
2072 Opc
= AArch64ISD::SUBS
;
2076 Opc
= AArch64ISD::SUBS
;
2079 // Multiply needs a little bit extra work.
2083 bool IsSigned
= Op
.getOpcode() == ISD::SMULO
;
2084 if (Op
.getValueType() == MVT::i32
) {
2085 unsigned ExtendOpc
= IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
2086 // For a 32 bit multiply with overflow check we want the instruction
2087 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2088 // need to generate the following pattern:
2089 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2090 LHS
= DAG
.getNode(ExtendOpc
, DL
, MVT::i64
, LHS
);
2091 RHS
= DAG
.getNode(ExtendOpc
, DL
, MVT::i64
, RHS
);
2092 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, MVT::i64
, LHS
, RHS
);
2093 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, Mul
,
2094 DAG
.getConstant(0, DL
, MVT::i64
));
2095 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2096 // operation. We need to clear out the upper 32 bits, because we used a
2097 // widening multiply that wrote all 64 bits. In the end this should be a
2099 Value
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i32
, Add
);
2101 // The signed overflow check requires more than just a simple check for
2102 // any bit set in the upper 32 bits of the result. These bits could be
2103 // just the sign bits of a negative number. To perform the overflow
2104 // check we have to arithmetic shift right the 32nd bit of the result by
2105 // 31 bits. Then we compare the result to the upper 32 bits.
2106 SDValue UpperBits
= DAG
.getNode(ISD::SRL
, DL
, MVT::i64
, Add
,
2107 DAG
.getConstant(32, DL
, MVT::i64
));
2108 UpperBits
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i32
, UpperBits
);
2109 SDValue LowerBits
= DAG
.getNode(ISD::SRA
, DL
, MVT::i32
, Value
,
2110 DAG
.getConstant(31, DL
, MVT::i64
));
2111 // It is important that LowerBits is last, otherwise the arithmetic
2112 // shift will not be folded into the compare (SUBS).
2113 SDVTList VTs
= DAG
.getVTList(MVT::i32
, MVT::i32
);
2114 Overflow
= DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
, UpperBits
, LowerBits
)
2117 // The overflow check for unsigned multiply is easy. We only need to
2118 // check if any of the upper 32 bits are set. This can be done with a
2119 // CMP (shifted register). For that we need to generate the following
2121 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2122 SDValue UpperBits
= DAG
.getNode(ISD::SRL
, DL
, MVT::i64
, Mul
,
2123 DAG
.getConstant(32, DL
, MVT::i64
));
2124 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2126 DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
,
2127 DAG
.getConstant(0, DL
, MVT::i64
),
2128 UpperBits
).getValue(1);
2132 assert(Op
.getValueType() == MVT::i64
&& "Expected an i64 value type");
2133 // For the 64 bit multiply
2134 Value
= DAG
.getNode(ISD::MUL
, DL
, MVT::i64
, LHS
, RHS
);
2136 SDValue UpperBits
= DAG
.getNode(ISD::MULHS
, DL
, MVT::i64
, LHS
, RHS
);
2137 SDValue LowerBits
= DAG
.getNode(ISD::SRA
, DL
, MVT::i64
, Value
,
2138 DAG
.getConstant(63, DL
, MVT::i64
));
2139 // It is important that LowerBits is last, otherwise the arithmetic
2140 // shift will not be folded into the compare (SUBS).
2141 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2142 Overflow
= DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
, UpperBits
, LowerBits
)
2145 SDValue UpperBits
= DAG
.getNode(ISD::MULHU
, DL
, MVT::i64
, LHS
, RHS
);
2146 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2148 DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
,
2149 DAG
.getConstant(0, DL
, MVT::i64
),
2150 UpperBits
).getValue(1);
2157 SDVTList VTs
= DAG
.getVTList(Op
->getValueType(0), MVT::i32
);
2159 // Emit the AArch64 operation with overflow check.
2160 Value
= DAG
.getNode(Opc
, DL
, VTs
, LHS
, RHS
);
2161 Overflow
= Value
.getValue(1);
2163 return std::make_pair(Value
, Overflow
);
2166 SDValue
AArch64TargetLowering::LowerF128Call(SDValue Op
, SelectionDAG
&DAG
,
2167 RTLIB::Libcall Call
) const {
2168 SmallVector
<SDValue
, 2> Ops(Op
->op_begin(), Op
->op_end());
2169 return makeLibCall(DAG
, Call
, MVT::f128
, Ops
, false, SDLoc(Op
)).first
;
2172 // Returns true if the given Op is the overflow flag result of an overflow
2173 // intrinsic operation.
2174 static bool isOverflowIntrOpRes(SDValue Op
) {
2175 unsigned Opc
= Op
.getOpcode();
2176 return (Op
.getResNo() == 1 &&
2177 (Opc
== ISD::SADDO
|| Opc
== ISD::UADDO
|| Opc
== ISD::SSUBO
||
2178 Opc
== ISD::USUBO
|| Opc
== ISD::SMULO
|| Opc
== ISD::UMULO
));
2181 static SDValue
LowerXOR(SDValue Op
, SelectionDAG
&DAG
) {
2182 SDValue Sel
= Op
.getOperand(0);
2183 SDValue Other
= Op
.getOperand(1);
2186 // If the operand is an overflow checking operation, invert the condition
2187 // code and kill the Not operation. I.e., transform:
2188 // (xor (overflow_op_bool, 1))
2190 // (csel 1, 0, invert(cc), overflow_op_bool)
2191 // ... which later gets transformed to just a cset instruction with an
2192 // inverted condition code, rather than a cset + eor sequence.
2193 if (isOneConstant(Other
) && isOverflowIntrOpRes(Sel
)) {
2194 // Only lower legal XALUO ops.
2195 if (!DAG
.getTargetLoweringInfo().isTypeLegal(Sel
->getValueType(0)))
2198 SDValue TVal
= DAG
.getConstant(1, dl
, MVT::i32
);
2199 SDValue FVal
= DAG
.getConstant(0, dl
, MVT::i32
);
2200 AArch64CC::CondCode CC
;
2201 SDValue Value
, Overflow
;
2202 std::tie(Value
, Overflow
) = getAArch64XALUOOp(CC
, Sel
.getValue(0), DAG
);
2203 SDValue CCVal
= DAG
.getConstant(getInvertedCondCode(CC
), dl
, MVT::i32
);
2204 return DAG
.getNode(AArch64ISD::CSEL
, dl
, Op
.getValueType(), TVal
, FVal
,
2207 // If neither operand is a SELECT_CC, give up.
2208 if (Sel
.getOpcode() != ISD::SELECT_CC
)
2209 std::swap(Sel
, Other
);
2210 if (Sel
.getOpcode() != ISD::SELECT_CC
)
2213 // The folding we want to perform is:
2214 // (xor x, (select_cc a, b, cc, 0, -1) )
2216 // (csel x, (xor x, -1), cc ...)
2218 // The latter will get matched to a CSINV instruction.
2220 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Sel
.getOperand(4))->get();
2221 SDValue LHS
= Sel
.getOperand(0);
2222 SDValue RHS
= Sel
.getOperand(1);
2223 SDValue TVal
= Sel
.getOperand(2);
2224 SDValue FVal
= Sel
.getOperand(3);
2226 // FIXME: This could be generalized to non-integer comparisons.
2227 if (LHS
.getValueType() != MVT::i32
&& LHS
.getValueType() != MVT::i64
)
2230 ConstantSDNode
*CFVal
= dyn_cast
<ConstantSDNode
>(FVal
);
2231 ConstantSDNode
*CTVal
= dyn_cast
<ConstantSDNode
>(TVal
);
2233 // The values aren't constants, this isn't the pattern we're looking for.
2234 if (!CFVal
|| !CTVal
)
2237 // We can commute the SELECT_CC by inverting the condition. This
2238 // might be needed to make this fit into a CSINV pattern.
2239 if (CTVal
->isAllOnesValue() && CFVal
->isNullValue()) {
2240 std::swap(TVal
, FVal
);
2241 std::swap(CTVal
, CFVal
);
2242 CC
= ISD::getSetCCInverse(CC
, true);
2245 // If the constants line up, perform the transform!
2246 if (CTVal
->isNullValue() && CFVal
->isAllOnesValue()) {
2248 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
2251 TVal
= DAG
.getNode(ISD::XOR
, dl
, Other
.getValueType(), Other
,
2252 DAG
.getConstant(-1ULL, dl
, Other
.getValueType()));
2254 return DAG
.getNode(AArch64ISD::CSEL
, dl
, Sel
.getValueType(), FVal
, TVal
,
2261 static SDValue
LowerADDC_ADDE_SUBC_SUBE(SDValue Op
, SelectionDAG
&DAG
) {
2262 EVT VT
= Op
.getValueType();
2264 // Let legalize expand this if it isn't a legal type yet.
2265 if (!DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
2268 SDVTList VTs
= DAG
.getVTList(VT
, MVT::i32
);
2271 bool ExtraOp
= false;
2272 switch (Op
.getOpcode()) {
2274 llvm_unreachable("Invalid code");
2276 Opc
= AArch64ISD::ADDS
;
2279 Opc
= AArch64ISD::SUBS
;
2282 Opc
= AArch64ISD::ADCS
;
2286 Opc
= AArch64ISD::SBCS
;
2292 return DAG
.getNode(Opc
, SDLoc(Op
), VTs
, Op
.getOperand(0), Op
.getOperand(1));
2293 return DAG
.getNode(Opc
, SDLoc(Op
), VTs
, Op
.getOperand(0), Op
.getOperand(1),
2297 static SDValue
LowerXALUO(SDValue Op
, SelectionDAG
&DAG
) {
2298 // Let legalize expand this if it isn't a legal type yet.
2299 if (!DAG
.getTargetLoweringInfo().isTypeLegal(Op
.getValueType()))
2303 AArch64CC::CondCode CC
;
2304 // The actual operation that sets the overflow or carry flag.
2305 SDValue Value
, Overflow
;
2306 std::tie(Value
, Overflow
) = getAArch64XALUOOp(CC
, Op
, DAG
);
2308 // We use 0 and 1 as false and true values.
2309 SDValue TVal
= DAG
.getConstant(1, dl
, MVT::i32
);
2310 SDValue FVal
= DAG
.getConstant(0, dl
, MVT::i32
);
2312 // We use an inverted condition, because the conditional select is inverted
2313 // too. This will allow it to be selected to a single instruction:
2314 // CSINC Wd, WZR, WZR, invert(cond).
2315 SDValue CCVal
= DAG
.getConstant(getInvertedCondCode(CC
), dl
, MVT::i32
);
2316 Overflow
= DAG
.getNode(AArch64ISD::CSEL
, dl
, MVT::i32
, FVal
, TVal
,
2319 SDVTList VTs
= DAG
.getVTList(Op
.getValueType(), MVT::i32
);
2320 return DAG
.getNode(ISD::MERGE_VALUES
, dl
, VTs
, Value
, Overflow
);
2323 // Prefetch operands are:
2324 // 1: Address to prefetch
2326 // 3: int locality (0 = no locality ... 3 = extreme locality)
2327 // 4: bool isDataCache
2328 static SDValue
LowerPREFETCH(SDValue Op
, SelectionDAG
&DAG
) {
2330 unsigned IsWrite
= cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue();
2331 unsigned Locality
= cast
<ConstantSDNode
>(Op
.getOperand(3))->getZExtValue();
2332 unsigned IsData
= cast
<ConstantSDNode
>(Op
.getOperand(4))->getZExtValue();
2334 bool IsStream
= !Locality
;
2335 // When the locality number is set
2337 // The front-end should have filtered out the out-of-range values
2338 assert(Locality
<= 3 && "Prefetch locality out-of-range");
2339 // The locality degree is the opposite of the cache speed.
2340 // Put the number the other way around.
2341 // The encoding starts at 0 for level 1
2342 Locality
= 3 - Locality
;
2345 // built the mask value encoding the expected behavior.
2346 unsigned PrfOp
= (IsWrite
<< 4) | // Load/Store bit
2347 (!IsData
<< 3) | // IsDataCache bit
2348 (Locality
<< 1) | // Cache level bits
2349 (unsigned)IsStream
; // Stream bit
2350 return DAG
.getNode(AArch64ISD::PREFETCH
, DL
, MVT::Other
, Op
.getOperand(0),
2351 DAG
.getConstant(PrfOp
, DL
, MVT::i32
), Op
.getOperand(1));
2354 SDValue
AArch64TargetLowering::LowerFP_EXTEND(SDValue Op
,
2355 SelectionDAG
&DAG
) const {
2356 assert(Op
.getValueType() == MVT::f128
&& "Unexpected lowering");
2359 LC
= RTLIB::getFPEXT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2361 return LowerF128Call(Op
, DAG
, LC
);
2364 SDValue
AArch64TargetLowering::LowerFP_ROUND(SDValue Op
,
2365 SelectionDAG
&DAG
) const {
2366 if (Op
.getOperand(0).getValueType() != MVT::f128
) {
2367 // It's legal except when f128 is involved
2372 LC
= RTLIB::getFPROUND(Op
.getOperand(0).getValueType(), Op
.getValueType());
2374 // FP_ROUND node has a second operand indicating whether it is known to be
2375 // precise. That doesn't take part in the LibCall so we can't directly use
2377 SDValue SrcVal
= Op
.getOperand(0);
2378 return makeLibCall(DAG
, LC
, Op
.getValueType(), SrcVal
, /*isSigned*/ false,
2382 SDValue
AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op
,
2383 SelectionDAG
&DAG
) const {
2384 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2385 // Any additional optimization in this function should be recorded
2386 // in the cost tables.
2387 EVT InVT
= Op
.getOperand(0).getValueType();
2388 EVT VT
= Op
.getValueType();
2389 unsigned NumElts
= InVT
.getVectorNumElements();
2391 // f16 conversions are promoted to f32 when full fp16 is not supported.
2392 if (InVT
.getVectorElementType() == MVT::f16
&&
2393 !Subtarget
->hasFullFP16()) {
2394 MVT NewVT
= MVT::getVectorVT(MVT::f32
, NumElts
);
2397 Op
.getOpcode(), dl
, Op
.getValueType(),
2398 DAG
.getNode(ISD::FP_EXTEND
, dl
, NewVT
, Op
.getOperand(0)));
2401 if (VT
.getSizeInBits() < InVT
.getSizeInBits()) {
2404 DAG
.getNode(Op
.getOpcode(), dl
, InVT
.changeVectorElementTypeToInteger(),
2406 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Cv
);
2409 if (VT
.getSizeInBits() > InVT
.getSizeInBits()) {
2412 MVT::getVectorVT(MVT::getFloatingPointVT(VT
.getScalarSizeInBits()),
2413 VT
.getVectorNumElements());
2414 SDValue Ext
= DAG
.getNode(ISD::FP_EXTEND
, dl
, ExtVT
, Op
.getOperand(0));
2415 return DAG
.getNode(Op
.getOpcode(), dl
, VT
, Ext
);
2418 // Type changing conversions are illegal.
2422 SDValue
AArch64TargetLowering::LowerFP_TO_INT(SDValue Op
,
2423 SelectionDAG
&DAG
) const {
2424 if (Op
.getOperand(0).getValueType().isVector())
2425 return LowerVectorFP_TO_INT(Op
, DAG
);
2427 // f16 conversions are promoted to f32 when full fp16 is not supported.
2428 if (Op
.getOperand(0).getValueType() == MVT::f16
&&
2429 !Subtarget
->hasFullFP16()) {
2432 Op
.getOpcode(), dl
, Op
.getValueType(),
2433 DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, Op
.getOperand(0)));
2436 if (Op
.getOperand(0).getValueType() != MVT::f128
) {
2437 // It's legal except when f128 is involved
2442 if (Op
.getOpcode() == ISD::FP_TO_SINT
)
2443 LC
= RTLIB::getFPTOSINT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2445 LC
= RTLIB::getFPTOUINT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2447 SmallVector
<SDValue
, 2> Ops(Op
->op_begin(), Op
->op_end());
2448 return makeLibCall(DAG
, LC
, Op
.getValueType(), Ops
, false, SDLoc(Op
)).first
;
2451 static SDValue
LowerVectorINT_TO_FP(SDValue Op
, SelectionDAG
&DAG
) {
2452 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2453 // Any additional optimization in this function should be recorded
2454 // in the cost tables.
2455 EVT VT
= Op
.getValueType();
2457 SDValue In
= Op
.getOperand(0);
2458 EVT InVT
= In
.getValueType();
2460 if (VT
.getSizeInBits() < InVT
.getSizeInBits()) {
2462 MVT::getVectorVT(MVT::getFloatingPointVT(InVT
.getScalarSizeInBits()),
2463 InVT
.getVectorNumElements());
2464 In
= DAG
.getNode(Op
.getOpcode(), dl
, CastVT
, In
);
2465 return DAG
.getNode(ISD::FP_ROUND
, dl
, VT
, In
, DAG
.getIntPtrConstant(0, dl
));
2468 if (VT
.getSizeInBits() > InVT
.getSizeInBits()) {
2470 Op
.getOpcode() == ISD::SINT_TO_FP
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
2471 EVT CastVT
= VT
.changeVectorElementTypeToInteger();
2472 In
= DAG
.getNode(CastOpc
, dl
, CastVT
, In
);
2473 return DAG
.getNode(Op
.getOpcode(), dl
, VT
, In
);
2479 SDValue
AArch64TargetLowering::LowerINT_TO_FP(SDValue Op
,
2480 SelectionDAG
&DAG
) const {
2481 if (Op
.getValueType().isVector())
2482 return LowerVectorINT_TO_FP(Op
, DAG
);
2484 // f16 conversions are promoted to f32 when full fp16 is not supported.
2485 if (Op
.getValueType() == MVT::f16
&&
2486 !Subtarget
->hasFullFP16()) {
2489 ISD::FP_ROUND
, dl
, MVT::f16
,
2490 DAG
.getNode(Op
.getOpcode(), dl
, MVT::f32
, Op
.getOperand(0)),
2491 DAG
.getIntPtrConstant(0, dl
));
2494 // i128 conversions are libcalls.
2495 if (Op
.getOperand(0).getValueType() == MVT::i128
)
2498 // Other conversions are legal, unless it's to the completely software-based
2500 if (Op
.getValueType() != MVT::f128
)
2504 if (Op
.getOpcode() == ISD::SINT_TO_FP
)
2505 LC
= RTLIB::getSINTTOFP(Op
.getOperand(0).getValueType(), Op
.getValueType());
2507 LC
= RTLIB::getUINTTOFP(Op
.getOperand(0).getValueType(), Op
.getValueType());
2509 return LowerF128Call(Op
, DAG
, LC
);
2512 SDValue
AArch64TargetLowering::LowerFSINCOS(SDValue Op
,
2513 SelectionDAG
&DAG
) const {
2514 // For iOS, we want to call an alternative entry point: __sincos_stret,
2515 // which returns the values in two S / D registers.
2517 SDValue Arg
= Op
.getOperand(0);
2518 EVT ArgVT
= Arg
.getValueType();
2519 Type
*ArgTy
= ArgVT
.getTypeForEVT(*DAG
.getContext());
2526 Entry
.IsSExt
= false;
2527 Entry
.IsZExt
= false;
2528 Args
.push_back(Entry
);
2530 RTLIB::Libcall LC
= ArgVT
== MVT::f64
? RTLIB::SINCOS_STRET_F64
2531 : RTLIB::SINCOS_STRET_F32
;
2532 const char *LibcallName
= getLibcallName(LC
);
2534 DAG
.getExternalSymbol(LibcallName
, getPointerTy(DAG
.getDataLayout()));
2536 StructType
*RetTy
= StructType::get(ArgTy
, ArgTy
);
2537 TargetLowering::CallLoweringInfo
CLI(DAG
);
2539 .setChain(DAG
.getEntryNode())
2540 .setLibCallee(CallingConv::Fast
, RetTy
, Callee
, std::move(Args
));
2542 std::pair
<SDValue
, SDValue
> CallResult
= LowerCallTo(CLI
);
2543 return CallResult
.first
;
2546 static SDValue
LowerBITCAST(SDValue Op
, SelectionDAG
&DAG
) {
2547 if (Op
.getValueType() != MVT::f16
)
2550 assert(Op
.getOperand(0).getValueType() == MVT::i16
);
2553 Op
= DAG
.getNode(ISD::ANY_EXTEND
, DL
, MVT::i32
, Op
.getOperand(0));
2554 Op
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::f32
, Op
);
2556 DAG
.getMachineNode(TargetOpcode::EXTRACT_SUBREG
, DL
, MVT::f16
, Op
,
2557 DAG
.getTargetConstant(AArch64::hsub
, DL
, MVT::i32
)),
2561 static EVT
getExtensionTo64Bits(const EVT
&OrigVT
) {
2562 if (OrigVT
.getSizeInBits() >= 64)
2565 assert(OrigVT
.isSimple() && "Expecting a simple value type");
2567 MVT::SimpleValueType OrigSimpleTy
= OrigVT
.getSimpleVT().SimpleTy
;
2568 switch (OrigSimpleTy
) {
2569 default: llvm_unreachable("Unexpected Vector Type");
2578 static SDValue
addRequiredExtensionForVectorMULL(SDValue N
, SelectionDAG
&DAG
,
2581 unsigned ExtOpcode
) {
2582 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2583 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2584 // 64-bits we need to insert a new extension so that it will be 64-bits.
2585 assert(ExtTy
.is128BitVector() && "Unexpected extension size");
2586 if (OrigTy
.getSizeInBits() >= 64)
2589 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2590 EVT NewVT
= getExtensionTo64Bits(OrigTy
);
2592 return DAG
.getNode(ExtOpcode
, SDLoc(N
), NewVT
, N
);
2595 static bool isExtendedBUILD_VECTOR(SDNode
*N
, SelectionDAG
&DAG
,
2597 EVT VT
= N
->getValueType(0);
2599 if (N
->getOpcode() != ISD::BUILD_VECTOR
)
2602 for (const SDValue
&Elt
: N
->op_values()) {
2603 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Elt
)) {
2604 unsigned EltSize
= VT
.getScalarSizeInBits();
2605 unsigned HalfSize
= EltSize
/ 2;
2607 if (!isIntN(HalfSize
, C
->getSExtValue()))
2610 if (!isUIntN(HalfSize
, C
->getZExtValue()))
2621 static SDValue
skipExtensionForVectorMULL(SDNode
*N
, SelectionDAG
&DAG
) {
2622 if (N
->getOpcode() == ISD::SIGN_EXTEND
|| N
->getOpcode() == ISD::ZERO_EXTEND
)
2623 return addRequiredExtensionForVectorMULL(N
->getOperand(0), DAG
,
2624 N
->getOperand(0)->getValueType(0),
2628 assert(N
->getOpcode() == ISD::BUILD_VECTOR
&& "expected BUILD_VECTOR");
2629 EVT VT
= N
->getValueType(0);
2631 unsigned EltSize
= VT
.getScalarSizeInBits() / 2;
2632 unsigned NumElts
= VT
.getVectorNumElements();
2633 MVT TruncVT
= MVT::getIntegerVT(EltSize
);
2634 SmallVector
<SDValue
, 8> Ops
;
2635 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2636 ConstantSDNode
*C
= cast
<ConstantSDNode
>(N
->getOperand(i
));
2637 const APInt
&CInt
= C
->getAPIntValue();
2638 // Element types smaller than 32 bits are not legal, so use i32 elements.
2639 // The values are implicitly truncated so sext vs. zext doesn't matter.
2640 Ops
.push_back(DAG
.getConstant(CInt
.zextOrTrunc(32), dl
, MVT::i32
));
2642 return DAG
.getBuildVector(MVT::getVectorVT(TruncVT
, NumElts
), dl
, Ops
);
2645 static bool isSignExtended(SDNode
*N
, SelectionDAG
&DAG
) {
2646 return N
->getOpcode() == ISD::SIGN_EXTEND
||
2647 isExtendedBUILD_VECTOR(N
, DAG
, true);
2650 static bool isZeroExtended(SDNode
*N
, SelectionDAG
&DAG
) {
2651 return N
->getOpcode() == ISD::ZERO_EXTEND
||
2652 isExtendedBUILD_VECTOR(N
, DAG
, false);
2655 static bool isAddSubSExt(SDNode
*N
, SelectionDAG
&DAG
) {
2656 unsigned Opcode
= N
->getOpcode();
2657 if (Opcode
== ISD::ADD
|| Opcode
== ISD::SUB
) {
2658 SDNode
*N0
= N
->getOperand(0).getNode();
2659 SDNode
*N1
= N
->getOperand(1).getNode();
2660 return N0
->hasOneUse() && N1
->hasOneUse() &&
2661 isSignExtended(N0
, DAG
) && isSignExtended(N1
, DAG
);
2666 static bool isAddSubZExt(SDNode
*N
, SelectionDAG
&DAG
) {
2667 unsigned Opcode
= N
->getOpcode();
2668 if (Opcode
== ISD::ADD
|| Opcode
== ISD::SUB
) {
2669 SDNode
*N0
= N
->getOperand(0).getNode();
2670 SDNode
*N1
= N
->getOperand(1).getNode();
2671 return N0
->hasOneUse() && N1
->hasOneUse() &&
2672 isZeroExtended(N0
, DAG
) && isZeroExtended(N1
, DAG
);
2677 SDValue
AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op
,
2678 SelectionDAG
&DAG
) const {
2679 // The rounding mode is in bits 23:22 of the FPSCR.
2680 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2681 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2682 // so that the shift + and get folded into a bitfield extract.
2685 SDValue FPCR_64
= DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, dl
, MVT::i64
,
2686 DAG
.getConstant(Intrinsic::aarch64_get_fpcr
, dl
,
2688 SDValue FPCR_32
= DAG
.getNode(ISD::TRUNCATE
, dl
, MVT::i32
, FPCR_64
);
2689 SDValue FltRounds
= DAG
.getNode(ISD::ADD
, dl
, MVT::i32
, FPCR_32
,
2690 DAG
.getConstant(1U << 22, dl
, MVT::i32
));
2691 SDValue RMODE
= DAG
.getNode(ISD::SRL
, dl
, MVT::i32
, FltRounds
,
2692 DAG
.getConstant(22, dl
, MVT::i32
));
2693 return DAG
.getNode(ISD::AND
, dl
, MVT::i32
, RMODE
,
2694 DAG
.getConstant(3, dl
, MVT::i32
));
2697 static SDValue
LowerMUL(SDValue Op
, SelectionDAG
&DAG
) {
2698 // Multiplications are only custom-lowered for 128-bit vectors so that
2699 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2700 EVT VT
= Op
.getValueType();
2701 assert(VT
.is128BitVector() && VT
.isInteger() &&
2702 "unexpected type for custom-lowering ISD::MUL");
2703 SDNode
*N0
= Op
.getOperand(0).getNode();
2704 SDNode
*N1
= Op
.getOperand(1).getNode();
2705 unsigned NewOpc
= 0;
2707 bool isN0SExt
= isSignExtended(N0
, DAG
);
2708 bool isN1SExt
= isSignExtended(N1
, DAG
);
2709 if (isN0SExt
&& isN1SExt
)
2710 NewOpc
= AArch64ISD::SMULL
;
2712 bool isN0ZExt
= isZeroExtended(N0
, DAG
);
2713 bool isN1ZExt
= isZeroExtended(N1
, DAG
);
2714 if (isN0ZExt
&& isN1ZExt
)
2715 NewOpc
= AArch64ISD::UMULL
;
2716 else if (isN1SExt
|| isN1ZExt
) {
2717 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2718 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2719 if (isN1SExt
&& isAddSubSExt(N0
, DAG
)) {
2720 NewOpc
= AArch64ISD::SMULL
;
2722 } else if (isN1ZExt
&& isAddSubZExt(N0
, DAG
)) {
2723 NewOpc
= AArch64ISD::UMULL
;
2725 } else if (isN0ZExt
&& isAddSubZExt(N1
, DAG
)) {
2727 NewOpc
= AArch64ISD::UMULL
;
2733 if (VT
== MVT::v2i64
)
2734 // Fall through to expand this. It is not legal.
2737 // Other vector multiplications are legal.
2742 // Legalize to a S/UMULL instruction
2745 SDValue Op1
= skipExtensionForVectorMULL(N1
, DAG
);
2747 Op0
= skipExtensionForVectorMULL(N0
, DAG
);
2748 assert(Op0
.getValueType().is64BitVector() &&
2749 Op1
.getValueType().is64BitVector() &&
2750 "unexpected types for extended operands to VMULL");
2751 return DAG
.getNode(NewOpc
, DL
, VT
, Op0
, Op1
);
2753 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2754 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2755 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2756 SDValue N00
= skipExtensionForVectorMULL(N0
->getOperand(0).getNode(), DAG
);
2757 SDValue N01
= skipExtensionForVectorMULL(N0
->getOperand(1).getNode(), DAG
);
2758 EVT Op1VT
= Op1
.getValueType();
2759 return DAG
.getNode(N0
->getOpcode(), DL
, VT
,
2760 DAG
.getNode(NewOpc
, DL
, VT
,
2761 DAG
.getNode(ISD::BITCAST
, DL
, Op1VT
, N00
), Op1
),
2762 DAG
.getNode(NewOpc
, DL
, VT
,
2763 DAG
.getNode(ISD::BITCAST
, DL
, Op1VT
, N01
), Op1
));
2766 SDValue
AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op
,
2767 SelectionDAG
&DAG
) const {
2768 unsigned IntNo
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
2771 default: return SDValue(); // Don't custom lower most intrinsics.
2772 case Intrinsic::thread_pointer
: {
2773 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
2774 return DAG
.getNode(AArch64ISD::THREAD_POINTER
, dl
, PtrVT
);
2776 case Intrinsic::aarch64_neon_abs
: {
2777 EVT Ty
= Op
.getValueType();
2778 if (Ty
== MVT::i64
) {
2779 SDValue Result
= DAG
.getNode(ISD::BITCAST
, dl
, MVT::v1i64
,
2781 Result
= DAG
.getNode(ISD::ABS
, dl
, MVT::v1i64
, Result
);
2782 return DAG
.getNode(ISD::BITCAST
, dl
, MVT::i64
, Result
);
2783 } else if (Ty
.isVector() && Ty
.isInteger() && isTypeLegal(Ty
)) {
2784 return DAG
.getNode(ISD::ABS
, dl
, Ty
, Op
.getOperand(1));
2786 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2789 case Intrinsic::aarch64_neon_smax
:
2790 return DAG
.getNode(ISD::SMAX
, dl
, Op
.getValueType(),
2791 Op
.getOperand(1), Op
.getOperand(2));
2792 case Intrinsic::aarch64_neon_umax
:
2793 return DAG
.getNode(ISD::UMAX
, dl
, Op
.getValueType(),
2794 Op
.getOperand(1), Op
.getOperand(2));
2795 case Intrinsic::aarch64_neon_smin
:
2796 return DAG
.getNode(ISD::SMIN
, dl
, Op
.getValueType(),
2797 Op
.getOperand(1), Op
.getOperand(2));
2798 case Intrinsic::aarch64_neon_umin
:
2799 return DAG
.getNode(ISD::UMIN
, dl
, Op
.getValueType(),
2800 Op
.getOperand(1), Op
.getOperand(2));
2802 case Intrinsic::localaddress
: {
2803 const auto &MF
= DAG
.getMachineFunction();
2804 const auto *RegInfo
= Subtarget
->getRegisterInfo();
2805 unsigned Reg
= RegInfo
->getLocalAddressRegister(MF
);
2806 return DAG
.getCopyFromReg(DAG
.getEntryNode(), dl
, Reg
,
2807 Op
.getSimpleValueType());
2810 case Intrinsic::eh_recoverfp
: {
2811 // FIXME: This needs to be implemented to correctly handle highly aligned
2812 // stack objects. For now we simply return the incoming FP. Refer D53541
2813 // for more details.
2814 SDValue FnOp
= Op
.getOperand(1);
2815 SDValue IncomingFPOp
= Op
.getOperand(2);
2816 GlobalAddressSDNode
*GSD
= dyn_cast
<GlobalAddressSDNode
>(FnOp
);
2817 auto *Fn
= dyn_cast_or_null
<Function
>(GSD
? GSD
->getGlobal() : nullptr);
2820 "llvm.eh.recoverfp must take a function as the first argument");
2821 return IncomingFPOp
;
2826 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2827 static SDValue
LowerTruncateVectorStore(SDLoc DL
, StoreSDNode
*ST
,
2829 SelectionDAG
&DAG
) {
2830 assert(VT
.isVector() && "VT should be a vector type");
2831 assert(MemVT
== MVT::v4i8
&& VT
== MVT::v4i16
);
2833 SDValue Value
= ST
->getValue();
2835 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2836 // the word lane which represent the v4i8 subvector. It optimizes the store
2842 SDValue Undef
= DAG
.getUNDEF(MVT::i16
);
2843 SDValue UndefVec
= DAG
.getBuildVector(MVT::v4i16
, DL
,
2844 {Undef
, Undef
, Undef
, Undef
});
2846 SDValue TruncExt
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v8i16
,
2848 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::v8i8
, TruncExt
);
2850 Trunc
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2i32
, Trunc
);
2851 SDValue ExtractTrunc
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, MVT::i32
,
2852 Trunc
, DAG
.getConstant(0, DL
, MVT::i64
));
2854 return DAG
.getStore(ST
->getChain(), DL
, ExtractTrunc
,
2855 ST
->getBasePtr(), ST
->getMemOperand());
2858 // Custom lowering for any store, vector or scalar and/or default or with
2859 // a truncate operations. Currently only custom lower truncate operation
2860 // from vector v4i16 to v4i8.
2861 SDValue
AArch64TargetLowering::LowerSTORE(SDValue Op
,
2862 SelectionDAG
&DAG
) const {
2864 StoreSDNode
*StoreNode
= cast
<StoreSDNode
>(Op
);
2865 assert (StoreNode
&& "Can only custom lower store nodes");
2867 SDValue Value
= StoreNode
->getValue();
2869 EVT VT
= Value
.getValueType();
2870 EVT MemVT
= StoreNode
->getMemoryVT();
2872 assert (VT
.isVector() && "Can only custom lower vector store types");
2874 unsigned AS
= StoreNode
->getAddressSpace();
2875 unsigned Align
= StoreNode
->getAlignment();
2876 if (Align
< MemVT
.getStoreSize() &&
2877 !allowsMisalignedMemoryAccesses(
2878 MemVT
, AS
, Align
, StoreNode
->getMemOperand()->getFlags(), nullptr)) {
2879 return scalarizeVectorStore(StoreNode
, DAG
);
2882 if (StoreNode
->isTruncatingStore()) {
2883 return LowerTruncateVectorStore(Dl
, StoreNode
, VT
, MemVT
, DAG
);
2889 SDValue
AArch64TargetLowering::LowerOperation(SDValue Op
,
2890 SelectionDAG
&DAG
) const {
2891 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2892 LLVM_DEBUG(Op
.dump());
2894 switch (Op
.getOpcode()) {
2896 llvm_unreachable("unimplemented operand");
2899 return LowerBITCAST(Op
, DAG
);
2900 case ISD::GlobalAddress
:
2901 return LowerGlobalAddress(Op
, DAG
);
2902 case ISD::GlobalTLSAddress
:
2903 return LowerGlobalTLSAddress(Op
, DAG
);
2905 return LowerSETCC(Op
, DAG
);
2907 return LowerBR_CC(Op
, DAG
);
2909 return LowerSELECT(Op
, DAG
);
2910 case ISD::SELECT_CC
:
2911 return LowerSELECT_CC(Op
, DAG
);
2912 case ISD::JumpTable
:
2913 return LowerJumpTable(Op
, DAG
);
2915 return LowerBR_JT(Op
, DAG
);
2916 case ISD::ConstantPool
:
2917 return LowerConstantPool(Op
, DAG
);
2918 case ISD::BlockAddress
:
2919 return LowerBlockAddress(Op
, DAG
);
2921 return LowerVASTART(Op
, DAG
);
2923 return LowerVACOPY(Op
, DAG
);
2925 return LowerVAARG(Op
, DAG
);
2930 return LowerADDC_ADDE_SUBC_SUBE(Op
, DAG
);
2937 return LowerXALUO(Op
, DAG
);
2939 return LowerF128Call(Op
, DAG
, RTLIB::ADD_F128
);
2941 return LowerF128Call(Op
, DAG
, RTLIB::SUB_F128
);
2943 return LowerF128Call(Op
, DAG
, RTLIB::MUL_F128
);
2945 return LowerF128Call(Op
, DAG
, RTLIB::DIV_F128
);
2947 return LowerFP_ROUND(Op
, DAG
);
2948 case ISD::FP_EXTEND
:
2949 return LowerFP_EXTEND(Op
, DAG
);
2950 case ISD::FRAMEADDR
:
2951 return LowerFRAMEADDR(Op
, DAG
);
2952 case ISD::SPONENTRY
:
2953 return LowerSPONENTRY(Op
, DAG
);
2954 case ISD::RETURNADDR
:
2955 return LowerRETURNADDR(Op
, DAG
);
2956 case ISD::ADDROFRETURNADDR
:
2957 return LowerADDROFRETURNADDR(Op
, DAG
);
2958 case ISD::INSERT_VECTOR_ELT
:
2959 return LowerINSERT_VECTOR_ELT(Op
, DAG
);
2960 case ISD::EXTRACT_VECTOR_ELT
:
2961 return LowerEXTRACT_VECTOR_ELT(Op
, DAG
);
2962 case ISD::BUILD_VECTOR
:
2963 return LowerBUILD_VECTOR(Op
, DAG
);
2964 case ISD::VECTOR_SHUFFLE
:
2965 return LowerVECTOR_SHUFFLE(Op
, DAG
);
2966 case ISD::EXTRACT_SUBVECTOR
:
2967 return LowerEXTRACT_SUBVECTOR(Op
, DAG
);
2971 return LowerVectorSRA_SRL_SHL(Op
, DAG
);
2972 case ISD::SHL_PARTS
:
2973 return LowerShiftLeftParts(Op
, DAG
);
2974 case ISD::SRL_PARTS
:
2975 case ISD::SRA_PARTS
:
2976 return LowerShiftRightParts(Op
, DAG
);
2978 return LowerCTPOP(Op
, DAG
);
2979 case ISD::FCOPYSIGN
:
2980 return LowerFCOPYSIGN(Op
, DAG
);
2982 return LowerVectorOR(Op
, DAG
);
2984 return LowerXOR(Op
, DAG
);
2986 return LowerPREFETCH(Op
, DAG
);
2987 case ISD::SINT_TO_FP
:
2988 case ISD::UINT_TO_FP
:
2989 return LowerINT_TO_FP(Op
, DAG
);
2990 case ISD::FP_TO_SINT
:
2991 case ISD::FP_TO_UINT
:
2992 return LowerFP_TO_INT(Op
, DAG
);
2994 return LowerFSINCOS(Op
, DAG
);
2995 case ISD::FLT_ROUNDS_
:
2996 return LowerFLT_ROUNDS_(Op
, DAG
);
2998 return LowerMUL(Op
, DAG
);
2999 case ISD::INTRINSIC_WO_CHAIN
:
3000 return LowerINTRINSIC_WO_CHAIN(Op
, DAG
);
3002 return LowerSTORE(Op
, DAG
);
3003 case ISD::VECREDUCE_ADD
:
3004 case ISD::VECREDUCE_SMAX
:
3005 case ISD::VECREDUCE_SMIN
:
3006 case ISD::VECREDUCE_UMAX
:
3007 case ISD::VECREDUCE_UMIN
:
3008 case ISD::VECREDUCE_FMAX
:
3009 case ISD::VECREDUCE_FMIN
:
3010 return LowerVECREDUCE(Op
, DAG
);
3011 case ISD::ATOMIC_LOAD_SUB
:
3012 return LowerATOMIC_LOAD_SUB(Op
, DAG
);
3013 case ISD::ATOMIC_LOAD_AND
:
3014 return LowerATOMIC_LOAD_AND(Op
, DAG
);
3015 case ISD::DYNAMIC_STACKALLOC
:
3016 return LowerDYNAMIC_STACKALLOC(Op
, DAG
);
3020 //===----------------------------------------------------------------------===//
3021 // Calling Convention Implementation
3022 //===----------------------------------------------------------------------===//
3024 /// Selects the correct CCAssignFn for a given CallingConvention value.
3025 CCAssignFn
*AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC
,
3026 bool IsVarArg
) const {
3029 report_fatal_error("Unsupported calling convention.");
3030 case CallingConv::WebKit_JS
:
3031 return CC_AArch64_WebKit_JS
;
3032 case CallingConv::GHC
:
3033 return CC_AArch64_GHC
;
3034 case CallingConv::C
:
3035 case CallingConv::Fast
:
3036 case CallingConv::PreserveMost
:
3037 case CallingConv::CXX_FAST_TLS
:
3038 case CallingConv::Swift
:
3039 if (Subtarget
->isTargetWindows() && IsVarArg
)
3040 return CC_AArch64_Win64_VarArg
;
3041 if (!Subtarget
->isTargetDarwin())
3042 return CC_AArch64_AAPCS
;
3043 return IsVarArg
? CC_AArch64_DarwinPCS_VarArg
: CC_AArch64_DarwinPCS
;
3044 case CallingConv::Win64
:
3045 return IsVarArg
? CC_AArch64_Win64_VarArg
: CC_AArch64_AAPCS
;
3046 case CallingConv::AArch64_VectorCall
:
3047 return CC_AArch64_AAPCS
;
3052 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC
) const {
3053 return CC
== CallingConv::WebKit_JS
? RetCC_AArch64_WebKit_JS
3054 : RetCC_AArch64_AAPCS
;
3057 SDValue
AArch64TargetLowering::LowerFormalArguments(
3058 SDValue Chain
, CallingConv::ID CallConv
, bool isVarArg
,
3059 const SmallVectorImpl
<ISD::InputArg
> &Ins
, const SDLoc
&DL
,
3060 SelectionDAG
&DAG
, SmallVectorImpl
<SDValue
> &InVals
) const {
3061 MachineFunction
&MF
= DAG
.getMachineFunction();
3062 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3063 bool IsWin64
= Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv());
3065 // Assign locations to all of the incoming arguments.
3066 SmallVector
<CCValAssign
, 16> ArgLocs
;
3067 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), ArgLocs
,
3070 // At this point, Ins[].VT may already be promoted to i32. To correctly
3071 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3072 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3073 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3074 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3076 unsigned NumArgs
= Ins
.size();
3077 Function::const_arg_iterator CurOrigArg
= MF
.getFunction().arg_begin();
3078 unsigned CurArgIdx
= 0;
3079 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3080 MVT ValVT
= Ins
[i
].VT
;
3081 if (Ins
[i
].isOrigArg()) {
3082 std::advance(CurOrigArg
, Ins
[i
].getOrigArgIndex() - CurArgIdx
);
3083 CurArgIdx
= Ins
[i
].getOrigArgIndex();
3085 // Get type of the original argument.
3086 EVT ActualVT
= getValueType(DAG
.getDataLayout(), CurOrigArg
->getType(),
3087 /*AllowUnknown*/ true);
3088 MVT ActualMVT
= ActualVT
.isSimple() ? ActualVT
.getSimpleVT() : MVT::Other
;
3089 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3090 if (ActualMVT
== MVT::i1
|| ActualMVT
== MVT::i8
)
3092 else if (ActualMVT
== MVT::i16
)
3095 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
, /*IsVarArg=*/false);
3097 AssignFn(i
, ValVT
, ValVT
, CCValAssign::Full
, Ins
[i
].Flags
, CCInfo
);
3098 assert(!Res
&& "Call operand has unhandled type");
3101 assert(ArgLocs
.size() == Ins
.size());
3102 SmallVector
<SDValue
, 16> ArgValues
;
3103 for (unsigned i
= 0, e
= ArgLocs
.size(); i
!= e
; ++i
) {
3104 CCValAssign
&VA
= ArgLocs
[i
];
3106 if (Ins
[i
].Flags
.isByVal()) {
3107 // Byval is used for HFAs in the PCS, but the system should work in a
3108 // non-compliant manner for larger structs.
3109 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
3110 int Size
= Ins
[i
].Flags
.getByValSize();
3111 unsigned NumRegs
= (Size
+ 7) / 8;
3113 // FIXME: This works on big-endian for composite byvals, which are the common
3114 // case. It should also work for fundamental types too.
3116 MFI
.CreateFixedObject(8 * NumRegs
, VA
.getLocMemOffset(), false);
3117 SDValue FrameIdxN
= DAG
.getFrameIndex(FrameIdx
, PtrVT
);
3118 InVals
.push_back(FrameIdxN
);
3123 if (VA
.isRegLoc()) {
3124 // Arguments stored in registers.
3125 EVT RegVT
= VA
.getLocVT();
3128 const TargetRegisterClass
*RC
;
3130 if (RegVT
== MVT::i32
)
3131 RC
= &AArch64::GPR32RegClass
;
3132 else if (RegVT
== MVT::i64
)
3133 RC
= &AArch64::GPR64RegClass
;
3134 else if (RegVT
== MVT::f16
)
3135 RC
= &AArch64::FPR16RegClass
;
3136 else if (RegVT
== MVT::f32
)
3137 RC
= &AArch64::FPR32RegClass
;
3138 else if (RegVT
== MVT::f64
|| RegVT
.is64BitVector())
3139 RC
= &AArch64::FPR64RegClass
;
3140 else if (RegVT
== MVT::f128
|| RegVT
.is128BitVector())
3141 RC
= &AArch64::FPR128RegClass
;
3143 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3145 // Transform the arguments in physical registers into virtual ones.
3146 unsigned Reg
= MF
.addLiveIn(VA
.getLocReg(), RC
);
3147 ArgValue
= DAG
.getCopyFromReg(Chain
, DL
, Reg
, RegVT
);
3149 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3150 // to 64 bits. Insert an assert[sz]ext to capture this, then
3151 // truncate to the right size.
3152 switch (VA
.getLocInfo()) {
3154 llvm_unreachable("Unknown loc info!");
3155 case CCValAssign::Full
:
3157 case CCValAssign::BCvt
:
3158 ArgValue
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getValVT(), ArgValue
);
3160 case CCValAssign::AExt
:
3161 case CCValAssign::SExt
:
3162 case CCValAssign::ZExt
:
3163 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3164 // nodes after our lowering.
3165 assert(RegVT
== Ins
[i
].VT
&& "incorrect register location selected");
3169 InVals
.push_back(ArgValue
);
3171 } else { // VA.isRegLoc()
3172 assert(VA
.isMemLoc() && "CCValAssign is neither reg nor mem");
3173 unsigned ArgOffset
= VA
.getLocMemOffset();
3174 unsigned ArgSize
= VA
.getValVT().getSizeInBits() / 8;
3176 uint32_t BEAlign
= 0;
3177 if (!Subtarget
->isLittleEndian() && ArgSize
< 8 &&
3178 !Ins
[i
].Flags
.isInConsecutiveRegs())
3179 BEAlign
= 8 - ArgSize
;
3181 int FI
= MFI
.CreateFixedObject(ArgSize
, ArgOffset
+ BEAlign
, true);
3183 // Create load nodes to retrieve arguments from the stack.
3184 SDValue FIN
= DAG
.getFrameIndex(FI
, getPointerTy(DAG
.getDataLayout()));
3187 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3188 ISD::LoadExtType ExtType
= ISD::NON_EXTLOAD
;
3189 MVT MemVT
= VA
.getValVT();
3191 switch (VA
.getLocInfo()) {
3194 case CCValAssign::BCvt
:
3195 MemVT
= VA
.getLocVT();
3197 case CCValAssign::SExt
:
3198 ExtType
= ISD::SEXTLOAD
;
3200 case CCValAssign::ZExt
:
3201 ExtType
= ISD::ZEXTLOAD
;
3203 case CCValAssign::AExt
:
3204 ExtType
= ISD::EXTLOAD
;
3208 ArgValue
= DAG
.getExtLoad(
3209 ExtType
, DL
, VA
.getLocVT(), Chain
, FIN
,
3210 MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(), FI
),
3213 InVals
.push_back(ArgValue
);
3218 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3220 if (!Subtarget
->isTargetDarwin() || IsWin64
) {
3221 // The AAPCS variadic function ABI is identical to the non-variadic
3222 // one. As a result there may be more arguments in registers and we should
3223 // save them for future reference.
3224 // Win64 variadic functions also pass arguments in registers, but all float
3225 // arguments are passed in integer registers.
3226 saveVarArgRegisters(CCInfo
, DAG
, DL
, Chain
);
3229 // This will point to the next argument passed via stack.
3230 unsigned StackOffset
= CCInfo
.getNextStackOffset();
3231 // We currently pass all varargs at 8-byte alignment.
3232 StackOffset
= ((StackOffset
+ 7) & ~7);
3233 FuncInfo
->setVarArgsStackIndex(MFI
.CreateFixedObject(4, StackOffset
, true));
3235 if (MFI
.hasMustTailInVarArgFunc()) {
3236 SmallVector
<MVT
, 2> RegParmTypes
;
3237 RegParmTypes
.push_back(MVT::i64
);
3238 RegParmTypes
.push_back(MVT::f128
);
3239 // Compute the set of forwarded registers. The rest are scratch.
3240 SmallVectorImpl
<ForwardedRegister
> &Forwards
=
3241 FuncInfo
->getForwardedMustTailRegParms();
3242 CCInfo
.analyzeMustTailForwardedRegisters(Forwards
, RegParmTypes
,
3245 // Conservatively forward X8, since it might be used for aggregate return.
3246 if (!CCInfo
.isAllocated(AArch64::X8
)) {
3247 unsigned X8VReg
= MF
.addLiveIn(AArch64::X8
, &AArch64::GPR64RegClass
);
3248 Forwards
.push_back(ForwardedRegister(X8VReg
, AArch64::X8
, MVT::i64
));
3253 // On Windows, InReg pointers must be returned, so record the pointer in a
3254 // virtual register at the start of the function so it can be returned in the
3257 for (unsigned I
= 0, E
= Ins
.size(); I
!= E
; ++I
) {
3258 if (Ins
[I
].Flags
.isInReg()) {
3259 assert(!FuncInfo
->getSRetReturnReg());
3261 MVT PtrTy
= getPointerTy(DAG
.getDataLayout());
3263 MF
.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy
));
3264 FuncInfo
->setSRetReturnReg(Reg
);
3266 SDValue Copy
= DAG
.getCopyToReg(DAG
.getEntryNode(), DL
, Reg
, InVals
[I
]);
3267 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, Copy
, Chain
);
3273 unsigned StackArgSize
= CCInfo
.getNextStackOffset();
3274 bool TailCallOpt
= MF
.getTarget().Options
.GuaranteedTailCallOpt
;
3275 if (DoesCalleeRestoreStack(CallConv
, TailCallOpt
)) {
3276 // This is a non-standard ABI so by fiat I say we're allowed to make full
3277 // use of the stack area to be popped, which must be aligned to 16 bytes in
3279 StackArgSize
= alignTo(StackArgSize
, 16);
3281 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3282 // a multiple of 16.
3283 FuncInfo
->setArgumentStackToRestore(StackArgSize
);
3285 // This realignment carries over to the available bytes below. Our own
3286 // callers will guarantee the space is free by giving an aligned value to
3289 // Even if we're not expected to free up the space, it's useful to know how
3290 // much is there while considering tail calls (because we can reuse it).
3291 FuncInfo
->setBytesInStackArgArea(StackArgSize
);
3293 if (Subtarget
->hasCustomCallingConv())
3294 Subtarget
->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF
);
3299 void AArch64TargetLowering::saveVarArgRegisters(CCState
&CCInfo
,
3302 SDValue
&Chain
) const {
3303 MachineFunction
&MF
= DAG
.getMachineFunction();
3304 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3305 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3306 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
3307 bool IsWin64
= Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv());
3309 SmallVector
<SDValue
, 8> MemOps
;
3311 static const MCPhysReg GPRArgRegs
[] = { AArch64::X0
, AArch64::X1
, AArch64::X2
,
3312 AArch64::X3
, AArch64::X4
, AArch64::X5
,
3313 AArch64::X6
, AArch64::X7
};
3314 static const unsigned NumGPRArgRegs
= array_lengthof(GPRArgRegs
);
3315 unsigned FirstVariadicGPR
= CCInfo
.getFirstUnallocated(GPRArgRegs
);
3317 unsigned GPRSaveSize
= 8 * (NumGPRArgRegs
- FirstVariadicGPR
);
3319 if (GPRSaveSize
!= 0) {
3321 GPRIdx
= MFI
.CreateFixedObject(GPRSaveSize
, -(int)GPRSaveSize
, false);
3322 if (GPRSaveSize
& 15)
3323 // The extra size here, if triggered, will always be 8.
3324 MFI
.CreateFixedObject(16 - (GPRSaveSize
& 15), -(int)alignTo(GPRSaveSize
, 16), false);
3326 GPRIdx
= MFI
.CreateStackObject(GPRSaveSize
, 8, false);
3328 SDValue FIN
= DAG
.getFrameIndex(GPRIdx
, PtrVT
);
3330 for (unsigned i
= FirstVariadicGPR
; i
< NumGPRArgRegs
; ++i
) {
3331 unsigned VReg
= MF
.addLiveIn(GPRArgRegs
[i
], &AArch64::GPR64RegClass
);
3332 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, VReg
, MVT::i64
);
3333 SDValue Store
= DAG
.getStore(
3334 Val
.getValue(1), DL
, Val
, FIN
,
3336 ? MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(),
3338 (i
- FirstVariadicGPR
) * 8)
3339 : MachinePointerInfo::getStack(DAG
.getMachineFunction(), i
* 8));
3340 MemOps
.push_back(Store
);
3342 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, FIN
, DAG
.getConstant(8, DL
, PtrVT
));
3345 FuncInfo
->setVarArgsGPRIndex(GPRIdx
);
3346 FuncInfo
->setVarArgsGPRSize(GPRSaveSize
);
3348 if (Subtarget
->hasFPARMv8() && !IsWin64
) {
3349 static const MCPhysReg FPRArgRegs
[] = {
3350 AArch64::Q0
, AArch64::Q1
, AArch64::Q2
, AArch64::Q3
,
3351 AArch64::Q4
, AArch64::Q5
, AArch64::Q6
, AArch64::Q7
};
3352 static const unsigned NumFPRArgRegs
= array_lengthof(FPRArgRegs
);
3353 unsigned FirstVariadicFPR
= CCInfo
.getFirstUnallocated(FPRArgRegs
);
3355 unsigned FPRSaveSize
= 16 * (NumFPRArgRegs
- FirstVariadicFPR
);
3357 if (FPRSaveSize
!= 0) {
3358 FPRIdx
= MFI
.CreateStackObject(FPRSaveSize
, 16, false);
3360 SDValue FIN
= DAG
.getFrameIndex(FPRIdx
, PtrVT
);
3362 for (unsigned i
= FirstVariadicFPR
; i
< NumFPRArgRegs
; ++i
) {
3363 unsigned VReg
= MF
.addLiveIn(FPRArgRegs
[i
], &AArch64::FPR128RegClass
);
3364 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, VReg
, MVT::f128
);
3366 SDValue Store
= DAG
.getStore(
3367 Val
.getValue(1), DL
, Val
, FIN
,
3368 MachinePointerInfo::getStack(DAG
.getMachineFunction(), i
* 16));
3369 MemOps
.push_back(Store
);
3370 FIN
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, FIN
,
3371 DAG
.getConstant(16, DL
, PtrVT
));
3374 FuncInfo
->setVarArgsFPRIndex(FPRIdx
);
3375 FuncInfo
->setVarArgsFPRSize(FPRSaveSize
);
3378 if (!MemOps
.empty()) {
3379 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOps
);
3383 /// LowerCallResult - Lower the result values of a call into the
3384 /// appropriate copies out of appropriate physical registers.
3385 SDValue
AArch64TargetLowering::LowerCallResult(
3386 SDValue Chain
, SDValue InFlag
, CallingConv::ID CallConv
, bool isVarArg
,
3387 const SmallVectorImpl
<ISD::InputArg
> &Ins
, const SDLoc
&DL
,
3388 SelectionDAG
&DAG
, SmallVectorImpl
<SDValue
> &InVals
, bool isThisReturn
,
3389 SDValue ThisVal
) const {
3390 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
3391 ? RetCC_AArch64_WebKit_JS
3392 : RetCC_AArch64_AAPCS
;
3393 // Assign locations to each value returned by this call.
3394 SmallVector
<CCValAssign
, 16> RVLocs
;
3395 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), RVLocs
,
3397 CCInfo
.AnalyzeCallResult(Ins
, RetCC
);
3399 // Copy all of the result registers out of their specified physreg.
3400 for (unsigned i
= 0; i
!= RVLocs
.size(); ++i
) {
3401 CCValAssign VA
= RVLocs
[i
];
3403 // Pass 'this' value directly from the argument to return value, to avoid
3404 // reg unit interference
3405 if (i
== 0 && isThisReturn
) {
3406 assert(!VA
.needsCustom() && VA
.getLocVT() == MVT::i64
&&
3407 "unexpected return calling convention register assignment");
3408 InVals
.push_back(ThisVal
);
3413 DAG
.getCopyFromReg(Chain
, DL
, VA
.getLocReg(), VA
.getLocVT(), InFlag
);
3414 Chain
= Val
.getValue(1);
3415 InFlag
= Val
.getValue(2);
3417 switch (VA
.getLocInfo()) {
3419 llvm_unreachable("Unknown loc info!");
3420 case CCValAssign::Full
:
3422 case CCValAssign::BCvt
:
3423 Val
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getValVT(), Val
);
3427 InVals
.push_back(Val
);
3433 /// Return true if the calling convention is one that we can guarantee TCO for.
3434 static bool canGuaranteeTCO(CallingConv::ID CC
) {
3435 return CC
== CallingConv::Fast
;
3438 /// Return true if we might ever do TCO for calls with this calling convention.
3439 static bool mayTailCallThisCC(CallingConv::ID CC
) {
3441 case CallingConv::C
:
3442 case CallingConv::PreserveMost
:
3443 case CallingConv::Swift
:
3446 return canGuaranteeTCO(CC
);
3450 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3451 SDValue Callee
, CallingConv::ID CalleeCC
, bool isVarArg
,
3452 const SmallVectorImpl
<ISD::OutputArg
> &Outs
,
3453 const SmallVectorImpl
<SDValue
> &OutVals
,
3454 const SmallVectorImpl
<ISD::InputArg
> &Ins
, SelectionDAG
&DAG
) const {
3455 if (!mayTailCallThisCC(CalleeCC
))
3458 MachineFunction
&MF
= DAG
.getMachineFunction();
3459 const Function
&CallerF
= MF
.getFunction();
3460 CallingConv::ID CallerCC
= CallerF
.getCallingConv();
3461 bool CCMatch
= CallerCC
== CalleeCC
;
3463 // Byval parameters hand the function a pointer directly into the stack area
3464 // we want to reuse during a tail call. Working around this *is* possible (see
3465 // X86) but less efficient and uglier in LowerCall.
3466 for (Function::const_arg_iterator i
= CallerF
.arg_begin(),
3467 e
= CallerF
.arg_end();
3469 if (i
->hasByValAttr())
3472 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3473 // In this case, it is necessary to save/restore X0 in the callee. Tail
3474 // call opt interferes with this. So we disable tail call opt when the
3475 // caller has an argument with "inreg" attribute.
3477 // FIXME: Check whether the callee also has an "inreg" argument.
3478 if (i
->hasInRegAttr())
3482 if (getTargetMachine().Options
.GuaranteedTailCallOpt
)
3483 return canGuaranteeTCO(CalleeCC
) && CCMatch
;
3485 // Externally-defined functions with weak linkage should not be
3486 // tail-called on AArch64 when the OS does not support dynamic
3487 // pre-emption of symbols, as the AAELF spec requires normal calls
3488 // to undefined weak functions to be replaced with a NOP or jump to the
3489 // next instruction. The behaviour of branch instructions in this
3490 // situation (as used for tail calls) is implementation-defined, so we
3491 // cannot rely on the linker replacing the tail call with a return.
3492 if (GlobalAddressSDNode
*G
= dyn_cast
<GlobalAddressSDNode
>(Callee
)) {
3493 const GlobalValue
*GV
= G
->getGlobal();
3494 const Triple
&TT
= getTargetMachine().getTargetTriple();
3495 if (GV
->hasExternalWeakLinkage() &&
3496 (!TT
.isOSWindows() || TT
.isOSBinFormatELF() || TT
.isOSBinFormatMachO()))
3500 // Now we search for cases where we can use a tail call without changing the
3501 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3504 // I want anyone implementing a new calling convention to think long and hard
3505 // about this assert.
3506 assert((!isVarArg
|| CalleeCC
== CallingConv::C
) &&
3507 "Unexpected variadic calling convention");
3509 LLVMContext
&C
= *DAG
.getContext();
3510 if (isVarArg
&& !Outs
.empty()) {
3511 // At least two cases here: if caller is fastcc then we can't have any
3512 // memory arguments (we'd be expected to clean up the stack afterwards). If
3513 // caller is C then we could potentially use its argument area.
3515 // FIXME: for now we take the most conservative of these in both cases:
3516 // disallow all variadic memory operands.
3517 SmallVector
<CCValAssign
, 16> ArgLocs
;
3518 CCState
CCInfo(CalleeCC
, isVarArg
, MF
, ArgLocs
, C
);
3520 CCInfo
.AnalyzeCallOperands(Outs
, CCAssignFnForCall(CalleeCC
, true));
3521 for (const CCValAssign
&ArgLoc
: ArgLocs
)
3522 if (!ArgLoc
.isRegLoc())
3526 // Check that the call results are passed in the same way.
3527 if (!CCState::resultsCompatible(CalleeCC
, CallerCC
, MF
, C
, Ins
,
3528 CCAssignFnForCall(CalleeCC
, isVarArg
),
3529 CCAssignFnForCall(CallerCC
, isVarArg
)))
3531 // The callee has to preserve all registers the caller needs to preserve.
3532 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
3533 const uint32_t *CallerPreserved
= TRI
->getCallPreservedMask(MF
, CallerCC
);
3535 const uint32_t *CalleePreserved
= TRI
->getCallPreservedMask(MF
, CalleeCC
);
3536 if (Subtarget
->hasCustomCallingConv()) {
3537 TRI
->UpdateCustomCallPreservedMask(MF
, &CallerPreserved
);
3538 TRI
->UpdateCustomCallPreservedMask(MF
, &CalleePreserved
);
3540 if (!TRI
->regmaskSubsetEqual(CallerPreserved
, CalleePreserved
))
3544 // Nothing more to check if the callee is taking no arguments
3548 SmallVector
<CCValAssign
, 16> ArgLocs
;
3549 CCState
CCInfo(CalleeCC
, isVarArg
, MF
, ArgLocs
, C
);
3551 CCInfo
.AnalyzeCallOperands(Outs
, CCAssignFnForCall(CalleeCC
, isVarArg
));
3553 const AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3555 // If the stack arguments for this call do not fit into our own save area then
3556 // the call cannot be made tail.
3557 if (CCInfo
.getNextStackOffset() > FuncInfo
->getBytesInStackArgArea())
3560 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
3561 if (!parametersInCSRMatch(MRI
, CallerPreserved
, ArgLocs
, OutVals
))
3567 SDValue
AArch64TargetLowering::addTokenForArgument(SDValue Chain
,
3569 MachineFrameInfo
&MFI
,
3570 int ClobberedFI
) const {
3571 SmallVector
<SDValue
, 8> ArgChains
;
3572 int64_t FirstByte
= MFI
.getObjectOffset(ClobberedFI
);
3573 int64_t LastByte
= FirstByte
+ MFI
.getObjectSize(ClobberedFI
) - 1;
3575 // Include the original chain at the beginning of the list. When this is
3576 // used by target LowerCall hooks, this helps legalize find the
3577 // CALLSEQ_BEGIN node.
3578 ArgChains
.push_back(Chain
);
3580 // Add a chain value for each stack argument corresponding
3581 for (SDNode::use_iterator U
= DAG
.getEntryNode().getNode()->use_begin(),
3582 UE
= DAG
.getEntryNode().getNode()->use_end();
3584 if (LoadSDNode
*L
= dyn_cast
<LoadSDNode
>(*U
))
3585 if (FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(L
->getBasePtr()))
3586 if (FI
->getIndex() < 0) {
3587 int64_t InFirstByte
= MFI
.getObjectOffset(FI
->getIndex());
3588 int64_t InLastByte
= InFirstByte
;
3589 InLastByte
+= MFI
.getObjectSize(FI
->getIndex()) - 1;
3591 if ((InFirstByte
<= FirstByte
&& FirstByte
<= InLastByte
) ||
3592 (FirstByte
<= InFirstByte
&& InFirstByte
<= LastByte
))
3593 ArgChains
.push_back(SDValue(L
, 1));
3596 // Build a tokenfactor for all the chains.
3597 return DAG
.getNode(ISD::TokenFactor
, SDLoc(Chain
), MVT::Other
, ArgChains
);
3600 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC
,
3601 bool TailCallOpt
) const {
3602 return CallCC
== CallingConv::Fast
&& TailCallOpt
;
3605 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3606 /// and add input and output parameter nodes.
3608 AArch64TargetLowering::LowerCall(CallLoweringInfo
&CLI
,
3609 SmallVectorImpl
<SDValue
> &InVals
) const {
3610 SelectionDAG
&DAG
= CLI
.DAG
;
3612 SmallVector
<ISD::OutputArg
, 32> &Outs
= CLI
.Outs
;
3613 SmallVector
<SDValue
, 32> &OutVals
= CLI
.OutVals
;
3614 SmallVector
<ISD::InputArg
, 32> &Ins
= CLI
.Ins
;
3615 SDValue Chain
= CLI
.Chain
;
3616 SDValue Callee
= CLI
.Callee
;
3617 bool &IsTailCall
= CLI
.IsTailCall
;
3618 CallingConv::ID CallConv
= CLI
.CallConv
;
3619 bool IsVarArg
= CLI
.IsVarArg
;
3621 MachineFunction
&MF
= DAG
.getMachineFunction();
3622 bool IsThisReturn
= false;
3624 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3625 bool TailCallOpt
= MF
.getTarget().Options
.GuaranteedTailCallOpt
;
3626 bool IsSibCall
= false;
3629 // Check if it's really possible to do a tail call.
3630 IsTailCall
= isEligibleForTailCallOptimization(
3631 Callee
, CallConv
, IsVarArg
, Outs
, OutVals
, Ins
, DAG
);
3632 if (!IsTailCall
&& CLI
.CS
&& CLI
.CS
.isMustTailCall())
3633 report_fatal_error("failed to perform tail call elimination on a call "
3634 "site marked musttail");
3636 // A sibling call is one where we're under the usual C ABI and not planning
3637 // to change that but can still do a tail call:
3638 if (!TailCallOpt
&& IsTailCall
)
3645 // Analyze operands of the call, assigning locations to each operand.
3646 SmallVector
<CCValAssign
, 16> ArgLocs
;
3647 CCState
CCInfo(CallConv
, IsVarArg
, DAG
.getMachineFunction(), ArgLocs
,
3651 // Handle fixed and variable vector arguments differently.
3652 // Variable vector arguments always go into memory.
3653 unsigned NumArgs
= Outs
.size();
3655 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3656 MVT ArgVT
= Outs
[i
].VT
;
3657 ISD::ArgFlagsTy ArgFlags
= Outs
[i
].Flags
;
3658 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
,
3659 /*IsVarArg=*/ !Outs
[i
].IsFixed
);
3660 bool Res
= AssignFn(i
, ArgVT
, ArgVT
, CCValAssign::Full
, ArgFlags
, CCInfo
);
3661 assert(!Res
&& "Call operand has unhandled type");
3665 // At this point, Outs[].VT may already be promoted to i32. To correctly
3666 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3667 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3668 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3669 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3671 unsigned NumArgs
= Outs
.size();
3672 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3673 MVT ValVT
= Outs
[i
].VT
;
3674 // Get type of the original argument.
3675 EVT ActualVT
= getValueType(DAG
.getDataLayout(),
3676 CLI
.getArgs()[Outs
[i
].OrigArgIndex
].Ty
,
3677 /*AllowUnknown*/ true);
3678 MVT ActualMVT
= ActualVT
.isSimple() ? ActualVT
.getSimpleVT() : ValVT
;
3679 ISD::ArgFlagsTy ArgFlags
= Outs
[i
].Flags
;
3680 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3681 if (ActualMVT
== MVT::i1
|| ActualMVT
== MVT::i8
)
3683 else if (ActualMVT
== MVT::i16
)
3686 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
, /*IsVarArg=*/false);
3687 bool Res
= AssignFn(i
, ValVT
, ValVT
, CCValAssign::Full
, ArgFlags
, CCInfo
);
3688 assert(!Res
&& "Call operand has unhandled type");
3693 // Get a count of how many bytes are to be pushed on the stack.
3694 unsigned NumBytes
= CCInfo
.getNextStackOffset();
3697 // Since we're not changing the ABI to make this a tail call, the memory
3698 // operands are already available in the caller's incoming argument space.
3702 // FPDiff is the byte offset of the call's argument area from the callee's.
3703 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3704 // by this amount for a tail call. In a sibling call it must be 0 because the
3705 // caller will deallocate the entire stack and the callee still expects its
3706 // arguments to begin at SP+0. Completely unused for non-tail calls.
3709 if (IsTailCall
&& !IsSibCall
) {
3710 unsigned NumReusableBytes
= FuncInfo
->getBytesInStackArgArea();
3712 // Since callee will pop argument stack as a tail call, we must keep the
3713 // popped size 16-byte aligned.
3714 NumBytes
= alignTo(NumBytes
, 16);
3716 // FPDiff will be negative if this tail call requires more space than we
3717 // would automatically have in our incoming argument space. Positive if we
3718 // can actually shrink the stack.
3719 FPDiff
= NumReusableBytes
- NumBytes
;
3721 // The stack pointer must be 16-byte aligned at all times it's used for a
3722 // memory operation, which in practice means at *all* times and in
3723 // particular across call boundaries. Therefore our own arguments started at
3724 // a 16-byte aligned SP and the delta applied for the tail call should
3725 // satisfy the same constraint.
3726 assert(FPDiff
% 16 == 0 && "unaligned stack on tail call");
3729 // Adjust the stack pointer for the new arguments...
3730 // These operations are automatically eliminated by the prolog/epilog pass
3732 Chain
= DAG
.getCALLSEQ_START(Chain
, NumBytes
, 0, DL
);
3734 SDValue StackPtr
= DAG
.getCopyFromReg(Chain
, DL
, AArch64::SP
,
3735 getPointerTy(DAG
.getDataLayout()));
3737 SmallVector
<std::pair
<unsigned, SDValue
>, 8> RegsToPass
;
3738 SmallVector
<SDValue
, 8> MemOpChains
;
3739 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
3741 if (IsVarArg
&& CLI
.CS
&& CLI
.CS
.isMustTailCall()) {
3742 const auto &Forwards
= FuncInfo
->getForwardedMustTailRegParms();
3743 for (const auto &F
: Forwards
) {
3744 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, F
.VReg
, F
.VT
);
3745 RegsToPass
.push_back(std::make_pair(unsigned(F
.PReg
), Val
));
3749 // Walk the register/memloc assignments, inserting copies/loads.
3750 for (unsigned i
= 0, realArgIdx
= 0, e
= ArgLocs
.size(); i
!= e
;
3751 ++i
, ++realArgIdx
) {
3752 CCValAssign
&VA
= ArgLocs
[i
];
3753 SDValue Arg
= OutVals
[realArgIdx
];
3754 ISD::ArgFlagsTy Flags
= Outs
[realArgIdx
].Flags
;
3756 // Promote the value if needed.
3757 switch (VA
.getLocInfo()) {
3759 llvm_unreachable("Unknown loc info!");
3760 case CCValAssign::Full
:
3762 case CCValAssign::SExt
:
3763 Arg
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3765 case CCValAssign::ZExt
:
3766 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3768 case CCValAssign::AExt
:
3769 if (Outs
[realArgIdx
].ArgVT
== MVT::i1
) {
3770 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3771 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i1
, Arg
);
3772 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i8
, Arg
);
3774 Arg
= DAG
.getNode(ISD::ANY_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3776 case CCValAssign::BCvt
:
3777 Arg
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getLocVT(), Arg
);
3779 case CCValAssign::FPExt
:
3780 Arg
= DAG
.getNode(ISD::FP_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3784 if (VA
.isRegLoc()) {
3785 if (realArgIdx
== 0 && Flags
.isReturned() && !Flags
.isSwiftSelf() &&
3786 Outs
[0].VT
== MVT::i64
) {
3787 assert(VA
.getLocVT() == MVT::i64
&&
3788 "unexpected calling convention register assignment");
3789 assert(!Ins
.empty() && Ins
[0].VT
== MVT::i64
&&
3790 "unexpected use of 'returned'");
3791 IsThisReturn
= true;
3793 RegsToPass
.push_back(std::make_pair(VA
.getLocReg(), Arg
));
3795 assert(VA
.isMemLoc());
3798 MachinePointerInfo DstInfo
;
3800 // FIXME: This works on big-endian for composite byvals, which are the
3801 // common case. It should also work for fundamental types too.
3802 uint32_t BEAlign
= 0;
3803 unsigned OpSize
= Flags
.isByVal() ? Flags
.getByValSize() * 8
3804 : VA
.getValVT().getSizeInBits();
3805 OpSize
= (OpSize
+ 7) / 8;
3806 if (!Subtarget
->isLittleEndian() && !Flags
.isByVal() &&
3807 !Flags
.isInConsecutiveRegs()) {
3809 BEAlign
= 8 - OpSize
;
3811 unsigned LocMemOffset
= VA
.getLocMemOffset();
3812 int32_t Offset
= LocMemOffset
+ BEAlign
;
3813 SDValue PtrOff
= DAG
.getIntPtrConstant(Offset
, DL
);
3814 PtrOff
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, StackPtr
, PtrOff
);
3817 Offset
= Offset
+ FPDiff
;
3818 int FI
= MF
.getFrameInfo().CreateFixedObject(OpSize
, Offset
, true);
3820 DstAddr
= DAG
.getFrameIndex(FI
, PtrVT
);
3822 MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(), FI
);
3824 // Make sure any stack arguments overlapping with where we're storing
3825 // are loaded before this eventual operation. Otherwise they'll be
3827 Chain
= addTokenForArgument(Chain
, DAG
, MF
.getFrameInfo(), FI
);
3829 SDValue PtrOff
= DAG
.getIntPtrConstant(Offset
, DL
);
3831 DstAddr
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, StackPtr
, PtrOff
);
3832 DstInfo
= MachinePointerInfo::getStack(DAG
.getMachineFunction(),
3836 if (Outs
[i
].Flags
.isByVal()) {
3838 DAG
.getConstant(Outs
[i
].Flags
.getByValSize(), DL
, MVT::i64
);
3839 SDValue Cpy
= DAG
.getMemcpy(
3840 Chain
, DL
, DstAddr
, Arg
, SizeNode
, Outs
[i
].Flags
.getByValAlign(),
3841 /*isVol = */ false, /*AlwaysInline = */ false,
3842 /*isTailCall = */ false,
3843 DstInfo
, MachinePointerInfo());
3845 MemOpChains
.push_back(Cpy
);
3847 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3848 // promoted to a legal register type i32, we should truncate Arg back to
3850 if (VA
.getValVT() == MVT::i1
|| VA
.getValVT() == MVT::i8
||
3851 VA
.getValVT() == MVT::i16
)
3852 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, VA
.getValVT(), Arg
);
3854 SDValue Store
= DAG
.getStore(Chain
, DL
, Arg
, DstAddr
, DstInfo
);
3855 MemOpChains
.push_back(Store
);
3860 if (!MemOpChains
.empty())
3861 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOpChains
);
3863 // Build a sequence of copy-to-reg nodes chained together with token chain
3864 // and flag operands which copy the outgoing args into the appropriate regs.
3866 for (auto &RegToPass
: RegsToPass
) {
3867 Chain
= DAG
.getCopyToReg(Chain
, DL
, RegToPass
.first
,
3868 RegToPass
.second
, InFlag
);
3869 InFlag
= Chain
.getValue(1);
3872 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3873 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3874 // node so that legalize doesn't hack it.
3875 if (auto *G
= dyn_cast
<GlobalAddressSDNode
>(Callee
)) {
3876 auto GV
= G
->getGlobal();
3877 if (Subtarget
->classifyGlobalFunctionReference(GV
, getTargetMachine()) ==
3878 AArch64II::MO_GOT
) {
3879 Callee
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_GOT
);
3880 Callee
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, Callee
);
3881 } else if (Subtarget
->isTargetCOFF() && GV
->hasDLLImportStorageClass()) {
3882 assert(Subtarget
->isTargetWindows() &&
3883 "Windows is the only supported COFF target");
3884 Callee
= getGOT(G
, DAG
, AArch64II::MO_DLLIMPORT
);
3886 const GlobalValue
*GV
= G
->getGlobal();
3887 Callee
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, 0);
3889 } else if (auto *S
= dyn_cast
<ExternalSymbolSDNode
>(Callee
)) {
3890 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
3891 Subtarget
->isTargetMachO()) {
3892 const char *Sym
= S
->getSymbol();
3893 Callee
= DAG
.getTargetExternalSymbol(Sym
, PtrVT
, AArch64II::MO_GOT
);
3894 Callee
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, Callee
);
3896 const char *Sym
= S
->getSymbol();
3897 Callee
= DAG
.getTargetExternalSymbol(Sym
, PtrVT
, 0);
3901 // We don't usually want to end the call-sequence here because we would tidy
3902 // the frame up *after* the call, however in the ABI-changing tail-call case
3903 // we've carefully laid out the parameters so that when sp is reset they'll be
3904 // in the correct location.
3905 if (IsTailCall
&& !IsSibCall
) {
3906 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(NumBytes
, DL
, true),
3907 DAG
.getIntPtrConstant(0, DL
, true), InFlag
, DL
);
3908 InFlag
= Chain
.getValue(1);
3911 std::vector
<SDValue
> Ops
;
3912 Ops
.push_back(Chain
);
3913 Ops
.push_back(Callee
);
3916 // Each tail call may have to adjust the stack by a different amount, so
3917 // this information must travel along with the operation for eventual
3918 // consumption by emitEpilogue.
3919 Ops
.push_back(DAG
.getTargetConstant(FPDiff
, DL
, MVT::i32
));
3922 // Add argument registers to the end of the list so that they are known live
3924 for (auto &RegToPass
: RegsToPass
)
3925 Ops
.push_back(DAG
.getRegister(RegToPass
.first
,
3926 RegToPass
.second
.getValueType()));
3928 // Add a register mask operand representing the call-preserved registers.
3929 const uint32_t *Mask
;
3930 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
3932 // For 'this' returns, use the X0-preserving mask if applicable
3933 Mask
= TRI
->getThisReturnPreservedMask(MF
, CallConv
);
3935 IsThisReturn
= false;
3936 Mask
= TRI
->getCallPreservedMask(MF
, CallConv
);
3939 Mask
= TRI
->getCallPreservedMask(MF
, CallConv
);
3941 if (Subtarget
->hasCustomCallingConv())
3942 TRI
->UpdateCustomCallPreservedMask(MF
, &Mask
);
3944 if (TRI
->isAnyArgRegReserved(MF
))
3945 TRI
->emitReservedArgRegCallError(MF
);
3947 assert(Mask
&& "Missing call preserved mask for calling convention");
3948 Ops
.push_back(DAG
.getRegisterMask(Mask
));
3950 if (InFlag
.getNode())
3951 Ops
.push_back(InFlag
);
3953 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
3955 // If we're doing a tall call, use a TC_RETURN here rather than an
3956 // actual call instruction.
3958 MF
.getFrameInfo().setHasTailCall();
3959 return DAG
.getNode(AArch64ISD::TC_RETURN
, DL
, NodeTys
, Ops
);
3962 // Returns a chain and a flag for retval copy to use.
3963 Chain
= DAG
.getNode(AArch64ISD::CALL
, DL
, NodeTys
, Ops
);
3964 InFlag
= Chain
.getValue(1);
3966 uint64_t CalleePopBytes
=
3967 DoesCalleeRestoreStack(CallConv
, TailCallOpt
) ? alignTo(NumBytes
, 16) : 0;
3969 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(NumBytes
, DL
, true),
3970 DAG
.getIntPtrConstant(CalleePopBytes
, DL
, true),
3973 InFlag
= Chain
.getValue(1);
3975 // Handle result values, copying them out of physregs into vregs that we
3977 return LowerCallResult(Chain
, InFlag
, CallConv
, IsVarArg
, Ins
, DL
, DAG
,
3978 InVals
, IsThisReturn
,
3979 IsThisReturn
? OutVals
[0] : SDValue());
3982 bool AArch64TargetLowering::CanLowerReturn(
3983 CallingConv::ID CallConv
, MachineFunction
&MF
, bool isVarArg
,
3984 const SmallVectorImpl
<ISD::OutputArg
> &Outs
, LLVMContext
&Context
) const {
3985 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
3986 ? RetCC_AArch64_WebKit_JS
3987 : RetCC_AArch64_AAPCS
;
3988 SmallVector
<CCValAssign
, 16> RVLocs
;
3989 CCState
CCInfo(CallConv
, isVarArg
, MF
, RVLocs
, Context
);
3990 return CCInfo
.CheckReturn(Outs
, RetCC
);
3994 AArch64TargetLowering::LowerReturn(SDValue Chain
, CallingConv::ID CallConv
,
3996 const SmallVectorImpl
<ISD::OutputArg
> &Outs
,
3997 const SmallVectorImpl
<SDValue
> &OutVals
,
3998 const SDLoc
&DL
, SelectionDAG
&DAG
) const {
3999 auto &MF
= DAG
.getMachineFunction();
4000 auto *FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
4002 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
4003 ? RetCC_AArch64_WebKit_JS
4004 : RetCC_AArch64_AAPCS
;
4005 SmallVector
<CCValAssign
, 16> RVLocs
;
4006 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), RVLocs
,
4008 CCInfo
.AnalyzeReturn(Outs
, RetCC
);
4010 // Copy the result values into the output registers.
4012 SmallVector
<SDValue
, 4> RetOps(1, Chain
);
4013 for (unsigned i
= 0, realRVLocIdx
= 0; i
!= RVLocs
.size();
4014 ++i
, ++realRVLocIdx
) {
4015 CCValAssign
&VA
= RVLocs
[i
];
4016 assert(VA
.isRegLoc() && "Can only return in registers!");
4017 SDValue Arg
= OutVals
[realRVLocIdx
];
4019 switch (VA
.getLocInfo()) {
4021 llvm_unreachable("Unknown loc info!");
4022 case CCValAssign::Full
:
4023 if (Outs
[i
].ArgVT
== MVT::i1
) {
4024 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4025 // value. This is strictly redundant on Darwin (which uses "zeroext
4026 // i1"), but will be optimised out before ISel.
4027 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i1
, Arg
);
4028 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VA
.getLocVT(), Arg
);
4031 case CCValAssign::BCvt
:
4032 Arg
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getLocVT(), Arg
);
4036 Chain
= DAG
.getCopyToReg(Chain
, DL
, VA
.getLocReg(), Arg
, Flag
);
4037 Flag
= Chain
.getValue(1);
4038 RetOps
.push_back(DAG
.getRegister(VA
.getLocReg(), VA
.getLocVT()));
4041 // Windows AArch64 ABIs require that for returning structs by value we copy
4042 // the sret argument into X0 for the return.
4043 // We saved the argument into a virtual register in the entry block,
4044 // so now we copy the value out and into X0.
4045 if (unsigned SRetReg
= FuncInfo
->getSRetReturnReg()) {
4046 SDValue Val
= DAG
.getCopyFromReg(RetOps
[0], DL
, SRetReg
,
4047 getPointerTy(MF
.getDataLayout()));
4049 unsigned RetValReg
= AArch64::X0
;
4050 Chain
= DAG
.getCopyToReg(Chain
, DL
, RetValReg
, Val
, Flag
);
4051 Flag
= Chain
.getValue(1);
4054 DAG
.getRegister(RetValReg
, getPointerTy(DAG
.getDataLayout())));
4057 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
4058 const MCPhysReg
*I
=
4059 TRI
->getCalleeSavedRegsViaCopy(&DAG
.getMachineFunction());
4062 if (AArch64::GPR64RegClass
.contains(*I
))
4063 RetOps
.push_back(DAG
.getRegister(*I
, MVT::i64
));
4064 else if (AArch64::FPR64RegClass
.contains(*I
))
4065 RetOps
.push_back(DAG
.getRegister(*I
, MVT::getFloatingPointVT(64)));
4067 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4071 RetOps
[0] = Chain
; // Update chain.
4073 // Add the flag if we have it.
4075 RetOps
.push_back(Flag
);
4077 return DAG
.getNode(AArch64ISD::RET_FLAG
, DL
, MVT::Other
, RetOps
);
4080 //===----------------------------------------------------------------------===//
4081 // Other Lowering Code
4082 //===----------------------------------------------------------------------===//
4084 SDValue
AArch64TargetLowering::getTargetNode(GlobalAddressSDNode
*N
, EVT Ty
,
4086 unsigned Flag
) const {
4087 return DAG
.getTargetGlobalAddress(N
->getGlobal(), SDLoc(N
), Ty
,
4088 N
->getOffset(), Flag
);
4091 SDValue
AArch64TargetLowering::getTargetNode(JumpTableSDNode
*N
, EVT Ty
,
4093 unsigned Flag
) const {
4094 return DAG
.getTargetJumpTable(N
->getIndex(), Ty
, Flag
);
4097 SDValue
AArch64TargetLowering::getTargetNode(ConstantPoolSDNode
*N
, EVT Ty
,
4099 unsigned Flag
) const {
4100 return DAG
.getTargetConstantPool(N
->getConstVal(), Ty
, N
->getAlignment(),
4101 N
->getOffset(), Flag
);
4104 SDValue
AArch64TargetLowering::getTargetNode(BlockAddressSDNode
* N
, EVT Ty
,
4106 unsigned Flag
) const {
4107 return DAG
.getTargetBlockAddress(N
->getBlockAddress(), Ty
, 0, Flag
);
4111 template <class NodeTy
>
4112 SDValue
AArch64TargetLowering::getGOT(NodeTy
*N
, SelectionDAG
&DAG
,
4113 unsigned Flags
) const {
4114 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4116 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4117 SDValue GotAddr
= getTargetNode(N
, Ty
, DAG
, AArch64II::MO_GOT
| Flags
);
4118 // FIXME: Once remat is capable of dealing with instructions with register
4119 // operands, expand this into two nodes instead of using a wrapper node.
4120 return DAG
.getNode(AArch64ISD::LOADgot
, DL
, Ty
, GotAddr
);
4123 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4124 template <class NodeTy
>
4125 SDValue
AArch64TargetLowering::getAddrLarge(NodeTy
*N
, SelectionDAG
&DAG
,
4126 unsigned Flags
) const {
4127 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4129 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4130 const unsigned char MO_NC
= AArch64II::MO_NC
;
4132 AArch64ISD::WrapperLarge
, DL
, Ty
,
4133 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G3
| Flags
),
4134 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G2
| MO_NC
| Flags
),
4135 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G1
| MO_NC
| Flags
),
4136 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G0
| MO_NC
| Flags
));
4139 // (addlow (adrp %hi(sym)) %lo(sym))
4140 template <class NodeTy
>
4141 SDValue
AArch64TargetLowering::getAddr(NodeTy
*N
, SelectionDAG
&DAG
,
4142 unsigned Flags
) const {
4143 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4145 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4146 SDValue Hi
= getTargetNode(N
, Ty
, DAG
, AArch64II::MO_PAGE
| Flags
);
4147 SDValue Lo
= getTargetNode(N
, Ty
, DAG
,
4148 AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
| Flags
);
4149 SDValue ADRP
= DAG
.getNode(AArch64ISD::ADRP
, DL
, Ty
, Hi
);
4150 return DAG
.getNode(AArch64ISD::ADDlow
, DL
, Ty
, ADRP
, Lo
);
4154 template <class NodeTy
>
4155 SDValue
AArch64TargetLowering::getAddrTiny(NodeTy
*N
, SelectionDAG
&DAG
,
4156 unsigned Flags
) const {
4157 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4159 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4160 SDValue Sym
= getTargetNode(N
, Ty
, DAG
, Flags
);
4161 return DAG
.getNode(AArch64ISD::ADR
, DL
, Ty
, Sym
);
4164 SDValue
AArch64TargetLowering::LowerGlobalAddress(SDValue Op
,
4165 SelectionDAG
&DAG
) const {
4166 GlobalAddressSDNode
*GN
= cast
<GlobalAddressSDNode
>(Op
);
4167 const GlobalValue
*GV
= GN
->getGlobal();
4168 unsigned char OpFlags
=
4169 Subtarget
->ClassifyGlobalReference(GV
, getTargetMachine());
4171 if (OpFlags
!= AArch64II::MO_NO_FLAG
)
4172 assert(cast
<GlobalAddressSDNode
>(Op
)->getOffset() == 0 &&
4173 "unexpected offset in global node");
4175 // This also catches the large code model case for Darwin, and tiny code
4176 // model with got relocations.
4177 if ((OpFlags
& AArch64II::MO_GOT
) != 0) {
4178 return getGOT(GN
, DAG
, OpFlags
);
4182 if (getTargetMachine().getCodeModel() == CodeModel::Large
) {
4183 Result
= getAddrLarge(GN
, DAG
, OpFlags
);
4184 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
4185 Result
= getAddrTiny(GN
, DAG
, OpFlags
);
4187 Result
= getAddr(GN
, DAG
, OpFlags
);
4189 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4191 if (OpFlags
& (AArch64II::MO_DLLIMPORT
| AArch64II::MO_COFFSTUB
))
4192 Result
= DAG
.getLoad(PtrVT
, DL
, DAG
.getEntryNode(), Result
,
4193 MachinePointerInfo::getGOT(DAG
.getMachineFunction()));
4197 /// Convert a TLS address reference into the correct sequence of loads
4198 /// and calls to compute the variable's address (for Darwin, currently) and
4199 /// return an SDValue containing the final node.
4201 /// Darwin only has one TLS scheme which must be capable of dealing with the
4202 /// fully general situation, in the worst case. This means:
4203 /// + "extern __thread" declaration.
4204 /// + Defined in a possibly unknown dynamic library.
4206 /// The general system is that each __thread variable has a [3 x i64] descriptor
4207 /// which contains information used by the runtime to calculate the address. The
4208 /// only part of this the compiler needs to know about is the first xword, which
4209 /// contains a function pointer that must be called with the address of the
4210 /// entire descriptor in "x0".
4212 /// Since this descriptor may be in a different unit, in general even the
4213 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4215 /// adrp x0, _var@TLVPPAGE
4216 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4217 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4218 /// ; the function pointer
4219 /// blr x1 ; Uses descriptor address in x0
4220 /// ; Address of _var is now in x0.
4222 /// If the address of _var's descriptor *is* known to the linker, then it can
4223 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4224 /// a slight efficiency gain.
4226 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op
,
4227 SelectionDAG
&DAG
) const {
4228 assert(Subtarget
->isTargetDarwin() &&
4229 "This function expects a Darwin target");
4232 MVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4233 const GlobalValue
*GV
= cast
<GlobalAddressSDNode
>(Op
)->getGlobal();
4236 DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4237 SDValue DescAddr
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, TLVPAddr
);
4239 // The first entry in the descriptor is a function pointer that we must call
4240 // to obtain the address of the variable.
4241 SDValue Chain
= DAG
.getEntryNode();
4242 SDValue FuncTLVGet
= DAG
.getLoad(
4243 MVT::i64
, DL
, Chain
, DescAddr
,
4244 MachinePointerInfo::getGOT(DAG
.getMachineFunction()),
4245 /* Alignment = */ 8,
4246 MachineMemOperand::MONonTemporal
| MachineMemOperand::MOInvariant
|
4247 MachineMemOperand::MODereferenceable
);
4248 Chain
= FuncTLVGet
.getValue(1);
4250 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
4251 MFI
.setAdjustsStack(true);
4253 // TLS calls preserve all registers except those that absolutely must be
4254 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4256 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
4257 const uint32_t *Mask
= TRI
->getTLSCallPreservedMask();
4258 if (Subtarget
->hasCustomCallingConv())
4259 TRI
->UpdateCustomCallPreservedMask(DAG
.getMachineFunction(), &Mask
);
4261 // Finally, we can make the call. This is just a degenerate version of a
4262 // normal AArch64 call node: x0 takes the address of the descriptor, and
4263 // returns the address of the variable in this thread.
4264 Chain
= DAG
.getCopyToReg(Chain
, DL
, AArch64::X0
, DescAddr
, SDValue());
4266 DAG
.getNode(AArch64ISD::CALL
, DL
, DAG
.getVTList(MVT::Other
, MVT::Glue
),
4267 Chain
, FuncTLVGet
, DAG
.getRegister(AArch64::X0
, MVT::i64
),
4268 DAG
.getRegisterMask(Mask
), Chain
.getValue(1));
4269 return DAG
.getCopyFromReg(Chain
, DL
, AArch64::X0
, PtrVT
, Chain
.getValue(1));
4272 /// When accessing thread-local variables under either the general-dynamic or
4273 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4274 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4275 /// is a function pointer to carry out the resolution.
4277 /// The sequence is:
4278 /// adrp x0, :tlsdesc:var
4279 /// ldr x1, [x0, #:tlsdesc_lo12:var]
4280 /// add x0, x0, #:tlsdesc_lo12:var
4281 /// .tlsdesccall var
4283 /// (TPIDR_EL0 offset now in x0)
4285 /// The above sequence must be produced unscheduled, to enable the linker to
4286 /// optimize/relax this sequence.
4287 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4288 /// above sequence, and expanded really late in the compilation flow, to ensure
4289 /// the sequence is produced as per above.
4290 SDValue
AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr
,
4292 SelectionDAG
&DAG
) const {
4293 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4295 SDValue Chain
= DAG
.getEntryNode();
4296 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
4299 DAG
.getNode(AArch64ISD::TLSDESC_CALLSEQ
, DL
, NodeTys
, {Chain
, SymAddr
});
4300 SDValue Glue
= Chain
.getValue(1);
4302 return DAG
.getCopyFromReg(Chain
, DL
, AArch64::X0
, PtrVT
, Glue
);
4306 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op
,
4307 SelectionDAG
&DAG
) const {
4308 assert(Subtarget
->isTargetELF() && "This function expects an ELF target");
4309 if (getTargetMachine().getCodeModel() == CodeModel::Large
)
4310 report_fatal_error("ELF TLS only supported in small memory model");
4311 // Different choices can be made for the maximum size of the TLS area for a
4312 // module. For the small address model, the default TLS size is 16MiB and the
4313 // maximum TLS size is 4GiB.
4314 // FIXME: add -mtls-size command line option and make it control the 16MiB
4315 // vs. 4GiB code sequence generation.
4316 // FIXME: add tiny codemodel support. We currently generate the same code as
4317 // small, which may be larger than needed.
4318 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4320 TLSModel::Model Model
= getTargetMachine().getTLSModel(GA
->getGlobal());
4322 if (!EnableAArch64ELFLocalDynamicTLSGeneration
) {
4323 if (Model
== TLSModel::LocalDynamic
)
4324 Model
= TLSModel::GeneralDynamic
;
4328 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4330 const GlobalValue
*GV
= GA
->getGlobal();
4332 SDValue ThreadBase
= DAG
.getNode(AArch64ISD::THREAD_POINTER
, DL
, PtrVT
);
4334 if (Model
== TLSModel::LocalExec
) {
4335 SDValue HiVar
= DAG
.getTargetGlobalAddress(
4336 GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4337 SDValue LoVar
= DAG
.getTargetGlobalAddress(
4339 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4341 SDValue TPWithOff_lo
=
4342 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, ThreadBase
,
4344 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4347 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPWithOff_lo
,
4349 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4352 } else if (Model
== TLSModel::InitialExec
) {
4353 TPOff
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4354 TPOff
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, TPOff
);
4355 } else if (Model
== TLSModel::LocalDynamic
) {
4356 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4357 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4358 // the beginning of the module's TLS region, followed by a DTPREL offset
4361 // These accesses will need deduplicating if there's more than one.
4362 AArch64FunctionInfo
*MFI
=
4363 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
4364 MFI
->incNumLocalDynamicTLSAccesses();
4366 // The call needs a relocation too for linker relaxation. It doesn't make
4367 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4369 SDValue SymAddr
= DAG
.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT
,
4372 // Now we can calculate the offset from TPIDR_EL0 to this module's
4373 // thread-local area.
4374 TPOff
= LowerELFTLSDescCallSeq(SymAddr
, DL
, DAG
);
4376 // Now use :dtprel_whatever: operations to calculate this variable's offset
4377 // in its thread-storage area.
4378 SDValue HiVar
= DAG
.getTargetGlobalAddress(
4379 GV
, DL
, MVT::i64
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4380 SDValue LoVar
= DAG
.getTargetGlobalAddress(
4381 GV
, DL
, MVT::i64
, 0,
4382 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4384 TPOff
= SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPOff
, HiVar
,
4385 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4387 TPOff
= SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPOff
, LoVar
,
4388 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4390 } else if (Model
== TLSModel::GeneralDynamic
) {
4391 // The call needs a relocation too for linker relaxation. It doesn't make
4392 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4395 DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4397 // Finally we can make a call to calculate the offset from tpidr_el0.
4398 TPOff
= LowerELFTLSDescCallSeq(SymAddr
, DL
, DAG
);
4400 llvm_unreachable("Unsupported ELF TLS access model");
4402 return DAG
.getNode(ISD::ADD
, DL
, PtrVT
, ThreadBase
, TPOff
);
4406 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op
,
4407 SelectionDAG
&DAG
) const {
4408 assert(Subtarget
->isTargetWindows() && "Windows specific TLS lowering");
4410 SDValue Chain
= DAG
.getEntryNode();
4411 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4414 SDValue TEB
= DAG
.getRegister(AArch64::X18
, MVT::i64
);
4416 // Load the ThreadLocalStoragePointer from the TEB
4417 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4419 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, TEB
, DAG
.getIntPtrConstant(0x58, DL
));
4420 TLSArray
= DAG
.getLoad(PtrVT
, DL
, Chain
, TLSArray
, MachinePointerInfo());
4421 Chain
= TLSArray
.getValue(1);
4423 // Load the TLS index from the C runtime;
4424 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4425 // This also does the same as LOADgot, but using a generic i32 load,
4426 // while LOADgot only loads i64.
4427 SDValue TLSIndexHi
=
4428 DAG
.getTargetExternalSymbol("_tls_index", PtrVT
, AArch64II::MO_PAGE
);
4429 SDValue TLSIndexLo
= DAG
.getTargetExternalSymbol(
4430 "_tls_index", PtrVT
, AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4431 SDValue ADRP
= DAG
.getNode(AArch64ISD::ADRP
, DL
, PtrVT
, TLSIndexHi
);
4433 DAG
.getNode(AArch64ISD::ADDlow
, DL
, PtrVT
, ADRP
, TLSIndexLo
);
4434 TLSIndex
= DAG
.getLoad(MVT::i32
, DL
, Chain
, TLSIndex
, MachinePointerInfo());
4435 Chain
= TLSIndex
.getValue(1);
4437 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4438 // offset into the TLSArray.
4439 TLSIndex
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, PtrVT
, TLSIndex
);
4440 SDValue Slot
= DAG
.getNode(ISD::SHL
, DL
, PtrVT
, TLSIndex
,
4441 DAG
.getConstant(3, DL
, PtrVT
));
4442 SDValue TLS
= DAG
.getLoad(PtrVT
, DL
, Chain
,
4443 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, TLSArray
, Slot
),
4444 MachinePointerInfo());
4445 Chain
= TLS
.getValue(1);
4447 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4448 const GlobalValue
*GV
= GA
->getGlobal();
4449 SDValue TGAHi
= DAG
.getTargetGlobalAddress(
4450 GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4451 SDValue TGALo
= DAG
.getTargetGlobalAddress(
4453 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4455 // Add the offset from the start of the .tls section (section base).
4457 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TLS
, TGAHi
,
4458 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4460 Addr
= DAG
.getNode(AArch64ISD::ADDlow
, DL
, PtrVT
, Addr
, TGALo
);
4464 SDValue
AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op
,
4465 SelectionDAG
&DAG
) const {
4466 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4467 if (DAG
.getTarget().useEmulatedTLS())
4468 return LowerToTLSEmulatedModel(GA
, DAG
);
4470 if (Subtarget
->isTargetDarwin())
4471 return LowerDarwinGlobalTLSAddress(Op
, DAG
);
4472 if (Subtarget
->isTargetELF())
4473 return LowerELFGlobalTLSAddress(Op
, DAG
);
4474 if (Subtarget
->isTargetWindows())
4475 return LowerWindowsGlobalTLSAddress(Op
, DAG
);
4477 llvm_unreachable("Unexpected platform trying to use TLS");
4480 SDValue
AArch64TargetLowering::LowerBR_CC(SDValue Op
, SelectionDAG
&DAG
) const {
4481 SDValue Chain
= Op
.getOperand(0);
4482 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(1))->get();
4483 SDValue LHS
= Op
.getOperand(2);
4484 SDValue RHS
= Op
.getOperand(3);
4485 SDValue Dest
= Op
.getOperand(4);
4488 MachineFunction
&MF
= DAG
.getMachineFunction();
4489 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4490 // will not be produced, as they are conditional branch instructions that do
4492 bool ProduceNonFlagSettingCondBr
=
4493 !MF
.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening
);
4495 // Handle f128 first, since lowering it will result in comparing the return
4496 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4497 // is expecting to deal with.
4498 if (LHS
.getValueType() == MVT::f128
) {
4499 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
);
4501 // If softenSetCCOperands returned a scalar, we need to compare the result
4502 // against zero to select between true and false values.
4503 if (!RHS
.getNode()) {
4504 RHS
= DAG
.getConstant(0, dl
, LHS
.getValueType());
4509 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4511 if (isOverflowIntrOpRes(LHS
) && isOneConstant(RHS
) &&
4512 (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
4513 // Only lower legal XALUO ops.
4514 if (!DAG
.getTargetLoweringInfo().isTypeLegal(LHS
->getValueType(0)))
4517 // The actual operation with overflow check.
4518 AArch64CC::CondCode OFCC
;
4519 SDValue Value
, Overflow
;
4520 std::tie(Value
, Overflow
) = getAArch64XALUOOp(OFCC
, LHS
.getValue(0), DAG
);
4522 if (CC
== ISD::SETNE
)
4523 OFCC
= getInvertedCondCode(OFCC
);
4524 SDValue CCVal
= DAG
.getConstant(OFCC
, dl
, MVT::i32
);
4526 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CCVal
,
4530 if (LHS
.getValueType().isInteger()) {
4531 assert((LHS
.getValueType() == RHS
.getValueType()) &&
4532 (LHS
.getValueType() == MVT::i32
|| LHS
.getValueType() == MVT::i64
));
4534 // If the RHS of the comparison is zero, we can potentially fold this
4535 // to a specialized branch.
4536 const ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(RHS
);
4537 if (RHSC
&& RHSC
->getZExtValue() == 0 && ProduceNonFlagSettingCondBr
) {
4538 if (CC
== ISD::SETEQ
) {
4539 // See if we can use a TBZ to fold in an AND as well.
4540 // TBZ has a smaller branch displacement than CBZ. If the offset is
4541 // out of bounds, a late MI-layer pass rewrites branches.
4542 // 403.gcc is an example that hits this case.
4543 if (LHS
.getOpcode() == ISD::AND
&&
4544 isa
<ConstantSDNode
>(LHS
.getOperand(1)) &&
4545 isPowerOf2_64(LHS
.getConstantOperandVal(1))) {
4546 SDValue Test
= LHS
.getOperand(0);
4547 uint64_t Mask
= LHS
.getConstantOperandVal(1);
4548 return DAG
.getNode(AArch64ISD::TBZ
, dl
, MVT::Other
, Chain
, Test
,
4549 DAG
.getConstant(Log2_64(Mask
), dl
, MVT::i64
),
4553 return DAG
.getNode(AArch64ISD::CBZ
, dl
, MVT::Other
, Chain
, LHS
, Dest
);
4554 } else if (CC
== ISD::SETNE
) {
4555 // See if we can use a TBZ to fold in an AND as well.
4556 // TBZ has a smaller branch displacement than CBZ. If the offset is
4557 // out of bounds, a late MI-layer pass rewrites branches.
4558 // 403.gcc is an example that hits this case.
4559 if (LHS
.getOpcode() == ISD::AND
&&
4560 isa
<ConstantSDNode
>(LHS
.getOperand(1)) &&
4561 isPowerOf2_64(LHS
.getConstantOperandVal(1))) {
4562 SDValue Test
= LHS
.getOperand(0);
4563 uint64_t Mask
= LHS
.getConstantOperandVal(1);
4564 return DAG
.getNode(AArch64ISD::TBNZ
, dl
, MVT::Other
, Chain
, Test
,
4565 DAG
.getConstant(Log2_64(Mask
), dl
, MVT::i64
),
4569 return DAG
.getNode(AArch64ISD::CBNZ
, dl
, MVT::Other
, Chain
, LHS
, Dest
);
4570 } else if (CC
== ISD::SETLT
&& LHS
.getOpcode() != ISD::AND
) {
4571 // Don't combine AND since emitComparison converts the AND to an ANDS
4572 // (a.k.a. TST) and the test in the test bit and branch instruction
4573 // becomes redundant. This would also increase register pressure.
4574 uint64_t Mask
= LHS
.getValueSizeInBits() - 1;
4575 return DAG
.getNode(AArch64ISD::TBNZ
, dl
, MVT::Other
, Chain
, LHS
,
4576 DAG
.getConstant(Mask
, dl
, MVT::i64
), Dest
);
4579 if (RHSC
&& RHSC
->getSExtValue() == -1 && CC
== ISD::SETGT
&&
4580 LHS
.getOpcode() != ISD::AND
&& ProduceNonFlagSettingCondBr
) {
4581 // Don't combine AND since emitComparison converts the AND to an ANDS
4582 // (a.k.a. TST) and the test in the test bit and branch instruction
4583 // becomes redundant. This would also increase register pressure.
4584 uint64_t Mask
= LHS
.getValueSizeInBits() - 1;
4585 return DAG
.getNode(AArch64ISD::TBZ
, dl
, MVT::Other
, Chain
, LHS
,
4586 DAG
.getConstant(Mask
, dl
, MVT::i64
), Dest
);
4590 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
4591 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CCVal
,
4595 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4596 LHS
.getValueType() == MVT::f64
);
4598 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4599 // clean. Some of them require two branches to implement.
4600 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4601 AArch64CC::CondCode CC1
, CC2
;
4602 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4603 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4605 DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CC1Val
, Cmp
);
4606 if (CC2
!= AArch64CC::AL
) {
4607 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
4608 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, BR1
, Dest
, CC2Val
,
4615 SDValue
AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op
,
4616 SelectionDAG
&DAG
) const {
4617 EVT VT
= Op
.getValueType();
4620 SDValue In1
= Op
.getOperand(0);
4621 SDValue In2
= Op
.getOperand(1);
4622 EVT SrcVT
= In2
.getValueType();
4624 if (SrcVT
.bitsLT(VT
))
4625 In2
= DAG
.getNode(ISD::FP_EXTEND
, DL
, VT
, In2
);
4626 else if (SrcVT
.bitsGT(VT
))
4627 In2
= DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, In2
, DAG
.getIntPtrConstant(0, DL
));
4631 SDValue VecVal1
, VecVal2
;
4633 auto setVecVal
= [&] (int Idx
) {
4634 if (!VT
.isVector()) {
4635 VecVal1
= DAG
.getTargetInsertSubreg(Idx
, DL
, VecVT
,
4636 DAG
.getUNDEF(VecVT
), In1
);
4637 VecVal2
= DAG
.getTargetInsertSubreg(Idx
, DL
, VecVT
,
4638 DAG
.getUNDEF(VecVT
), In2
);
4640 VecVal1
= DAG
.getNode(ISD::BITCAST
, DL
, VecVT
, In1
);
4641 VecVal2
= DAG
.getNode(ISD::BITCAST
, DL
, VecVT
, In2
);
4645 if (VT
== MVT::f32
|| VT
== MVT::v2f32
|| VT
== MVT::v4f32
) {
4646 VecVT
= (VT
== MVT::v2f32
? MVT::v2i32
: MVT::v4i32
);
4647 EltMask
= 0x80000000ULL
;
4648 setVecVal(AArch64::ssub
);
4649 } else if (VT
== MVT::f64
|| VT
== MVT::v2f64
) {
4652 // We want to materialize a mask with the high bit set, but the AdvSIMD
4653 // immediate moves cannot materialize that in a single instruction for
4654 // 64-bit elements. Instead, materialize zero and then negate it.
4657 setVecVal(AArch64::dsub
);
4658 } else if (VT
== MVT::f16
|| VT
== MVT::v4f16
|| VT
== MVT::v8f16
) {
4659 VecVT
= (VT
== MVT::v4f16
? MVT::v4i16
: MVT::v8i16
);
4660 EltMask
= 0x8000ULL
;
4661 setVecVal(AArch64::hsub
);
4663 llvm_unreachable("Invalid type for copysign!");
4666 SDValue BuildVec
= DAG
.getConstant(EltMask
, DL
, VecVT
);
4668 // If we couldn't materialize the mask above, then the mask vector will be
4669 // the zero vector, and we need to negate it here.
4670 if (VT
== MVT::f64
|| VT
== MVT::v2f64
) {
4671 BuildVec
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2f64
, BuildVec
);
4672 BuildVec
= DAG
.getNode(ISD::FNEG
, DL
, MVT::v2f64
, BuildVec
);
4673 BuildVec
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2i64
, BuildVec
);
4677 DAG
.getNode(AArch64ISD::BIT
, DL
, VecVT
, VecVal1
, VecVal2
, BuildVec
);
4680 return DAG
.getTargetExtractSubreg(AArch64::hsub
, DL
, VT
, Sel
);
4682 return DAG
.getTargetExtractSubreg(AArch64::ssub
, DL
, VT
, Sel
);
4683 else if (VT
== MVT::f64
)
4684 return DAG
.getTargetExtractSubreg(AArch64::dsub
, DL
, VT
, Sel
);
4686 return DAG
.getNode(ISD::BITCAST
, DL
, VT
, Sel
);
4689 SDValue
AArch64TargetLowering::LowerCTPOP(SDValue Op
, SelectionDAG
&DAG
) const {
4690 if (DAG
.getMachineFunction().getFunction().hasFnAttribute(
4691 Attribute::NoImplicitFloat
))
4694 if (!Subtarget
->hasNEON())
4697 // While there is no integer popcount instruction, it can
4698 // be more efficiently lowered to the following sequence that uses
4699 // AdvSIMD registers/instructions as long as the copies to/from
4700 // the AdvSIMD registers are cheap.
4701 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4702 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4703 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4704 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4705 SDValue Val
= Op
.getOperand(0);
4707 EVT VT
= Op
.getValueType();
4709 if (VT
== MVT::i32
|| VT
== MVT::i64
) {
4711 Val
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i64
, Val
);
4712 Val
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v8i8
, Val
);
4714 SDValue CtPop
= DAG
.getNode(ISD::CTPOP
, DL
, MVT::v8i8
, Val
);
4715 SDValue UaddLV
= DAG
.getNode(
4716 ISD::INTRINSIC_WO_CHAIN
, DL
, MVT::i32
,
4717 DAG
.getConstant(Intrinsic::aarch64_neon_uaddlv
, DL
, MVT::i32
), CtPop
);
4720 UaddLV
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i64
, UaddLV
);
4724 assert((VT
== MVT::v1i64
|| VT
== MVT::v2i64
|| VT
== MVT::v2i32
||
4725 VT
== MVT::v4i32
|| VT
== MVT::v4i16
|| VT
== MVT::v8i16
) &&
4726 "Unexpected type for custom ctpop lowering");
4728 EVT VT8Bit
= VT
.is64BitVector() ? MVT::v8i8
: MVT::v16i8
;
4729 Val
= DAG
.getBitcast(VT8Bit
, Val
);
4730 Val
= DAG
.getNode(ISD::CTPOP
, DL
, VT8Bit
, Val
);
4732 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4733 unsigned EltSize
= 8;
4734 unsigned NumElts
= VT
.is64BitVector() ? 8 : 16;
4735 while (EltSize
!= VT
.getScalarSizeInBits()) {
4738 MVT WidenVT
= MVT::getVectorVT(MVT::getIntegerVT(EltSize
), NumElts
);
4740 ISD::INTRINSIC_WO_CHAIN
, DL
, WidenVT
,
4741 DAG
.getConstant(Intrinsic::aarch64_neon_uaddlp
, DL
, MVT::i32
), Val
);
4747 SDValue
AArch64TargetLowering::LowerSETCC(SDValue Op
, SelectionDAG
&DAG
) const {
4749 if (Op
.getValueType().isVector())
4750 return LowerVSETCC(Op
, DAG
);
4752 SDValue LHS
= Op
.getOperand(0);
4753 SDValue RHS
= Op
.getOperand(1);
4754 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
4757 // We chose ZeroOrOneBooleanContents, so use zero and one.
4758 EVT VT
= Op
.getValueType();
4759 SDValue TVal
= DAG
.getConstant(1, dl
, VT
);
4760 SDValue FVal
= DAG
.getConstant(0, dl
, VT
);
4762 // Handle f128 first, since one possible outcome is a normal integer
4763 // comparison which gets picked up by the next if statement.
4764 if (LHS
.getValueType() == MVT::f128
) {
4765 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
);
4767 // If softenSetCCOperands returned a scalar, use it.
4768 if (!RHS
.getNode()) {
4769 assert(LHS
.getValueType() == Op
.getValueType() &&
4770 "Unexpected setcc expansion!");
4775 if (LHS
.getValueType().isInteger()) {
4778 getAArch64Cmp(LHS
, RHS
, ISD::getSetCCInverse(CC
, true), CCVal
, DAG
, dl
);
4780 // Note that we inverted the condition above, so we reverse the order of
4781 // the true and false operands here. This will allow the setcc to be
4782 // matched to a single CSINC instruction.
4783 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, FVal
, TVal
, CCVal
, Cmp
);
4786 // Now we know we're dealing with FP values.
4787 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4788 LHS
.getValueType() == MVT::f64
);
4790 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4791 // and do the comparison.
4792 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4794 AArch64CC::CondCode CC1
, CC2
;
4795 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4796 if (CC2
== AArch64CC::AL
) {
4797 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC
, false), CC1
, CC2
);
4798 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4800 // Note that we inverted the condition above, so we reverse the order of
4801 // the true and false operands here. This will allow the setcc to be
4802 // matched to a single CSINC instruction.
4803 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, FVal
, TVal
, CC1Val
, Cmp
);
4805 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4806 // totally clean. Some of them require two CSELs to implement. As is in
4807 // this case, we emit the first CSEL and then emit a second using the output
4808 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4810 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4811 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4813 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, FVal
, CC1Val
, Cmp
);
4815 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
4816 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, CS1
, CC2Val
, Cmp
);
4820 SDValue
AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC
, SDValue LHS
,
4821 SDValue RHS
, SDValue TVal
,
4822 SDValue FVal
, const SDLoc
&dl
,
4823 SelectionDAG
&DAG
) const {
4824 // Handle f128 first, because it will result in a comparison of some RTLIB
4825 // call result against zero.
4826 if (LHS
.getValueType() == MVT::f128
) {
4827 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
);
4829 // If softenSetCCOperands returned a scalar, we need to compare the result
4830 // against zero to select between true and false values.
4831 if (!RHS
.getNode()) {
4832 RHS
= DAG
.getConstant(0, dl
, LHS
.getValueType());
4837 // Also handle f16, for which we need to do a f32 comparison.
4838 if (LHS
.getValueType() == MVT::f16
&& !Subtarget
->hasFullFP16()) {
4839 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, LHS
);
4840 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, RHS
);
4843 // Next, handle integers.
4844 if (LHS
.getValueType().isInteger()) {
4845 assert((LHS
.getValueType() == RHS
.getValueType()) &&
4846 (LHS
.getValueType() == MVT::i32
|| LHS
.getValueType() == MVT::i64
));
4848 unsigned Opcode
= AArch64ISD::CSEL
;
4850 // If both the TVal and the FVal are constants, see if we can swap them in
4851 // order to for a CSINV or CSINC out of them.
4852 ConstantSDNode
*CFVal
= dyn_cast
<ConstantSDNode
>(FVal
);
4853 ConstantSDNode
*CTVal
= dyn_cast
<ConstantSDNode
>(TVal
);
4855 if (CTVal
&& CFVal
&& CTVal
->isAllOnesValue() && CFVal
->isNullValue()) {
4856 std::swap(TVal
, FVal
);
4857 std::swap(CTVal
, CFVal
);
4858 CC
= ISD::getSetCCInverse(CC
, true);
4859 } else if (CTVal
&& CFVal
&& CTVal
->isOne() && CFVal
->isNullValue()) {
4860 std::swap(TVal
, FVal
);
4861 std::swap(CTVal
, CFVal
);
4862 CC
= ISD::getSetCCInverse(CC
, true);
4863 } else if (TVal
.getOpcode() == ISD::XOR
) {
4864 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4865 // with a CSINV rather than a CSEL.
4866 if (isAllOnesConstant(TVal
.getOperand(1))) {
4867 std::swap(TVal
, FVal
);
4868 std::swap(CTVal
, CFVal
);
4869 CC
= ISD::getSetCCInverse(CC
, true);
4871 } else if (TVal
.getOpcode() == ISD::SUB
) {
4872 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4873 // that we can match with a CSNEG rather than a CSEL.
4874 if (isNullConstant(TVal
.getOperand(0))) {
4875 std::swap(TVal
, FVal
);
4876 std::swap(CTVal
, CFVal
);
4877 CC
= ISD::getSetCCInverse(CC
, true);
4879 } else if (CTVal
&& CFVal
) {
4880 const int64_t TrueVal
= CTVal
->getSExtValue();
4881 const int64_t FalseVal
= CFVal
->getSExtValue();
4884 // If both TVal and FVal are constants, see if FVal is the
4885 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4886 // instead of a CSEL in that case.
4887 if (TrueVal
== ~FalseVal
) {
4888 Opcode
= AArch64ISD::CSINV
;
4889 } else if (TrueVal
== -FalseVal
) {
4890 Opcode
= AArch64ISD::CSNEG
;
4891 } else if (TVal
.getValueType() == MVT::i32
) {
4892 // If our operands are only 32-bit wide, make sure we use 32-bit
4893 // arithmetic for the check whether we can use CSINC. This ensures that
4894 // the addition in the check will wrap around properly in case there is
4895 // an overflow (which would not be the case if we do the check with
4896 // 64-bit arithmetic).
4897 const uint32_t TrueVal32
= CTVal
->getZExtValue();
4898 const uint32_t FalseVal32
= CFVal
->getZExtValue();
4900 if ((TrueVal32
== FalseVal32
+ 1) || (TrueVal32
+ 1 == FalseVal32
)) {
4901 Opcode
= AArch64ISD::CSINC
;
4903 if (TrueVal32
> FalseVal32
) {
4907 // 64-bit check whether we can use CSINC.
4908 } else if ((TrueVal
== FalseVal
+ 1) || (TrueVal
+ 1 == FalseVal
)) {
4909 Opcode
= AArch64ISD::CSINC
;
4911 if (TrueVal
> FalseVal
) {
4916 // Swap TVal and FVal if necessary.
4918 std::swap(TVal
, FVal
);
4919 std::swap(CTVal
, CFVal
);
4920 CC
= ISD::getSetCCInverse(CC
, true);
4923 if (Opcode
!= AArch64ISD::CSEL
) {
4924 // Drop FVal since we can get its value by simply inverting/negating
4930 // Avoid materializing a constant when possible by reusing a known value in
4931 // a register. However, don't perform this optimization if the known value
4932 // is one, zero or negative one in the case of a CSEL. We can always
4933 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4934 // FVal, respectively.
4935 ConstantSDNode
*RHSVal
= dyn_cast
<ConstantSDNode
>(RHS
);
4936 if (Opcode
== AArch64ISD::CSEL
&& RHSVal
&& !RHSVal
->isOne() &&
4937 !RHSVal
->isNullValue() && !RHSVal
->isAllOnesValue()) {
4938 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
4939 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4940 // "a != C ? x : a" to avoid materializing C.
4941 if (CTVal
&& CTVal
== RHSVal
&& AArch64CC
== AArch64CC::EQ
)
4943 else if (CFVal
&& CFVal
== RHSVal
&& AArch64CC
== AArch64CC::NE
)
4945 } else if (Opcode
== AArch64ISD::CSNEG
&& RHSVal
&& RHSVal
->isOne()) {
4946 assert (CTVal
&& CFVal
&& "Expected constant operands for CSNEG.");
4947 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4948 // avoid materializing C.
4949 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
4950 if (CTVal
== RHSVal
&& AArch64CC
== AArch64CC::EQ
) {
4951 Opcode
= AArch64ISD::CSINV
;
4953 FVal
= DAG
.getConstant(0, dl
, FVal
.getValueType());
4958 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
4959 EVT VT
= TVal
.getValueType();
4960 return DAG
.getNode(Opcode
, dl
, VT
, TVal
, FVal
, CCVal
, Cmp
);
4963 // Now we know we're dealing with FP values.
4964 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4965 LHS
.getValueType() == MVT::f64
);
4966 assert(LHS
.getValueType() == RHS
.getValueType());
4967 EVT VT
= TVal
.getValueType();
4968 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4970 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4971 // clean. Some of them require two CSELs to implement.
4972 AArch64CC::CondCode CC1
, CC2
;
4973 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4975 if (DAG
.getTarget().Options
.UnsafeFPMath
) {
4976 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4977 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4978 ConstantFPSDNode
*RHSVal
= dyn_cast
<ConstantFPSDNode
>(RHS
);
4979 if (RHSVal
&& RHSVal
->isZero()) {
4980 ConstantFPSDNode
*CFVal
= dyn_cast
<ConstantFPSDNode
>(FVal
);
4981 ConstantFPSDNode
*CTVal
= dyn_cast
<ConstantFPSDNode
>(TVal
);
4983 if ((CC
== ISD::SETEQ
|| CC
== ISD::SETOEQ
|| CC
== ISD::SETUEQ
) &&
4984 CTVal
&& CTVal
->isZero() && TVal
.getValueType() == LHS
.getValueType())
4986 else if ((CC
== ISD::SETNE
|| CC
== ISD::SETONE
|| CC
== ISD::SETUNE
) &&
4987 CFVal
&& CFVal
->isZero() &&
4988 FVal
.getValueType() == LHS
.getValueType())
4993 // Emit first, and possibly only, CSEL.
4994 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4995 SDValue CS1
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, FVal
, CC1Val
, Cmp
);
4997 // If we need a second CSEL, emit it, using the output of the first as the
4998 // RHS. We're effectively OR'ing the two CC's together.
4999 if (CC2
!= AArch64CC::AL
) {
5000 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
5001 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, CS1
, CC2Val
, Cmp
);
5004 // Otherwise, return the output of the first CSEL.
5008 SDValue
AArch64TargetLowering::LowerSELECT_CC(SDValue Op
,
5009 SelectionDAG
&DAG
) const {
5010 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(4))->get();
5011 SDValue LHS
= Op
.getOperand(0);
5012 SDValue RHS
= Op
.getOperand(1);
5013 SDValue TVal
= Op
.getOperand(2);
5014 SDValue FVal
= Op
.getOperand(3);
5016 return LowerSELECT_CC(CC
, LHS
, RHS
, TVal
, FVal
, DL
, DAG
);
5019 SDValue
AArch64TargetLowering::LowerSELECT(SDValue Op
,
5020 SelectionDAG
&DAG
) const {
5021 SDValue CCVal
= Op
->getOperand(0);
5022 SDValue TVal
= Op
->getOperand(1);
5023 SDValue FVal
= Op
->getOperand(2);
5026 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5028 if (isOverflowIntrOpRes(CCVal
)) {
5029 // Only lower legal XALUO ops.
5030 if (!DAG
.getTargetLoweringInfo().isTypeLegal(CCVal
->getValueType(0)))
5033 AArch64CC::CondCode OFCC
;
5034 SDValue Value
, Overflow
;
5035 std::tie(Value
, Overflow
) = getAArch64XALUOOp(OFCC
, CCVal
.getValue(0), DAG
);
5036 SDValue CCVal
= DAG
.getConstant(OFCC
, DL
, MVT::i32
);
5038 return DAG
.getNode(AArch64ISD::CSEL
, DL
, Op
.getValueType(), TVal
, FVal
,
5042 // Lower it the same way as we would lower a SELECT_CC node.
5045 if (CCVal
.getOpcode() == ISD::SETCC
) {
5046 LHS
= CCVal
.getOperand(0);
5047 RHS
= CCVal
.getOperand(1);
5048 CC
= cast
<CondCodeSDNode
>(CCVal
->getOperand(2))->get();
5051 RHS
= DAG
.getConstant(0, DL
, CCVal
.getValueType());
5054 return LowerSELECT_CC(CC
, LHS
, RHS
, TVal
, FVal
, DL
, DAG
);
5057 SDValue
AArch64TargetLowering::LowerJumpTable(SDValue Op
,
5058 SelectionDAG
&DAG
) const {
5059 // Jump table entries as PC relative offsets. No additional tweaking
5060 // is necessary here. Just get the address of the jump table.
5061 JumpTableSDNode
*JT
= cast
<JumpTableSDNode
>(Op
);
5063 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
5064 !Subtarget
->isTargetMachO()) {
5065 return getAddrLarge(JT
, DAG
);
5066 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
5067 return getAddrTiny(JT
, DAG
);
5069 return getAddr(JT
, DAG
);
5072 SDValue
AArch64TargetLowering::LowerBR_JT(SDValue Op
,
5073 SelectionDAG
&DAG
) const {
5074 // Jump table entries as PC relative offsets. No additional tweaking
5075 // is necessary here. Just get the address of the jump table.
5077 SDValue JT
= Op
.getOperand(1);
5078 SDValue Entry
= Op
.getOperand(2);
5079 int JTI
= cast
<JumpTableSDNode
>(JT
.getNode())->getIndex();
5082 DAG
.getMachineNode(AArch64::JumpTableDest32
, DL
, MVT::i64
, MVT::i64
, JT
,
5083 Entry
, DAG
.getTargetJumpTable(JTI
, MVT::i32
));
5084 return DAG
.getNode(ISD::BRIND
, DL
, MVT::Other
, Op
.getOperand(0),
5088 SDValue
AArch64TargetLowering::LowerConstantPool(SDValue Op
,
5089 SelectionDAG
&DAG
) const {
5090 ConstantPoolSDNode
*CP
= cast
<ConstantPoolSDNode
>(Op
);
5092 if (getTargetMachine().getCodeModel() == CodeModel::Large
) {
5093 // Use the GOT for the large code model on iOS.
5094 if (Subtarget
->isTargetMachO()) {
5095 return getGOT(CP
, DAG
);
5097 return getAddrLarge(CP
, DAG
);
5098 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
5099 return getAddrTiny(CP
, DAG
);
5101 return getAddr(CP
, DAG
);
5105 SDValue
AArch64TargetLowering::LowerBlockAddress(SDValue Op
,
5106 SelectionDAG
&DAG
) const {
5107 BlockAddressSDNode
*BA
= cast
<BlockAddressSDNode
>(Op
);
5108 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
5109 !Subtarget
->isTargetMachO()) {
5110 return getAddrLarge(BA
, DAG
);
5111 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
5112 return getAddrTiny(BA
, DAG
);
5114 return getAddr(BA
, DAG
);
5117 SDValue
AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op
,
5118 SelectionDAG
&DAG
) const {
5119 AArch64FunctionInfo
*FuncInfo
=
5120 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
5123 SDValue FR
= DAG
.getFrameIndex(FuncInfo
->getVarArgsStackIndex(),
5124 getPointerTy(DAG
.getDataLayout()));
5125 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5126 return DAG
.getStore(Op
.getOperand(0), DL
, FR
, Op
.getOperand(1),
5127 MachinePointerInfo(SV
));
5130 SDValue
AArch64TargetLowering::LowerWin64_VASTART(SDValue Op
,
5131 SelectionDAG
&DAG
) const {
5132 AArch64FunctionInfo
*FuncInfo
=
5133 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
5136 SDValue FR
= DAG
.getFrameIndex(FuncInfo
->getVarArgsGPRSize() > 0
5137 ? FuncInfo
->getVarArgsGPRIndex()
5138 : FuncInfo
->getVarArgsStackIndex(),
5139 getPointerTy(DAG
.getDataLayout()));
5140 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5141 return DAG
.getStore(Op
.getOperand(0), DL
, FR
, Op
.getOperand(1),
5142 MachinePointerInfo(SV
));
5145 SDValue
AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op
,
5146 SelectionDAG
&DAG
) const {
5147 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5148 // Standard, section B.3.
5149 MachineFunction
&MF
= DAG
.getMachineFunction();
5150 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
5151 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
5154 SDValue Chain
= Op
.getOperand(0);
5155 SDValue VAList
= Op
.getOperand(1);
5156 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5157 SmallVector
<SDValue
, 4> MemOps
;
5159 // void *__stack at offset 0
5160 SDValue Stack
= DAG
.getFrameIndex(FuncInfo
->getVarArgsStackIndex(), PtrVT
);
5161 MemOps
.push_back(DAG
.getStore(Chain
, DL
, Stack
, VAList
,
5162 MachinePointerInfo(SV
), /* Alignment = */ 8));
5164 // void *__gr_top at offset 8
5165 int GPRSize
= FuncInfo
->getVarArgsGPRSize();
5167 SDValue GRTop
, GRTopAddr
;
5170 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(8, DL
, PtrVT
));
5172 GRTop
= DAG
.getFrameIndex(FuncInfo
->getVarArgsGPRIndex(), PtrVT
);
5173 GRTop
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, GRTop
,
5174 DAG
.getConstant(GPRSize
, DL
, PtrVT
));
5176 MemOps
.push_back(DAG
.getStore(Chain
, DL
, GRTop
, GRTopAddr
,
5177 MachinePointerInfo(SV
, 8),
5178 /* Alignment = */ 8));
5181 // void *__vr_top at offset 16
5182 int FPRSize
= FuncInfo
->getVarArgsFPRSize();
5184 SDValue VRTop
, VRTopAddr
;
5185 VRTopAddr
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5186 DAG
.getConstant(16, DL
, PtrVT
));
5188 VRTop
= DAG
.getFrameIndex(FuncInfo
->getVarArgsFPRIndex(), PtrVT
);
5189 VRTop
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VRTop
,
5190 DAG
.getConstant(FPRSize
, DL
, PtrVT
));
5192 MemOps
.push_back(DAG
.getStore(Chain
, DL
, VRTop
, VRTopAddr
,
5193 MachinePointerInfo(SV
, 16),
5194 /* Alignment = */ 8));
5197 // int __gr_offs at offset 24
5198 SDValue GROffsAddr
=
5199 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(24, DL
, PtrVT
));
5200 MemOps
.push_back(DAG
.getStore(
5201 Chain
, DL
, DAG
.getConstant(-GPRSize
, DL
, MVT::i32
), GROffsAddr
,
5202 MachinePointerInfo(SV
, 24), /* Alignment = */ 4));
5204 // int __vr_offs at offset 28
5205 SDValue VROffsAddr
=
5206 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(28, DL
, PtrVT
));
5207 MemOps
.push_back(DAG
.getStore(
5208 Chain
, DL
, DAG
.getConstant(-FPRSize
, DL
, MVT::i32
), VROffsAddr
,
5209 MachinePointerInfo(SV
, 28), /* Alignment = */ 4));
5211 return DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOps
);
5214 SDValue
AArch64TargetLowering::LowerVASTART(SDValue Op
,
5215 SelectionDAG
&DAG
) const {
5216 MachineFunction
&MF
= DAG
.getMachineFunction();
5218 if (Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv()))
5219 return LowerWin64_VASTART(Op
, DAG
);
5220 else if (Subtarget
->isTargetDarwin())
5221 return LowerDarwin_VASTART(Op
, DAG
);
5223 return LowerAAPCS_VASTART(Op
, DAG
);
5226 SDValue
AArch64TargetLowering::LowerVACOPY(SDValue Op
,
5227 SelectionDAG
&DAG
) const {
5228 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5231 unsigned VaListSize
=
5232 Subtarget
->isTargetDarwin() || Subtarget
->isTargetWindows() ? 8 : 32;
5233 const Value
*DestSV
= cast
<SrcValueSDNode
>(Op
.getOperand(3))->getValue();
5234 const Value
*SrcSV
= cast
<SrcValueSDNode
>(Op
.getOperand(4))->getValue();
5236 return DAG
.getMemcpy(Op
.getOperand(0), DL
, Op
.getOperand(1),
5238 DAG
.getConstant(VaListSize
, DL
, MVT::i32
),
5239 8, false, false, false, MachinePointerInfo(DestSV
),
5240 MachinePointerInfo(SrcSV
));
5243 SDValue
AArch64TargetLowering::LowerVAARG(SDValue Op
, SelectionDAG
&DAG
) const {
5244 assert(Subtarget
->isTargetDarwin() &&
5245 "automatic va_arg instruction only works on Darwin");
5247 const Value
*V
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5248 EVT VT
= Op
.getValueType();
5250 SDValue Chain
= Op
.getOperand(0);
5251 SDValue Addr
= Op
.getOperand(1);
5252 unsigned Align
= Op
.getConstantOperandVal(3);
5253 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
5255 SDValue VAList
= DAG
.getLoad(PtrVT
, DL
, Chain
, Addr
, MachinePointerInfo(V
));
5256 Chain
= VAList
.getValue(1);
5259 assert(((Align
& (Align
- 1)) == 0) && "Expected Align to be a power of 2");
5260 VAList
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5261 DAG
.getConstant(Align
- 1, DL
, PtrVT
));
5262 VAList
= DAG
.getNode(ISD::AND
, DL
, PtrVT
, VAList
,
5263 DAG
.getConstant(-(int64_t)Align
, DL
, PtrVT
));
5266 Type
*ArgTy
= VT
.getTypeForEVT(*DAG
.getContext());
5267 uint64_t ArgSize
= DAG
.getDataLayout().getTypeAllocSize(ArgTy
);
5269 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5270 // up to 64 bits. At the very least, we have to increase the striding of the
5271 // vaargs list to match this, and for FP values we need to introduce
5272 // FP_ROUND nodes as well.
5273 if (VT
.isInteger() && !VT
.isVector())
5275 bool NeedFPTrunc
= false;
5276 if (VT
.isFloatingPoint() && !VT
.isVector() && VT
!= MVT::f64
) {
5281 // Increment the pointer, VAList, to the next vaarg
5282 SDValue VANext
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5283 DAG
.getConstant(ArgSize
, DL
, PtrVT
));
5284 // Store the incremented VAList to the legalized pointer
5286 DAG
.getStore(Chain
, DL
, VANext
, Addr
, MachinePointerInfo(V
));
5288 // Load the actual argument out of the pointer VAList
5290 // Load the value as an f64.
5292 DAG
.getLoad(MVT::f64
, DL
, APStore
, VAList
, MachinePointerInfo());
5293 // Round the value down to an f32.
5294 SDValue NarrowFP
= DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, WideFP
.getValue(0),
5295 DAG
.getIntPtrConstant(1, DL
));
5296 SDValue Ops
[] = { NarrowFP
, WideFP
.getValue(1) };
5297 // Merge the rounded value with the chain output of the load.
5298 return DAG
.getMergeValues(Ops
, DL
);
5301 return DAG
.getLoad(VT
, DL
, APStore
, VAList
, MachinePointerInfo());
5304 SDValue
AArch64TargetLowering::LowerFRAMEADDR(SDValue Op
,
5305 SelectionDAG
&DAG
) const {
5306 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
5307 MFI
.setFrameAddressIsTaken(true);
5309 EVT VT
= Op
.getValueType();
5311 unsigned Depth
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
5313 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, AArch64::FP
, VT
);
5315 FrameAddr
= DAG
.getLoad(VT
, DL
, DAG
.getEntryNode(), FrameAddr
,
5316 MachinePointerInfo());
5320 SDValue
AArch64TargetLowering::LowerSPONENTRY(SDValue Op
,
5321 SelectionDAG
&DAG
) const {
5322 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
5324 EVT VT
= getPointerTy(DAG
.getDataLayout());
5326 int FI
= MFI
.CreateFixedObject(4, 0, false);
5327 return DAG
.getFrameIndex(FI
, VT
);
5330 #define GET_REGISTER_MATCHER
5331 #include "AArch64GenAsmMatcher.inc"
5333 // FIXME? Maybe this could be a TableGen attribute on some registers and
5334 // this table could be generated automatically from RegInfo.
5335 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName
, EVT VT
,
5336 SelectionDAG
&DAG
) const {
5337 unsigned Reg
= MatchRegisterName(RegName
);
5338 if (AArch64::X1
<= Reg
&& Reg
<= AArch64::X28
) {
5339 const MCRegisterInfo
*MRI
= Subtarget
->getRegisterInfo();
5340 unsigned DwarfRegNum
= MRI
->getDwarfRegNum(Reg
, false);
5341 if (!Subtarget
->isXRegisterReserved(DwarfRegNum
))
5346 report_fatal_error(Twine("Invalid register name \""
5347 + StringRef(RegName
) + "\"."));
5350 SDValue
AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op
,
5351 SelectionDAG
&DAG
) const {
5352 DAG
.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5354 EVT VT
= Op
.getValueType();
5358 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, AArch64::FP
, VT
);
5359 SDValue Offset
= DAG
.getConstant(8, DL
, getPointerTy(DAG
.getDataLayout()));
5361 return DAG
.getNode(ISD::ADD
, DL
, VT
, FrameAddr
, Offset
);
5364 SDValue
AArch64TargetLowering::LowerRETURNADDR(SDValue Op
,
5365 SelectionDAG
&DAG
) const {
5366 MachineFunction
&MF
= DAG
.getMachineFunction();
5367 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
5368 MFI
.setReturnAddressIsTaken(true);
5370 EVT VT
= Op
.getValueType();
5372 unsigned Depth
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
5374 SDValue FrameAddr
= LowerFRAMEADDR(Op
, DAG
);
5375 SDValue Offset
= DAG
.getConstant(8, DL
, getPointerTy(DAG
.getDataLayout()));
5376 return DAG
.getLoad(VT
, DL
, DAG
.getEntryNode(),
5377 DAG
.getNode(ISD::ADD
, DL
, VT
, FrameAddr
, Offset
),
5378 MachinePointerInfo());
5381 // Return LR, which contains the return address. Mark it an implicit live-in.
5382 unsigned Reg
= MF
.addLiveIn(AArch64::LR
, &AArch64::GPR64RegClass
);
5383 return DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, Reg
, VT
);
5386 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5387 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5388 SDValue
AArch64TargetLowering::LowerShiftRightParts(SDValue Op
,
5389 SelectionDAG
&DAG
) const {
5390 assert(Op
.getNumOperands() == 3 && "Not a double-shift!");
5391 EVT VT
= Op
.getValueType();
5392 unsigned VTBits
= VT
.getSizeInBits();
5394 SDValue ShOpLo
= Op
.getOperand(0);
5395 SDValue ShOpHi
= Op
.getOperand(1);
5396 SDValue ShAmt
= Op
.getOperand(2);
5397 unsigned Opc
= (Op
.getOpcode() == ISD::SRA_PARTS
) ? ISD::SRA
: ISD::SRL
;
5399 assert(Op
.getOpcode() == ISD::SRA_PARTS
|| Op
.getOpcode() == ISD::SRL_PARTS
);
5401 SDValue RevShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
,
5402 DAG
.getConstant(VTBits
, dl
, MVT::i64
), ShAmt
);
5403 SDValue HiBitsForLo
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpHi
, RevShAmt
);
5405 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5406 // is "undef". We wanted 0, so CSEL it directly.
5407 SDValue Cmp
= emitComparison(ShAmt
, DAG
.getConstant(0, dl
, MVT::i64
),
5408 ISD::SETEQ
, dl
, DAG
);
5409 SDValue CCVal
= DAG
.getConstant(AArch64CC::EQ
, dl
, MVT::i32
);
5411 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, DAG
.getConstant(0, dl
, MVT::i64
),
5412 HiBitsForLo
, CCVal
, Cmp
);
5414 SDValue ExtraShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, ShAmt
,
5415 DAG
.getConstant(VTBits
, dl
, MVT::i64
));
5417 SDValue LoBitsForLo
= DAG
.getNode(ISD::SRL
, dl
, VT
, ShOpLo
, ShAmt
);
5418 SDValue LoForNormalShift
=
5419 DAG
.getNode(ISD::OR
, dl
, VT
, LoBitsForLo
, HiBitsForLo
);
5421 Cmp
= emitComparison(ExtraShAmt
, DAG
.getConstant(0, dl
, MVT::i64
), ISD::SETGE
,
5423 CCVal
= DAG
.getConstant(AArch64CC::GE
, dl
, MVT::i32
);
5424 SDValue LoForBigShift
= DAG
.getNode(Opc
, dl
, VT
, ShOpHi
, ExtraShAmt
);
5425 SDValue Lo
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, LoForBigShift
,
5426 LoForNormalShift
, CCVal
, Cmp
);
5428 // AArch64 shifts larger than the register width are wrapped rather than
5429 // clamped, so we can't just emit "hi >> x".
5430 SDValue HiForNormalShift
= DAG
.getNode(Opc
, dl
, VT
, ShOpHi
, ShAmt
);
5431 SDValue HiForBigShift
=
5433 ? DAG
.getNode(Opc
, dl
, VT
, ShOpHi
,
5434 DAG
.getConstant(VTBits
- 1, dl
, MVT::i64
))
5435 : DAG
.getConstant(0, dl
, VT
);
5436 SDValue Hi
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, HiForBigShift
,
5437 HiForNormalShift
, CCVal
, Cmp
);
5439 SDValue Ops
[2] = { Lo
, Hi
};
5440 return DAG
.getMergeValues(Ops
, dl
);
5443 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5444 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5445 SDValue
AArch64TargetLowering::LowerShiftLeftParts(SDValue Op
,
5446 SelectionDAG
&DAG
) const {
5447 assert(Op
.getNumOperands() == 3 && "Not a double-shift!");
5448 EVT VT
= Op
.getValueType();
5449 unsigned VTBits
= VT
.getSizeInBits();
5451 SDValue ShOpLo
= Op
.getOperand(0);
5452 SDValue ShOpHi
= Op
.getOperand(1);
5453 SDValue ShAmt
= Op
.getOperand(2);
5455 assert(Op
.getOpcode() == ISD::SHL_PARTS
);
5456 SDValue RevShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
,
5457 DAG
.getConstant(VTBits
, dl
, MVT::i64
), ShAmt
);
5458 SDValue LoBitsForHi
= DAG
.getNode(ISD::SRL
, dl
, VT
, ShOpLo
, RevShAmt
);
5460 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5461 // is "undef". We wanted 0, so CSEL it directly.
5462 SDValue Cmp
= emitComparison(ShAmt
, DAG
.getConstant(0, dl
, MVT::i64
),
5463 ISD::SETEQ
, dl
, DAG
);
5464 SDValue CCVal
= DAG
.getConstant(AArch64CC::EQ
, dl
, MVT::i32
);
5466 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, DAG
.getConstant(0, dl
, MVT::i64
),
5467 LoBitsForHi
, CCVal
, Cmp
);
5469 SDValue ExtraShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, ShAmt
,
5470 DAG
.getConstant(VTBits
, dl
, MVT::i64
));
5471 SDValue HiBitsForHi
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpHi
, ShAmt
);
5472 SDValue HiForNormalShift
=
5473 DAG
.getNode(ISD::OR
, dl
, VT
, LoBitsForHi
, HiBitsForHi
);
5475 SDValue HiForBigShift
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpLo
, ExtraShAmt
);
5477 Cmp
= emitComparison(ExtraShAmt
, DAG
.getConstant(0, dl
, MVT::i64
), ISD::SETGE
,
5479 CCVal
= DAG
.getConstant(AArch64CC::GE
, dl
, MVT::i32
);
5480 SDValue Hi
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, HiForBigShift
,
5481 HiForNormalShift
, CCVal
, Cmp
);
5483 // AArch64 shifts of larger than register sizes are wrapped rather than
5484 // clamped, so we can't just emit "lo << a" if a is too big.
5485 SDValue LoForBigShift
= DAG
.getConstant(0, dl
, VT
);
5486 SDValue LoForNormalShift
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpLo
, ShAmt
);
5487 SDValue Lo
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, LoForBigShift
,
5488 LoForNormalShift
, CCVal
, Cmp
);
5490 SDValue Ops
[2] = { Lo
, Hi
};
5491 return DAG
.getMergeValues(Ops
, dl
);
5494 bool AArch64TargetLowering::isOffsetFoldingLegal(
5495 const GlobalAddressSDNode
*GA
) const {
5496 // Offsets are folded in the DAG combine rather than here so that we can
5497 // intelligently choose an offset based on the uses.
5501 bool AArch64TargetLowering::isFPImmLegal(const APFloat
&Imm
, EVT VT
,
5502 bool OptForSize
) const {
5503 bool IsLegal
= false;
5504 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5505 // 16-bit case when target has full fp16 support.
5506 // FIXME: We should be able to handle f128 as well with a clever lowering.
5507 const APInt ImmInt
= Imm
.bitcastToAPInt();
5509 IsLegal
= AArch64_AM::getFP64Imm(ImmInt
) != -1 || Imm
.isPosZero();
5510 else if (VT
== MVT::f32
)
5511 IsLegal
= AArch64_AM::getFP32Imm(ImmInt
) != -1 || Imm
.isPosZero();
5512 else if (VT
== MVT::f16
&& Subtarget
->hasFullFP16())
5513 IsLegal
= AArch64_AM::getFP16Imm(ImmInt
) != -1 || Imm
.isPosZero();
5514 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5515 // generate that fmov.
5517 // If we can not materialize in immediate field for fmov, check if the
5518 // value can be encoded as the immediate operand of a logical instruction.
5519 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5520 if (!IsLegal
&& (VT
== MVT::f64
|| VT
== MVT::f32
)) {
5521 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5522 // however the mov+fmov sequence is always better because of the reduced
5523 // cache pressure. The timings are still the same if you consider
5524 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5525 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5526 SmallVector
<AArch64_IMM::ImmInsnModel
, 4> Insn
;
5527 AArch64_IMM::expandMOVImm(ImmInt
.getZExtValue(), VT
.getSizeInBits(),
5529 unsigned Limit
= (OptForSize
? 1 : (Subtarget
->hasFuseLiterals() ? 5 : 2));
5530 IsLegal
= Insn
.size() <= Limit
;
5533 LLVM_DEBUG(dbgs() << (IsLegal
? "Legal " : "Illegal ") << VT
.getEVTString()
5534 << " imm value: "; Imm
.dump(););
5538 //===----------------------------------------------------------------------===//
5539 // AArch64 Optimization Hooks
5540 //===----------------------------------------------------------------------===//
5542 static SDValue
getEstimate(const AArch64Subtarget
*ST
, unsigned Opcode
,
5543 SDValue Operand
, SelectionDAG
&DAG
,
5545 EVT VT
= Operand
.getValueType();
5546 if (ST
->hasNEON() &&
5547 (VT
== MVT::f64
|| VT
== MVT::v1f64
|| VT
== MVT::v2f64
||
5548 VT
== MVT::f32
|| VT
== MVT::v1f32
||
5549 VT
== MVT::v2f32
|| VT
== MVT::v4f32
)) {
5550 if (ExtraSteps
== TargetLoweringBase::ReciprocalEstimate::Unspecified
)
5551 // For the reciprocal estimates, convergence is quadratic, so the number
5552 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5553 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5554 // the result for float (23 mantissa bits) is 2 and for double (52
5555 // mantissa bits) is 3.
5556 ExtraSteps
= VT
.getScalarType() == MVT::f64
? 3 : 2;
5558 return DAG
.getNode(Opcode
, SDLoc(Operand
), VT
, Operand
);
5564 SDValue
AArch64TargetLowering::getSqrtEstimate(SDValue Operand
,
5565 SelectionDAG
&DAG
, int Enabled
,
5568 bool Reciprocal
) const {
5569 if (Enabled
== ReciprocalEstimate::Enabled
||
5570 (Enabled
== ReciprocalEstimate::Unspecified
&& Subtarget
->useRSqrt()))
5571 if (SDValue Estimate
= getEstimate(Subtarget
, AArch64ISD::FRSQRTE
, Operand
,
5574 EVT VT
= Operand
.getValueType();
5577 Flags
.setAllowReassociation(true);
5579 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5580 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5581 for (int i
= ExtraSteps
; i
> 0; --i
) {
5582 SDValue Step
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Estimate
,
5584 Step
= DAG
.getNode(AArch64ISD::FRSQRTS
, DL
, VT
, Operand
, Step
, Flags
);
5585 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Step
, Flags
);
5588 EVT CCVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(),
5590 SDValue FPZero
= DAG
.getConstantFP(0.0, DL
, VT
);
5591 SDValue Eq
= DAG
.getSetCC(DL
, CCVT
, Operand
, FPZero
, ISD::SETEQ
);
5593 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Operand
, Estimate
, Flags
);
5594 // Correct the result if the operand is 0.0.
5595 Estimate
= DAG
.getNode(VT
.isVector() ? ISD::VSELECT
: ISD::SELECT
, DL
,
5596 VT
, Eq
, Operand
, Estimate
);
5606 SDValue
AArch64TargetLowering::getRecipEstimate(SDValue Operand
,
5607 SelectionDAG
&DAG
, int Enabled
,
5608 int &ExtraSteps
) const {
5609 if (Enabled
== ReciprocalEstimate::Enabled
)
5610 if (SDValue Estimate
= getEstimate(Subtarget
, AArch64ISD::FRECPE
, Operand
,
5613 EVT VT
= Operand
.getValueType();
5616 Flags
.setAllowReassociation(true);
5618 // Newton reciprocal iteration: E * (2 - X * E)
5619 // AArch64 reciprocal iteration instruction: (2 - M * N)
5620 for (int i
= ExtraSteps
; i
> 0; --i
) {
5621 SDValue Step
= DAG
.getNode(AArch64ISD::FRECPS
, DL
, VT
, Operand
,
5623 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Step
, Flags
);
5633 //===----------------------------------------------------------------------===//
5634 // AArch64 Inline Assembly Support
5635 //===----------------------------------------------------------------------===//
5637 // Table of Constraints
5638 // TODO: This is the current set of constraints supported by ARM for the
5639 // compiler, not all of them may make sense.
5641 // r - A general register
5642 // w - An FP/SIMD register of some size in the range v0-v31
5643 // x - An FP/SIMD register of some size in the range v0-v15
5644 // I - Constant that can be used with an ADD instruction
5645 // J - Constant that can be used with a SUB instruction
5646 // K - Constant that can be used with a 32-bit logical instruction
5647 // L - Constant that can be used with a 64-bit logical instruction
5648 // M - Constant that can be used as a 32-bit MOV immediate
5649 // N - Constant that can be used as a 64-bit MOV immediate
5650 // Q - A memory reference with base register and no offset
5651 // S - A symbolic address
5652 // Y - Floating point constant zero
5653 // Z - Integer constant zero
5655 // Note that general register operands will be output using their 64-bit x
5656 // register name, whatever the size of the variable, unless the asm operand
5657 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5658 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5660 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT
) const {
5661 // At this point, we have to lower this constraint to something else, so we
5662 // lower it to an "r" or "w". However, by doing this we will force the result
5663 // to be in register, while the X constraint is much more permissive.
5665 // Although we are correct (we are free to emit anything, without
5666 // constraints), we might break use cases that would expect us to be more
5667 // efficient and emit something else.
5668 if (!Subtarget
->hasFPARMv8())
5671 if (ConstraintVT
.isFloatingPoint())
5674 if (ConstraintVT
.isVector() &&
5675 (ConstraintVT
.getSizeInBits() == 64 ||
5676 ConstraintVT
.getSizeInBits() == 128))
5682 /// getConstraintType - Given a constraint letter, return the type of
5683 /// constraint it is for this target.
5684 AArch64TargetLowering::ConstraintType
5685 AArch64TargetLowering::getConstraintType(StringRef Constraint
) const {
5686 if (Constraint
.size() == 1) {
5687 switch (Constraint
[0]) {
5694 return C_RegisterClass
;
5695 // An address with a single base register. Due to the way we
5696 // currently handle addresses it is the same as 'r'.
5699 case 'S': // A symbolic address
5703 return TargetLowering::getConstraintType(Constraint
);
5706 /// Examine constraint type and operand type and determine a weight value.
5707 /// This object must already have been set up with the operand type
5708 /// and the current alternative constraint selected.
5709 TargetLowering::ConstraintWeight
5710 AArch64TargetLowering::getSingleConstraintMatchWeight(
5711 AsmOperandInfo
&info
, const char *constraint
) const {
5712 ConstraintWeight weight
= CW_Invalid
;
5713 Value
*CallOperandVal
= info
.CallOperandVal
;
5714 // If we don't have a value, we can't do a match,
5715 // but allow it at the lowest weight.
5716 if (!CallOperandVal
)
5718 Type
*type
= CallOperandVal
->getType();
5719 // Look at the constraint type.
5720 switch (*constraint
) {
5722 weight
= TargetLowering::getSingleConstraintMatchWeight(info
, constraint
);
5726 if (type
->isFloatingPointTy() || type
->isVectorTy())
5727 weight
= CW_Register
;
5730 weight
= CW_Constant
;
5736 std::pair
<unsigned, const TargetRegisterClass
*>
5737 AArch64TargetLowering::getRegForInlineAsmConstraint(
5738 const TargetRegisterInfo
*TRI
, StringRef Constraint
, MVT VT
) const {
5739 if (Constraint
.size() == 1) {
5740 switch (Constraint
[0]) {
5742 if (VT
.getSizeInBits() == 64)
5743 return std::make_pair(0U, &AArch64::GPR64commonRegClass
);
5744 return std::make_pair(0U, &AArch64::GPR32commonRegClass
);
5746 if (!Subtarget
->hasFPARMv8())
5748 if (VT
.getSizeInBits() == 16)
5749 return std::make_pair(0U, &AArch64::FPR16RegClass
);
5750 if (VT
.getSizeInBits() == 32)
5751 return std::make_pair(0U, &AArch64::FPR32RegClass
);
5752 if (VT
.getSizeInBits() == 64)
5753 return std::make_pair(0U, &AArch64::FPR64RegClass
);
5754 if (VT
.getSizeInBits() == 128)
5755 return std::make_pair(0U, &AArch64::FPR128RegClass
);
5757 // The instructions that this constraint is designed for can
5758 // only take 128-bit registers so just use that regclass.
5760 if (!Subtarget
->hasFPARMv8())
5762 if (VT
.getSizeInBits() == 128)
5763 return std::make_pair(0U, &AArch64::FPR128_loRegClass
);
5767 if (StringRef("{cc}").equals_lower(Constraint
))
5768 return std::make_pair(unsigned(AArch64::NZCV
), &AArch64::CCRRegClass
);
5770 // Use the default implementation in TargetLowering to convert the register
5771 // constraint into a member of a register class.
5772 std::pair
<unsigned, const TargetRegisterClass
*> Res
;
5773 Res
= TargetLowering::getRegForInlineAsmConstraint(TRI
, Constraint
, VT
);
5775 // Not found as a standard register?
5777 unsigned Size
= Constraint
.size();
5778 if ((Size
== 4 || Size
== 5) && Constraint
[0] == '{' &&
5779 tolower(Constraint
[1]) == 'v' && Constraint
[Size
- 1] == '}') {
5781 bool Failed
= Constraint
.slice(2, Size
- 1).getAsInteger(10, RegNo
);
5782 if (!Failed
&& RegNo
>= 0 && RegNo
<= 31) {
5783 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5784 // By default we'll emit v0-v31 for this unless there's a modifier where
5785 // we'll emit the correct register as well.
5786 if (VT
!= MVT::Other
&& VT
.getSizeInBits() == 64) {
5787 Res
.first
= AArch64::FPR64RegClass
.getRegister(RegNo
);
5788 Res
.second
= &AArch64::FPR64RegClass
;
5790 Res
.first
= AArch64::FPR128RegClass
.getRegister(RegNo
);
5791 Res
.second
= &AArch64::FPR128RegClass
;
5797 if (Res
.second
&& !Subtarget
->hasFPARMv8() &&
5798 !AArch64::GPR32allRegClass
.hasSubClassEq(Res
.second
) &&
5799 !AArch64::GPR64allRegClass
.hasSubClassEq(Res
.second
))
5800 return std::make_pair(0U, nullptr);
5805 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5806 /// vector. If it is invalid, don't add anything to Ops.
5807 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5808 SDValue Op
, std::string
&Constraint
, std::vector
<SDValue
> &Ops
,
5809 SelectionDAG
&DAG
) const {
5812 // Currently only support length 1 constraints.
5813 if (Constraint
.length() != 1)
5816 char ConstraintLetter
= Constraint
[0];
5817 switch (ConstraintLetter
) {
5821 // This set of constraints deal with valid constants for various instructions.
5822 // Validate and return a target constant for them if we can.
5824 // 'z' maps to xzr or wzr so it needs an input of 0.
5825 if (!isNullConstant(Op
))
5828 if (Op
.getValueType() == MVT::i64
)
5829 Result
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
5831 Result
= DAG
.getRegister(AArch64::WZR
, MVT::i32
);
5835 // An absolute symbolic address or label reference.
5836 if (const GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(Op
)) {
5837 Result
= DAG
.getTargetGlobalAddress(GA
->getGlobal(), SDLoc(Op
),
5838 GA
->getValueType(0));
5839 } else if (const BlockAddressSDNode
*BA
=
5840 dyn_cast
<BlockAddressSDNode
>(Op
)) {
5842 DAG
.getTargetBlockAddress(BA
->getBlockAddress(), BA
->getValueType(0));
5843 } else if (const ExternalSymbolSDNode
*ES
=
5844 dyn_cast
<ExternalSymbolSDNode
>(Op
)) {
5846 DAG
.getTargetExternalSymbol(ES
->getSymbol(), ES
->getValueType(0));
5858 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
);
5862 // Grab the value and do some validation.
5863 uint64_t CVal
= C
->getZExtValue();
5864 switch (ConstraintLetter
) {
5865 // The I constraint applies only to simple ADD or SUB immediate operands:
5866 // i.e. 0 to 4095 with optional shift by 12
5867 // The J constraint applies only to ADD or SUB immediates that would be
5868 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5869 // instruction [or vice versa], in other words -1 to -4095 with optional
5870 // left shift by 12.
5872 if (isUInt
<12>(CVal
) || isShiftedUInt
<12, 12>(CVal
))
5876 uint64_t NVal
= -C
->getSExtValue();
5877 if (isUInt
<12>(NVal
) || isShiftedUInt
<12, 12>(NVal
)) {
5878 CVal
= C
->getSExtValue();
5883 // The K and L constraints apply *only* to logical immediates, including
5884 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5885 // been removed and MOV should be used). So these constraints have to
5886 // distinguish between bit patterns that are valid 32-bit or 64-bit
5887 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5888 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5891 if (AArch64_AM::isLogicalImmediate(CVal
, 32))
5895 if (AArch64_AM::isLogicalImmediate(CVal
, 64))
5898 // The M and N constraints are a superset of K and L respectively, for use
5899 // with the MOV (immediate) alias. As well as the logical immediates they
5900 // also match 32 or 64-bit immediates that can be loaded either using a
5901 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5902 // (M) or 64-bit 0x1234000000000000 (N) etc.
5903 // As a note some of this code is liberally stolen from the asm parser.
5905 if (!isUInt
<32>(CVal
))
5907 if (AArch64_AM::isLogicalImmediate(CVal
, 32))
5909 if ((CVal
& 0xFFFF) == CVal
)
5911 if ((CVal
& 0xFFFF0000ULL
) == CVal
)
5913 uint64_t NCVal
= ~(uint32_t)CVal
;
5914 if ((NCVal
& 0xFFFFULL
) == NCVal
)
5916 if ((NCVal
& 0xFFFF0000ULL
) == NCVal
)
5921 if (AArch64_AM::isLogicalImmediate(CVal
, 64))
5923 if ((CVal
& 0xFFFFULL
) == CVal
)
5925 if ((CVal
& 0xFFFF0000ULL
) == CVal
)
5927 if ((CVal
& 0xFFFF00000000ULL
) == CVal
)
5929 if ((CVal
& 0xFFFF000000000000ULL
) == CVal
)
5931 uint64_t NCVal
= ~CVal
;
5932 if ((NCVal
& 0xFFFFULL
) == NCVal
)
5934 if ((NCVal
& 0xFFFF0000ULL
) == NCVal
)
5936 if ((NCVal
& 0xFFFF00000000ULL
) == NCVal
)
5938 if ((NCVal
& 0xFFFF000000000000ULL
) == NCVal
)
5946 // All assembler immediates are 64-bit integers.
5947 Result
= DAG
.getTargetConstant(CVal
, SDLoc(Op
), MVT::i64
);
5951 if (Result
.getNode()) {
5952 Ops
.push_back(Result
);
5956 return TargetLowering::LowerAsmOperandForConstraint(Op
, Constraint
, Ops
, DAG
);
5959 //===----------------------------------------------------------------------===//
5960 // AArch64 Advanced SIMD Support
5961 //===----------------------------------------------------------------------===//
5963 /// WidenVector - Given a value in the V64 register class, produce the
5964 /// equivalent value in the V128 register class.
5965 static SDValue
WidenVector(SDValue V64Reg
, SelectionDAG
&DAG
) {
5966 EVT VT
= V64Reg
.getValueType();
5967 unsigned NarrowSize
= VT
.getVectorNumElements();
5968 MVT EltTy
= VT
.getVectorElementType().getSimpleVT();
5969 MVT WideTy
= MVT::getVectorVT(EltTy
, 2 * NarrowSize
);
5972 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, WideTy
, DAG
.getUNDEF(WideTy
),
5973 V64Reg
, DAG
.getConstant(0, DL
, MVT::i32
));
5976 /// getExtFactor - Determine the adjustment factor for the position when
5977 /// generating an "extract from vector registers" instruction.
5978 static unsigned getExtFactor(SDValue
&V
) {
5979 EVT EltType
= V
.getValueType().getVectorElementType();
5980 return EltType
.getSizeInBits() / 8;
5983 /// NarrowVector - Given a value in the V128 register class, produce the
5984 /// equivalent value in the V64 register class.
5985 static SDValue
NarrowVector(SDValue V128Reg
, SelectionDAG
&DAG
) {
5986 EVT VT
= V128Reg
.getValueType();
5987 unsigned WideSize
= VT
.getVectorNumElements();
5988 MVT EltTy
= VT
.getVectorElementType().getSimpleVT();
5989 MVT NarrowTy
= MVT::getVectorVT(EltTy
, WideSize
/ 2);
5992 return DAG
.getTargetExtractSubreg(AArch64::dsub
, DL
, NarrowTy
, V128Reg
);
5995 // Gather data to see if the operation can be modelled as a
5996 // shuffle in combination with VEXTs.
5997 SDValue
AArch64TargetLowering::ReconstructShuffle(SDValue Op
,
5998 SelectionDAG
&DAG
) const {
5999 assert(Op
.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!");
6000 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6002 EVT VT
= Op
.getValueType();
6003 unsigned NumElts
= VT
.getVectorNumElements();
6005 struct ShuffleSourceInfo
{
6010 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6011 // be compatible with the shuffle we intend to construct. As a result
6012 // ShuffleVec will be some sliding window into the original Vec.
6015 // Code should guarantee that element i in Vec starts at element "WindowBase
6016 // + i * WindowScale in ShuffleVec".
6020 ShuffleSourceInfo(SDValue Vec
)
6021 : Vec(Vec
), MinElt(std::numeric_limits
<unsigned>::max()), MaxElt(0),
6022 ShuffleVec(Vec
), WindowBase(0), WindowScale(1) {}
6024 bool operator ==(SDValue OtherVec
) { return Vec
== OtherVec
; }
6027 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6029 SmallVector
<ShuffleSourceInfo
, 2> Sources
;
6030 for (unsigned i
= 0; i
< NumElts
; ++i
) {
6031 SDValue V
= Op
.getOperand(i
);
6034 else if (V
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
6035 !isa
<ConstantSDNode
>(V
.getOperand(1))) {
6037 dbgs() << "Reshuffle failed: "
6038 "a shuffle can only come from building a vector from "
6039 "various elements of other vectors, provided their "
6040 "indices are constant\n");
6044 // Add this element source to the list if it's not already there.
6045 SDValue SourceVec
= V
.getOperand(0);
6046 auto Source
= find(Sources
, SourceVec
);
6047 if (Source
== Sources
.end())
6048 Source
= Sources
.insert(Sources
.end(), ShuffleSourceInfo(SourceVec
));
6050 // Update the minimum and maximum lane number seen.
6051 unsigned EltNo
= cast
<ConstantSDNode
>(V
.getOperand(1))->getZExtValue();
6052 Source
->MinElt
= std::min(Source
->MinElt
, EltNo
);
6053 Source
->MaxElt
= std::max(Source
->MaxElt
, EltNo
);
6056 if (Sources
.size() > 2) {
6058 dbgs() << "Reshuffle failed: currently only do something sane when at "
6059 "most two source vectors are involved\n");
6063 // Find out the smallest element size among result and two sources, and use
6064 // it as element size to build the shuffle_vector.
6065 EVT SmallestEltTy
= VT
.getVectorElementType();
6066 for (auto &Source
: Sources
) {
6067 EVT SrcEltTy
= Source
.Vec
.getValueType().getVectorElementType();
6068 if (SrcEltTy
.bitsLT(SmallestEltTy
)) {
6069 SmallestEltTy
= SrcEltTy
;
6072 unsigned ResMultiplier
=
6073 VT
.getScalarSizeInBits() / SmallestEltTy
.getSizeInBits();
6074 NumElts
= VT
.getSizeInBits() / SmallestEltTy
.getSizeInBits();
6075 EVT ShuffleVT
= EVT::getVectorVT(*DAG
.getContext(), SmallestEltTy
, NumElts
);
6077 // If the source vector is too wide or too narrow, we may nevertheless be able
6078 // to construct a compatible shuffle either by concatenating it with UNDEF or
6079 // extracting a suitable range of elements.
6080 for (auto &Src
: Sources
) {
6081 EVT SrcVT
= Src
.ShuffleVec
.getValueType();
6083 if (SrcVT
.getSizeInBits() == VT
.getSizeInBits())
6086 // This stage of the search produces a source with the same element type as
6087 // the original, but with a total width matching the BUILD_VECTOR output.
6088 EVT EltVT
= SrcVT
.getVectorElementType();
6089 unsigned NumSrcElts
= VT
.getSizeInBits() / EltVT
.getSizeInBits();
6090 EVT DestVT
= EVT::getVectorVT(*DAG
.getContext(), EltVT
, NumSrcElts
);
6092 if (SrcVT
.getSizeInBits() < VT
.getSizeInBits()) {
6093 assert(2 * SrcVT
.getSizeInBits() == VT
.getSizeInBits());
6094 // We can pad out the smaller vector for free, so if it's part of a
6097 DAG
.getNode(ISD::CONCAT_VECTORS
, dl
, DestVT
, Src
.ShuffleVec
,
6098 DAG
.getUNDEF(Src
.ShuffleVec
.getValueType()));
6102 assert(SrcVT
.getSizeInBits() == 2 * VT
.getSizeInBits());
6104 if (Src
.MaxElt
- Src
.MinElt
>= NumSrcElts
) {
6106 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6110 if (Src
.MinElt
>= NumSrcElts
) {
6111 // The extraction can just take the second half
6113 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6114 DAG
.getConstant(NumSrcElts
, dl
, MVT::i64
));
6115 Src
.WindowBase
= -NumSrcElts
;
6116 } else if (Src
.MaxElt
< NumSrcElts
) {
6117 // The extraction can just take the first half
6119 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6120 DAG
.getConstant(0, dl
, MVT::i64
));
6122 // An actual VEXT is needed
6124 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6125 DAG
.getConstant(0, dl
, MVT::i64
));
6127 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6128 DAG
.getConstant(NumSrcElts
, dl
, MVT::i64
));
6129 unsigned Imm
= Src
.MinElt
* getExtFactor(VEXTSrc1
);
6131 Src
.ShuffleVec
= DAG
.getNode(AArch64ISD::EXT
, dl
, DestVT
, VEXTSrc1
,
6133 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6134 Src
.WindowBase
= -Src
.MinElt
;
6138 // Another possible incompatibility occurs from the vector element types. We
6139 // can fix this by bitcasting the source vectors to the same type we intend
6141 for (auto &Src
: Sources
) {
6142 EVT SrcEltTy
= Src
.ShuffleVec
.getValueType().getVectorElementType();
6143 if (SrcEltTy
== SmallestEltTy
)
6145 assert(ShuffleVT
.getVectorElementType() == SmallestEltTy
);
6146 Src
.ShuffleVec
= DAG
.getNode(ISD::BITCAST
, dl
, ShuffleVT
, Src
.ShuffleVec
);
6147 Src
.WindowScale
= SrcEltTy
.getSizeInBits() / SmallestEltTy
.getSizeInBits();
6148 Src
.WindowBase
*= Src
.WindowScale
;
6151 // Final sanity check before we try to actually produce a shuffle.
6152 LLVM_DEBUG(for (auto Src
6154 assert(Src
.ShuffleVec
.getValueType() == ShuffleVT
););
6156 // The stars all align, our next step is to produce the mask for the shuffle.
6157 SmallVector
<int, 8> Mask(ShuffleVT
.getVectorNumElements(), -1);
6158 int BitsPerShuffleLane
= ShuffleVT
.getScalarSizeInBits();
6159 for (unsigned i
= 0; i
< VT
.getVectorNumElements(); ++i
) {
6160 SDValue Entry
= Op
.getOperand(i
);
6161 if (Entry
.isUndef())
6164 auto Src
= find(Sources
, Entry
.getOperand(0));
6165 int EltNo
= cast
<ConstantSDNode
>(Entry
.getOperand(1))->getSExtValue();
6167 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6168 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6170 EVT OrigEltTy
= Entry
.getOperand(0).getValueType().getVectorElementType();
6172 std::min(OrigEltTy
.getSizeInBits(), VT
.getScalarSizeInBits());
6173 int LanesDefined
= BitsDefined
/ BitsPerShuffleLane
;
6175 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6176 // starting at the appropriate offset.
6177 int *LaneMask
= &Mask
[i
* ResMultiplier
];
6179 int ExtractBase
= EltNo
* Src
->WindowScale
+ Src
->WindowBase
;
6180 ExtractBase
+= NumElts
* (Src
- Sources
.begin());
6181 for (int j
= 0; j
< LanesDefined
; ++j
)
6182 LaneMask
[j
] = ExtractBase
+ j
;
6185 // Final check before we try to produce nonsense...
6186 if (!isShuffleMaskLegal(Mask
, ShuffleVT
)) {
6187 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6191 SDValue ShuffleOps
[] = { DAG
.getUNDEF(ShuffleVT
), DAG
.getUNDEF(ShuffleVT
) };
6192 for (unsigned i
= 0; i
< Sources
.size(); ++i
)
6193 ShuffleOps
[i
] = Sources
[i
].ShuffleVec
;
6195 SDValue Shuffle
= DAG
.getVectorShuffle(ShuffleVT
, dl
, ShuffleOps
[0],
6196 ShuffleOps
[1], Mask
);
6197 SDValue V
= DAG
.getNode(ISD::BITCAST
, dl
, VT
, Shuffle
);
6199 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle
.dump();
6200 dbgs() << "Reshuffle, creating node: "; V
.dump(););
6205 // check if an EXT instruction can handle the shuffle mask when the
6206 // vector sources of the shuffle are the same.
6207 static bool isSingletonEXTMask(ArrayRef
<int> M
, EVT VT
, unsigned &Imm
) {
6208 unsigned NumElts
= VT
.getVectorNumElements();
6210 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6216 // If this is a VEXT shuffle, the immediate value is the index of the first
6217 // element. The other shuffle indices must be the successive elements after
6219 unsigned ExpectedElt
= Imm
;
6220 for (unsigned i
= 1; i
< NumElts
; ++i
) {
6221 // Increment the expected index. If it wraps around, just follow it
6222 // back to index zero and keep going.
6224 if (ExpectedElt
== NumElts
)
6228 continue; // ignore UNDEF indices
6229 if (ExpectedElt
!= static_cast<unsigned>(M
[i
]))
6236 // check if an EXT instruction can handle the shuffle mask when the
6237 // vector sources of the shuffle are different.
6238 static bool isEXTMask(ArrayRef
<int> M
, EVT VT
, bool &ReverseEXT
,
6240 // Look for the first non-undef element.
6241 const int *FirstRealElt
= find_if(M
, [](int Elt
) { return Elt
>= 0; });
6243 // Benefit form APInt to handle overflow when calculating expected element.
6244 unsigned NumElts
= VT
.getVectorNumElements();
6245 unsigned MaskBits
= APInt(32, NumElts
* 2).logBase2();
6246 APInt ExpectedElt
= APInt(MaskBits
, *FirstRealElt
+ 1);
6247 // The following shuffle indices must be the successive elements after the
6248 // first real element.
6249 const int *FirstWrongElt
= std::find_if(FirstRealElt
+ 1, M
.end(),
6250 [&](int Elt
) {return Elt
!= ExpectedElt
++ && Elt
!= -1;});
6251 if (FirstWrongElt
!= M
.end())
6254 // The index of an EXT is the first element if it is not UNDEF.
6255 // Watch out for the beginning UNDEFs. The EXT index should be the expected
6256 // value of the first element. E.g.
6257 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6258 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6259 // ExpectedElt is the last mask index plus 1.
6260 Imm
= ExpectedElt
.getZExtValue();
6262 // There are two difference cases requiring to reverse input vectors.
6263 // For example, for vector <4 x i32> we have the following cases,
6264 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6265 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6266 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6267 // to reverse two input vectors.
6276 /// isREVMask - Check if a vector shuffle corresponds to a REV
6277 /// instruction with the specified blocksize. (The order of the elements
6278 /// within each block of the vector is reversed.)
6279 static bool isREVMask(ArrayRef
<int> M
, EVT VT
, unsigned BlockSize
) {
6280 assert((BlockSize
== 16 || BlockSize
== 32 || BlockSize
== 64) &&
6281 "Only possible block sizes for REV are: 16, 32, 64");
6283 unsigned EltSz
= VT
.getScalarSizeInBits();
6287 unsigned NumElts
= VT
.getVectorNumElements();
6288 unsigned BlockElts
= M
[0] + 1;
6289 // If the first shuffle index is UNDEF, be optimistic.
6291 BlockElts
= BlockSize
/ EltSz
;
6293 if (BlockSize
<= EltSz
|| BlockSize
!= BlockElts
* EltSz
)
6296 for (unsigned i
= 0; i
< NumElts
; ++i
) {
6298 continue; // ignore UNDEF indices
6299 if ((unsigned)M
[i
] != (i
- i
% BlockElts
) + (BlockElts
- 1 - i
% BlockElts
))
6306 static bool isZIPMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6307 unsigned NumElts
= VT
.getVectorNumElements();
6308 WhichResult
= (M
[0] == 0 ? 0 : 1);
6309 unsigned Idx
= WhichResult
* NumElts
/ 2;
6310 for (unsigned i
= 0; i
!= NumElts
; i
+= 2) {
6311 if ((M
[i
] >= 0 && (unsigned)M
[i
] != Idx
) ||
6312 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != Idx
+ NumElts
))
6320 static bool isUZPMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6321 unsigned NumElts
= VT
.getVectorNumElements();
6322 WhichResult
= (M
[0] == 0 ? 0 : 1);
6323 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
6325 continue; // ignore UNDEF indices
6326 if ((unsigned)M
[i
] != 2 * i
+ WhichResult
)
6333 static bool isTRNMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6334 unsigned NumElts
= VT
.getVectorNumElements();
6335 if (NumElts
% 2 != 0)
6337 WhichResult
= (M
[0] == 0 ? 0 : 1);
6338 for (unsigned i
= 0; i
< NumElts
; i
+= 2) {
6339 if ((M
[i
] >= 0 && (unsigned)M
[i
] != i
+ WhichResult
) ||
6340 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != i
+ NumElts
+ WhichResult
))
6346 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6347 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6348 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6349 static bool isZIP_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6350 unsigned NumElts
= VT
.getVectorNumElements();
6351 if (NumElts
% 2 != 0)
6353 WhichResult
= (M
[0] == 0 ? 0 : 1);
6354 unsigned Idx
= WhichResult
* NumElts
/ 2;
6355 for (unsigned i
= 0; i
!= NumElts
; i
+= 2) {
6356 if ((M
[i
] >= 0 && (unsigned)M
[i
] != Idx
) ||
6357 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != Idx
))
6365 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6366 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6367 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6368 static bool isUZP_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6369 unsigned Half
= VT
.getVectorNumElements() / 2;
6370 WhichResult
= (M
[0] == 0 ? 0 : 1);
6371 for (unsigned j
= 0; j
!= 2; ++j
) {
6372 unsigned Idx
= WhichResult
;
6373 for (unsigned i
= 0; i
!= Half
; ++i
) {
6374 int MIdx
= M
[i
+ j
* Half
];
6375 if (MIdx
>= 0 && (unsigned)MIdx
!= Idx
)
6384 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6385 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6386 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6387 static bool isTRN_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6388 unsigned NumElts
= VT
.getVectorNumElements();
6389 if (NumElts
% 2 != 0)
6391 WhichResult
= (M
[0] == 0 ? 0 : 1);
6392 for (unsigned i
= 0; i
< NumElts
; i
+= 2) {
6393 if ((M
[i
] >= 0 && (unsigned)M
[i
] != i
+ WhichResult
) ||
6394 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != i
+ WhichResult
))
6400 static bool isINSMask(ArrayRef
<int> M
, int NumInputElements
,
6401 bool &DstIsLeft
, int &Anomaly
) {
6402 if (M
.size() != static_cast<size_t>(NumInputElements
))
6405 int NumLHSMatch
= 0, NumRHSMatch
= 0;
6406 int LastLHSMismatch
= -1, LastRHSMismatch
= -1;
6408 for (int i
= 0; i
< NumInputElements
; ++i
) {
6418 LastLHSMismatch
= i
;
6420 if (M
[i
] == i
+ NumInputElements
)
6423 LastRHSMismatch
= i
;
6426 if (NumLHSMatch
== NumInputElements
- 1) {
6428 Anomaly
= LastLHSMismatch
;
6430 } else if (NumRHSMatch
== NumInputElements
- 1) {
6432 Anomaly
= LastRHSMismatch
;
6439 static bool isConcatMask(ArrayRef
<int> Mask
, EVT VT
, bool SplitLHS
) {
6440 if (VT
.getSizeInBits() != 128)
6443 unsigned NumElts
= VT
.getVectorNumElements();
6445 for (int I
= 0, E
= NumElts
/ 2; I
!= E
; I
++) {
6450 int Offset
= NumElts
/ 2;
6451 for (int I
= NumElts
/ 2, E
= NumElts
; I
!= E
; I
++) {
6452 if (Mask
[I
] != I
+ SplitLHS
* Offset
)
6459 static SDValue
tryFormConcatFromShuffle(SDValue Op
, SelectionDAG
&DAG
) {
6461 EVT VT
= Op
.getValueType();
6462 SDValue V0
= Op
.getOperand(0);
6463 SDValue V1
= Op
.getOperand(1);
6464 ArrayRef
<int> Mask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
6466 if (VT
.getVectorElementType() != V0
.getValueType().getVectorElementType() ||
6467 VT
.getVectorElementType() != V1
.getValueType().getVectorElementType())
6470 bool SplitV0
= V0
.getValueSizeInBits() == 128;
6472 if (!isConcatMask(Mask
, VT
, SplitV0
))
6475 EVT CastVT
= EVT::getVectorVT(*DAG
.getContext(), VT
.getVectorElementType(),
6476 VT
.getVectorNumElements() / 2);
6478 V0
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, CastVT
, V0
,
6479 DAG
.getConstant(0, DL
, MVT::i64
));
6481 if (V1
.getValueSizeInBits() == 128) {
6482 V1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, CastVT
, V1
,
6483 DAG
.getConstant(0, DL
, MVT::i64
));
6485 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, V0
, V1
);
6488 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6489 /// the specified operations to build the shuffle.
6490 static SDValue
GeneratePerfectShuffle(unsigned PFEntry
, SDValue LHS
,
6491 SDValue RHS
, SelectionDAG
&DAG
,
6493 unsigned OpNum
= (PFEntry
>> 26) & 0x0F;
6494 unsigned LHSID
= (PFEntry
>> 13) & ((1 << 13) - 1);
6495 unsigned RHSID
= (PFEntry
>> 0) & ((1 << 13) - 1);
6498 OP_COPY
= 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6507 OP_VUZPL
, // VUZP, left result
6508 OP_VUZPR
, // VUZP, right result
6509 OP_VZIPL
, // VZIP, left result
6510 OP_VZIPR
, // VZIP, right result
6511 OP_VTRNL
, // VTRN, left result
6512 OP_VTRNR
// VTRN, right result
6515 if (OpNum
== OP_COPY
) {
6516 if (LHSID
== (1 * 9 + 2) * 9 + 3)
6518 assert(LHSID
== ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6522 SDValue OpLHS
, OpRHS
;
6523 OpLHS
= GeneratePerfectShuffle(PerfectShuffleTable
[LHSID
], LHS
, RHS
, DAG
, dl
);
6524 OpRHS
= GeneratePerfectShuffle(PerfectShuffleTable
[RHSID
], LHS
, RHS
, DAG
, dl
);
6525 EVT VT
= OpLHS
.getValueType();
6529 llvm_unreachable("Unknown shuffle opcode!");
6531 // VREV divides the vector in half and swaps within the half.
6532 if (VT
.getVectorElementType() == MVT::i32
||
6533 VT
.getVectorElementType() == MVT::f32
)
6534 return DAG
.getNode(AArch64ISD::REV64
, dl
, VT
, OpLHS
);
6535 // vrev <4 x i16> -> REV32
6536 if (VT
.getVectorElementType() == MVT::i16
||
6537 VT
.getVectorElementType() == MVT::f16
)
6538 return DAG
.getNode(AArch64ISD::REV32
, dl
, VT
, OpLHS
);
6539 // vrev <4 x i8> -> REV16
6540 assert(VT
.getVectorElementType() == MVT::i8
);
6541 return DAG
.getNode(AArch64ISD::REV16
, dl
, VT
, OpLHS
);
6546 EVT EltTy
= VT
.getVectorElementType();
6548 if (EltTy
== MVT::i8
)
6549 Opcode
= AArch64ISD::DUPLANE8
;
6550 else if (EltTy
== MVT::i16
|| EltTy
== MVT::f16
)
6551 Opcode
= AArch64ISD::DUPLANE16
;
6552 else if (EltTy
== MVT::i32
|| EltTy
== MVT::f32
)
6553 Opcode
= AArch64ISD::DUPLANE32
;
6554 else if (EltTy
== MVT::i64
|| EltTy
== MVT::f64
)
6555 Opcode
= AArch64ISD::DUPLANE64
;
6557 llvm_unreachable("Invalid vector element type?");
6559 if (VT
.getSizeInBits() == 64)
6560 OpLHS
= WidenVector(OpLHS
, DAG
);
6561 SDValue Lane
= DAG
.getConstant(OpNum
- OP_VDUP0
, dl
, MVT::i64
);
6562 return DAG
.getNode(Opcode
, dl
, VT
, OpLHS
, Lane
);
6567 unsigned Imm
= (OpNum
- OP_VEXT1
+ 1) * getExtFactor(OpLHS
);
6568 return DAG
.getNode(AArch64ISD::EXT
, dl
, VT
, OpLHS
, OpRHS
,
6569 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6572 return DAG
.getNode(AArch64ISD::UZP1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6575 return DAG
.getNode(AArch64ISD::UZP2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6578 return DAG
.getNode(AArch64ISD::ZIP1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6581 return DAG
.getNode(AArch64ISD::ZIP2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6584 return DAG
.getNode(AArch64ISD::TRN1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6587 return DAG
.getNode(AArch64ISD::TRN2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6592 static SDValue
GenerateTBL(SDValue Op
, ArrayRef
<int> ShuffleMask
,
6593 SelectionDAG
&DAG
) {
6594 // Check to see if we can use the TBL instruction.
6595 SDValue V1
= Op
.getOperand(0);
6596 SDValue V2
= Op
.getOperand(1);
6599 EVT EltVT
= Op
.getValueType().getVectorElementType();
6600 unsigned BytesPerElt
= EltVT
.getSizeInBits() / 8;
6602 SmallVector
<SDValue
, 8> TBLMask
;
6603 for (int Val
: ShuffleMask
) {
6604 for (unsigned Byte
= 0; Byte
< BytesPerElt
; ++Byte
) {
6605 unsigned Offset
= Byte
+ Val
* BytesPerElt
;
6606 TBLMask
.push_back(DAG
.getConstant(Offset
, DL
, MVT::i32
));
6610 MVT IndexVT
= MVT::v8i8
;
6611 unsigned IndexLen
= 8;
6612 if (Op
.getValueSizeInBits() == 128) {
6613 IndexVT
= MVT::v16i8
;
6617 SDValue V1Cst
= DAG
.getNode(ISD::BITCAST
, DL
, IndexVT
, V1
);
6618 SDValue V2Cst
= DAG
.getNode(ISD::BITCAST
, DL
, IndexVT
, V2
);
6621 if (V2
.getNode()->isUndef()) {
6623 V1Cst
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v16i8
, V1Cst
, V1Cst
);
6624 Shuffle
= DAG
.getNode(
6625 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6626 DAG
.getConstant(Intrinsic::aarch64_neon_tbl1
, DL
, MVT::i32
), V1Cst
,
6627 DAG
.getBuildVector(IndexVT
, DL
,
6628 makeArrayRef(TBLMask
.data(), IndexLen
)));
6630 if (IndexLen
== 8) {
6631 V1Cst
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v16i8
, V1Cst
, V2Cst
);
6632 Shuffle
= DAG
.getNode(
6633 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6634 DAG
.getConstant(Intrinsic::aarch64_neon_tbl1
, DL
, MVT::i32
), V1Cst
,
6635 DAG
.getBuildVector(IndexVT
, DL
,
6636 makeArrayRef(TBLMask
.data(), IndexLen
)));
6638 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6639 // cannot currently represent the register constraints on the input
6641 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6642 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6644 Shuffle
= DAG
.getNode(
6645 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6646 DAG
.getConstant(Intrinsic::aarch64_neon_tbl2
, DL
, MVT::i32
), V1Cst
,
6647 V2Cst
, DAG
.getBuildVector(IndexVT
, DL
,
6648 makeArrayRef(TBLMask
.data(), IndexLen
)));
6651 return DAG
.getNode(ISD::BITCAST
, DL
, Op
.getValueType(), Shuffle
);
6654 static unsigned getDUPLANEOp(EVT EltType
) {
6655 if (EltType
== MVT::i8
)
6656 return AArch64ISD::DUPLANE8
;
6657 if (EltType
== MVT::i16
|| EltType
== MVT::f16
)
6658 return AArch64ISD::DUPLANE16
;
6659 if (EltType
== MVT::i32
|| EltType
== MVT::f32
)
6660 return AArch64ISD::DUPLANE32
;
6661 if (EltType
== MVT::i64
|| EltType
== MVT::f64
)
6662 return AArch64ISD::DUPLANE64
;
6664 llvm_unreachable("Invalid vector element type?");
6667 SDValue
AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op
,
6668 SelectionDAG
&DAG
) const {
6670 EVT VT
= Op
.getValueType();
6672 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(Op
.getNode());
6674 // Convert shuffles that are directly supported on NEON to target-specific
6675 // DAG nodes, instead of keeping them as shuffles and matching them again
6676 // during code selection. This is more efficient and avoids the possibility
6677 // of inconsistencies between legalization and selection.
6678 ArrayRef
<int> ShuffleMask
= SVN
->getMask();
6680 SDValue V1
= Op
.getOperand(0);
6681 SDValue V2
= Op
.getOperand(1);
6683 if (SVN
->isSplat()) {
6684 int Lane
= SVN
->getSplatIndex();
6685 // If this is undef splat, generate it via "just" vdup, if possible.
6689 if (Lane
== 0 && V1
.getOpcode() == ISD::SCALAR_TO_VECTOR
)
6690 return DAG
.getNode(AArch64ISD::DUP
, dl
, V1
.getValueType(),
6692 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6693 // constant. If so, we can just reference the lane's definition directly.
6694 if (V1
.getOpcode() == ISD::BUILD_VECTOR
&&
6695 !isa
<ConstantSDNode
>(V1
.getOperand(Lane
)))
6696 return DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, V1
.getOperand(Lane
));
6698 // Otherwise, duplicate from the lane of the input vector.
6699 unsigned Opcode
= getDUPLANEOp(V1
.getValueType().getVectorElementType());
6701 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6702 // to make a vector of the same size as this SHUFFLE. We can ignore the
6703 // extract entirely, and canonicalise the concat using WidenVector.
6704 if (V1
.getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
6705 Lane
+= cast
<ConstantSDNode
>(V1
.getOperand(1))->getZExtValue();
6706 V1
= V1
.getOperand(0);
6707 } else if (V1
.getOpcode() == ISD::CONCAT_VECTORS
) {
6708 unsigned Idx
= Lane
>= (int)VT
.getVectorNumElements() / 2;
6709 Lane
-= Idx
* VT
.getVectorNumElements() / 2;
6710 V1
= WidenVector(V1
.getOperand(Idx
), DAG
);
6711 } else if (VT
.getSizeInBits() == 64)
6712 V1
= WidenVector(V1
, DAG
);
6714 return DAG
.getNode(Opcode
, dl
, VT
, V1
, DAG
.getConstant(Lane
, dl
, MVT::i64
));
6717 if (isREVMask(ShuffleMask
, VT
, 64))
6718 return DAG
.getNode(AArch64ISD::REV64
, dl
, V1
.getValueType(), V1
, V2
);
6719 if (isREVMask(ShuffleMask
, VT
, 32))
6720 return DAG
.getNode(AArch64ISD::REV32
, dl
, V1
.getValueType(), V1
, V2
);
6721 if (isREVMask(ShuffleMask
, VT
, 16))
6722 return DAG
.getNode(AArch64ISD::REV16
, dl
, V1
.getValueType(), V1
, V2
);
6724 bool ReverseEXT
= false;
6726 if (isEXTMask(ShuffleMask
, VT
, ReverseEXT
, Imm
)) {
6729 Imm
*= getExtFactor(V1
);
6730 return DAG
.getNode(AArch64ISD::EXT
, dl
, V1
.getValueType(), V1
, V2
,
6731 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6732 } else if (V2
->isUndef() && isSingletonEXTMask(ShuffleMask
, VT
, Imm
)) {
6733 Imm
*= getExtFactor(V1
);
6734 return DAG
.getNode(AArch64ISD::EXT
, dl
, V1
.getValueType(), V1
, V1
,
6735 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6738 unsigned WhichResult
;
6739 if (isZIPMask(ShuffleMask
, VT
, WhichResult
)) {
6740 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::ZIP1
: AArch64ISD::ZIP2
;
6741 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6743 if (isUZPMask(ShuffleMask
, VT
, WhichResult
)) {
6744 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::UZP1
: AArch64ISD::UZP2
;
6745 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6747 if (isTRNMask(ShuffleMask
, VT
, WhichResult
)) {
6748 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::TRN1
: AArch64ISD::TRN2
;
6749 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6752 if (isZIP_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6753 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::ZIP1
: AArch64ISD::ZIP2
;
6754 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6756 if (isUZP_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6757 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::UZP1
: AArch64ISD::UZP2
;
6758 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6760 if (isTRN_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6761 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::TRN1
: AArch64ISD::TRN2
;
6762 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6765 if (SDValue Concat
= tryFormConcatFromShuffle(Op
, DAG
))
6770 int NumInputElements
= V1
.getValueType().getVectorNumElements();
6771 if (isINSMask(ShuffleMask
, NumInputElements
, DstIsLeft
, Anomaly
)) {
6772 SDValue DstVec
= DstIsLeft
? V1
: V2
;
6773 SDValue DstLaneV
= DAG
.getConstant(Anomaly
, dl
, MVT::i64
);
6775 SDValue SrcVec
= V1
;
6776 int SrcLane
= ShuffleMask
[Anomaly
];
6777 if (SrcLane
>= NumInputElements
) {
6779 SrcLane
-= VT
.getVectorNumElements();
6781 SDValue SrcLaneV
= DAG
.getConstant(SrcLane
, dl
, MVT::i64
);
6783 EVT ScalarVT
= VT
.getVectorElementType();
6785 if (ScalarVT
.getSizeInBits() < 32 && ScalarVT
.isInteger())
6786 ScalarVT
= MVT::i32
;
6789 ISD::INSERT_VECTOR_ELT
, dl
, VT
, DstVec
,
6790 DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, dl
, ScalarVT
, SrcVec
, SrcLaneV
),
6794 // If the shuffle is not directly supported and it has 4 elements, use
6795 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6796 unsigned NumElts
= VT
.getVectorNumElements();
6798 unsigned PFIndexes
[4];
6799 for (unsigned i
= 0; i
!= 4; ++i
) {
6800 if (ShuffleMask
[i
] < 0)
6803 PFIndexes
[i
] = ShuffleMask
[i
];
6806 // Compute the index in the perfect shuffle table.
6807 unsigned PFTableIndex
= PFIndexes
[0] * 9 * 9 * 9 + PFIndexes
[1] * 9 * 9 +
6808 PFIndexes
[2] * 9 + PFIndexes
[3];
6809 unsigned PFEntry
= PerfectShuffleTable
[PFTableIndex
];
6810 unsigned Cost
= (PFEntry
>> 30);
6813 return GeneratePerfectShuffle(PFEntry
, V1
, V2
, DAG
, dl
);
6816 return GenerateTBL(Op
, ShuffleMask
, DAG
);
6819 static bool resolveBuildVector(BuildVectorSDNode
*BVN
, APInt
&CnstBits
,
6821 EVT VT
= BVN
->getValueType(0);
6822 APInt SplatBits
, SplatUndef
;
6823 unsigned SplatBitSize
;
6825 if (BVN
->isConstantSplat(SplatBits
, SplatUndef
, SplatBitSize
, HasAnyUndefs
)) {
6826 unsigned NumSplats
= VT
.getSizeInBits() / SplatBitSize
;
6828 for (unsigned i
= 0; i
< NumSplats
; ++i
) {
6829 CnstBits
<<= SplatBitSize
;
6830 UndefBits
<<= SplatBitSize
;
6831 CnstBits
|= SplatBits
.zextOrTrunc(VT
.getSizeInBits());
6832 UndefBits
|= (SplatBits
^ SplatUndef
).zextOrTrunc(VT
.getSizeInBits());
6841 // Try 64-bit splatted SIMD immediate.
6842 static SDValue
tryAdvSIMDModImm64(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6843 const APInt
&Bits
) {
6844 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6845 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6846 EVT VT
= Op
.getValueType();
6847 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v2i64
: MVT::f64
;
6849 if (AArch64_AM::isAdvSIMDModImmType10(Value
)) {
6850 Value
= AArch64_AM::encodeAdvSIMDModImmType10(Value
);
6853 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6854 DAG
.getConstant(Value
, dl
, MVT::i32
));
6855 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6862 // Try 32-bit splatted SIMD immediate.
6863 static SDValue
tryAdvSIMDModImm32(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6865 const SDValue
*LHS
= nullptr) {
6866 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6867 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6868 EVT VT
= Op
.getValueType();
6869 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v4i32
: MVT::v2i32
;
6870 bool isAdvSIMDModImm
= false;
6873 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType1(Value
))) {
6874 Value
= AArch64_AM::encodeAdvSIMDModImmType1(Value
);
6877 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType2(Value
))) {
6878 Value
= AArch64_AM::encodeAdvSIMDModImmType2(Value
);
6881 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType3(Value
))) {
6882 Value
= AArch64_AM::encodeAdvSIMDModImmType3(Value
);
6885 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType4(Value
))) {
6886 Value
= AArch64_AM::encodeAdvSIMDModImmType4(Value
);
6890 if (isAdvSIMDModImm
) {
6895 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
, *LHS
,
6896 DAG
.getConstant(Value
, dl
, MVT::i32
),
6897 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6899 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6900 DAG
.getConstant(Value
, dl
, MVT::i32
),
6901 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6903 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6910 // Try 16-bit splatted SIMD immediate.
6911 static SDValue
tryAdvSIMDModImm16(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6913 const SDValue
*LHS
= nullptr) {
6914 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6915 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6916 EVT VT
= Op
.getValueType();
6917 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v8i16
: MVT::v4i16
;
6918 bool isAdvSIMDModImm
= false;
6921 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType5(Value
))) {
6922 Value
= AArch64_AM::encodeAdvSIMDModImmType5(Value
);
6925 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType6(Value
))) {
6926 Value
= AArch64_AM::encodeAdvSIMDModImmType6(Value
);
6930 if (isAdvSIMDModImm
) {
6935 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
, *LHS
,
6936 DAG
.getConstant(Value
, dl
, MVT::i32
),
6937 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6939 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6940 DAG
.getConstant(Value
, dl
, MVT::i32
),
6941 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6943 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6950 // Try 32-bit splatted SIMD immediate with shifted ones.
6951 static SDValue
tryAdvSIMDModImm321s(unsigned NewOp
, SDValue Op
,
6952 SelectionDAG
&DAG
, const APInt
&Bits
) {
6953 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6954 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6955 EVT VT
= Op
.getValueType();
6956 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v4i32
: MVT::v2i32
;
6957 bool isAdvSIMDModImm
= false;
6960 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType7(Value
))) {
6961 Value
= AArch64_AM::encodeAdvSIMDModImmType7(Value
);
6964 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType8(Value
))) {
6965 Value
= AArch64_AM::encodeAdvSIMDModImmType8(Value
);
6969 if (isAdvSIMDModImm
) {
6971 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6972 DAG
.getConstant(Value
, dl
, MVT::i32
),
6973 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6974 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6981 // Try 8-bit splatted SIMD immediate.
6982 static SDValue
tryAdvSIMDModImm8(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6983 const APInt
&Bits
) {
6984 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6985 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6986 EVT VT
= Op
.getValueType();
6987 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v16i8
: MVT::v8i8
;
6989 if (AArch64_AM::isAdvSIMDModImmType9(Value
)) {
6990 Value
= AArch64_AM::encodeAdvSIMDModImmType9(Value
);
6993 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6994 DAG
.getConstant(Value
, dl
, MVT::i32
));
6995 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
7002 // Try FP splatted SIMD immediate.
7003 static SDValue
tryAdvSIMDModImmFP(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
7004 const APInt
&Bits
) {
7005 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
7006 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
7007 EVT VT
= Op
.getValueType();
7008 bool isWide
= (VT
.getSizeInBits() == 128);
7010 bool isAdvSIMDModImm
= false;
7012 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType11(Value
))) {
7013 Value
= AArch64_AM::encodeAdvSIMDModImmType11(Value
);
7014 MovTy
= isWide
? MVT::v4f32
: MVT::v2f32
;
7017 (isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType12(Value
))) {
7018 Value
= AArch64_AM::encodeAdvSIMDModImmType12(Value
);
7022 if (isAdvSIMDModImm
) {
7024 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
7025 DAG
.getConstant(Value
, dl
, MVT::i32
));
7026 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
7033 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7034 // consists of only the same constant int value, returned in reference arg
7036 static bool isAllConstantBuildVector(const SDValue
&PotentialBVec
,
7037 uint64_t &ConstVal
) {
7038 BuildVectorSDNode
*Bvec
= dyn_cast
<BuildVectorSDNode
>(PotentialBVec
);
7041 ConstantSDNode
*FirstElt
= dyn_cast
<ConstantSDNode
>(Bvec
->getOperand(0));
7044 EVT VT
= Bvec
->getValueType(0);
7045 unsigned NumElts
= VT
.getVectorNumElements();
7046 for (unsigned i
= 1; i
< NumElts
; ++i
)
7047 if (dyn_cast
<ConstantSDNode
>(Bvec
->getOperand(i
)) != FirstElt
)
7049 ConstVal
= FirstElt
->getZExtValue();
7053 static unsigned getIntrinsicID(const SDNode
*N
) {
7054 unsigned Opcode
= N
->getOpcode();
7057 return Intrinsic::not_intrinsic
;
7058 case ISD::INTRINSIC_WO_CHAIN
: {
7059 unsigned IID
= cast
<ConstantSDNode
>(N
->getOperand(0))->getZExtValue();
7060 if (IID
< Intrinsic::num_intrinsics
)
7062 return Intrinsic::not_intrinsic
;
7067 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7068 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7069 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7070 // Also, logical shift right -> sri, with the same structure.
7071 static SDValue
tryLowerToSLI(SDNode
*N
, SelectionDAG
&DAG
) {
7072 EVT VT
= N
->getValueType(0);
7079 // Is the first op an AND?
7080 const SDValue And
= N
->getOperand(0);
7081 if (And
.getOpcode() != ISD::AND
)
7084 // Is the second op an shl or lshr?
7085 SDValue Shift
= N
->getOperand(1);
7086 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7087 // or AArch64ISD::VLSHR vector, #shift
7088 unsigned ShiftOpc
= Shift
.getOpcode();
7089 if ((ShiftOpc
!= AArch64ISD::VSHL
&& ShiftOpc
!= AArch64ISD::VLSHR
))
7091 bool IsShiftRight
= ShiftOpc
== AArch64ISD::VLSHR
;
7093 // Is the shift amount constant?
7094 ConstantSDNode
*C2node
= dyn_cast
<ConstantSDNode
>(Shift
.getOperand(1));
7098 // Is the and mask vector all constant?
7100 if (!isAllConstantBuildVector(And
.getOperand(1), C1
))
7103 // Is C1 == ~C2, taking into account how much one can shift elements of a
7105 uint64_t C2
= C2node
->getZExtValue();
7106 unsigned ElemSizeInBits
= VT
.getScalarSizeInBits();
7107 if (C2
> ElemSizeInBits
)
7109 unsigned ElemMask
= (1 << ElemSizeInBits
) - 1;
7110 if ((C1
& ElemMask
) != (~C2
& ElemMask
))
7113 SDValue X
= And
.getOperand(0);
7114 SDValue Y
= Shift
.getOperand(0);
7117 IsShiftRight
? Intrinsic::aarch64_neon_vsri
: Intrinsic::aarch64_neon_vsli
;
7119 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7120 DAG
.getConstant(Intrin
, DL
, MVT::i32
), X
, Y
,
7121 Shift
.getOperand(1));
7123 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7124 LLVM_DEBUG(N
->dump(&DAG
));
7125 LLVM_DEBUG(dbgs() << "into: \n");
7126 LLVM_DEBUG(ResultSLI
->dump(&DAG
));
7132 SDValue
AArch64TargetLowering::LowerVectorOR(SDValue Op
,
7133 SelectionDAG
&DAG
) const {
7134 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7135 if (EnableAArch64SlrGeneration
) {
7136 if (SDValue Res
= tryLowerToSLI(Op
.getNode(), DAG
))
7140 EVT VT
= Op
.getValueType();
7142 SDValue LHS
= Op
.getOperand(0);
7143 BuildVectorSDNode
*BVN
=
7144 dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(1).getNode());
7146 // OR commutes, so try swapping the operands.
7147 LHS
= Op
.getOperand(1);
7148 BVN
= dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(0).getNode());
7153 APInt
DefBits(VT
.getSizeInBits(), 0);
7154 APInt
UndefBits(VT
.getSizeInBits(), 0);
7155 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
7158 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::ORRi
, Op
, DAG
,
7160 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::ORRi
, Op
, DAG
,
7164 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::ORRi
, Op
, DAG
,
7165 UndefBits
, &LHS
)) ||
7166 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::ORRi
, Op
, DAG
,
7171 // We can always fall back to a non-immediate OR.
7175 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7176 // be truncated to fit element width.
7177 static SDValue
NormalizeBuildVector(SDValue Op
,
7178 SelectionDAG
&DAG
) {
7179 assert(Op
.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!");
7181 EVT VT
= Op
.getValueType();
7182 EVT EltTy
= VT
.getVectorElementType();
7184 if (EltTy
.isFloatingPoint() || EltTy
.getSizeInBits() > 16)
7187 SmallVector
<SDValue
, 16> Ops
;
7188 for (SDValue Lane
: Op
->ops()) {
7189 // For integer vectors, type legalization would have promoted the
7190 // operands already. Otherwise, if Op is a floating-point splat
7191 // (with operands cast to integers), then the only possibilities
7192 // are constants and UNDEFs.
7193 if (auto *CstLane
= dyn_cast
<ConstantSDNode
>(Lane
)) {
7194 APInt
LowBits(EltTy
.getSizeInBits(),
7195 CstLane
->getZExtValue());
7196 Lane
= DAG
.getConstant(LowBits
.getZExtValue(), dl
, MVT::i32
);
7197 } else if (Lane
.getNode()->isUndef()) {
7198 Lane
= DAG
.getUNDEF(MVT::i32
);
7200 assert(Lane
.getValueType() == MVT::i32
&&
7201 "Unexpected BUILD_VECTOR operand type");
7203 Ops
.push_back(Lane
);
7205 return DAG
.getBuildVector(VT
, dl
, Ops
);
7208 static SDValue
ConstantBuildVector(SDValue Op
, SelectionDAG
&DAG
) {
7209 EVT VT
= Op
.getValueType();
7211 APInt
DefBits(VT
.getSizeInBits(), 0);
7212 APInt
UndefBits(VT
.getSizeInBits(), 0);
7213 BuildVectorSDNode
*BVN
= cast
<BuildVectorSDNode
>(Op
.getNode());
7214 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
7216 if ((NewOp
= tryAdvSIMDModImm64(AArch64ISD::MOVIedit
, Op
, DAG
, DefBits
)) ||
7217 (NewOp
= tryAdvSIMDModImm32(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7218 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MOVImsl
, Op
, DAG
, DefBits
)) ||
7219 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7220 (NewOp
= tryAdvSIMDModImm8(AArch64ISD::MOVI
, Op
, DAG
, DefBits
)) ||
7221 (NewOp
= tryAdvSIMDModImmFP(AArch64ISD::FMOV
, Op
, DAG
, DefBits
)))
7225 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)) ||
7226 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MVNImsl
, Op
, DAG
, DefBits
)) ||
7227 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)))
7230 DefBits
= UndefBits
;
7231 if ((NewOp
= tryAdvSIMDModImm64(AArch64ISD::MOVIedit
, Op
, DAG
, DefBits
)) ||
7232 (NewOp
= tryAdvSIMDModImm32(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7233 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MOVImsl
, Op
, DAG
, DefBits
)) ||
7234 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7235 (NewOp
= tryAdvSIMDModImm8(AArch64ISD::MOVI
, Op
, DAG
, DefBits
)) ||
7236 (NewOp
= tryAdvSIMDModImmFP(AArch64ISD::FMOV
, Op
, DAG
, DefBits
)))
7239 DefBits
= ~UndefBits
;
7240 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)) ||
7241 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MVNImsl
, Op
, DAG
, DefBits
)) ||
7242 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)))
7249 SDValue
AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op
,
7250 SelectionDAG
&DAG
) const {
7251 EVT VT
= Op
.getValueType();
7253 // Try to build a simple constant vector.
7254 Op
= NormalizeBuildVector(Op
, DAG
);
7255 if (VT
.isInteger()) {
7256 // Certain vector constants, used to express things like logical NOT and
7257 // arithmetic NEG, are passed through unmodified. This allows special
7258 // patterns for these operations to match, which will lower these constants
7259 // to whatever is proven necessary.
7260 BuildVectorSDNode
*BVN
= cast
<BuildVectorSDNode
>(Op
.getNode());
7261 if (BVN
->isConstant())
7262 if (ConstantSDNode
*Const
= BVN
->getConstantSplatNode()) {
7263 unsigned BitSize
= VT
.getVectorElementType().getSizeInBits();
7265 Const
->getAPIntValue().zextOrTrunc(BitSize
).getZExtValue());
7266 if (Val
.isNullValue() || Val
.isAllOnesValue())
7271 if (SDValue V
= ConstantBuildVector(Op
, DAG
))
7274 // Scan through the operands to find some interesting properties we can
7276 // 1) If only one value is used, we can use a DUP, or
7277 // 2) if only the low element is not undef, we can just insert that, or
7278 // 3) if only one constant value is used (w/ some non-constant lanes),
7279 // we can splat the constant value into the whole vector then fill
7280 // in the non-constant lanes.
7281 // 4) FIXME: If different constant values are used, but we can intelligently
7282 // select the values we'll be overwriting for the non-constant
7283 // lanes such that we can directly materialize the vector
7284 // some other way (MOVI, e.g.), we can be sneaky.
7285 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7287 unsigned NumElts
= VT
.getVectorNumElements();
7288 bool isOnlyLowElement
= true;
7289 bool usesOnlyOneValue
= true;
7290 bool usesOnlyOneConstantValue
= true;
7291 bool isConstant
= true;
7292 bool AllLanesExtractElt
= true;
7293 unsigned NumConstantLanes
= 0;
7295 SDValue ConstantValue
;
7296 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7297 SDValue V
= Op
.getOperand(i
);
7298 if (V
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
)
7299 AllLanesExtractElt
= false;
7303 isOnlyLowElement
= false;
7304 if (!isa
<ConstantFPSDNode
>(V
) && !isa
<ConstantSDNode
>(V
))
7307 if (isa
<ConstantSDNode
>(V
) || isa
<ConstantFPSDNode
>(V
)) {
7309 if (!ConstantValue
.getNode())
7311 else if (ConstantValue
!= V
)
7312 usesOnlyOneConstantValue
= false;
7315 if (!Value
.getNode())
7317 else if (V
!= Value
)
7318 usesOnlyOneValue
= false;
7321 if (!Value
.getNode()) {
7323 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7324 return DAG
.getUNDEF(VT
);
7327 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7328 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7329 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7330 if (isOnlyLowElement
&& !(NumElts
== 1 && isa
<ConstantSDNode
>(Value
))) {
7331 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7332 "SCALAR_TO_VECTOR node\n");
7333 return DAG
.getNode(ISD::SCALAR_TO_VECTOR
, dl
, VT
, Value
);
7336 if (AllLanesExtractElt
) {
7337 SDNode
*Vector
= nullptr;
7340 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7341 // the Odd pattern <1,3,5,...>.
7342 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7343 SDValue V
= Op
.getOperand(i
);
7344 const SDNode
*N
= V
.getNode();
7345 if (!isa
<ConstantSDNode
>(N
->getOperand(1)))
7347 SDValue N0
= N
->getOperand(0);
7349 // All elements are extracted from the same vector.
7351 Vector
= N0
.getNode();
7352 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7354 if (VT
.getVectorElementType() !=
7355 N0
.getValueType().getVectorElementType())
7357 } else if (Vector
!= N0
.getNode()) {
7363 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7364 // indices <1,3,5,...>.
7365 uint64_t Val
= N
->getConstantOperandVal(1);
7370 if (Val
- 1 == 2 * i
) {
7375 // Something does not match: abort.
7382 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, SDValue(Vector
, 0),
7383 DAG
.getConstant(0, dl
, MVT::i64
));
7385 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, SDValue(Vector
, 0),
7386 DAG
.getConstant(NumElts
, dl
, MVT::i64
));
7389 return DAG
.getNode(AArch64ISD::UZP1
, dl
, DAG
.getVTList(VT
, VT
), LHS
,
7392 return DAG
.getNode(AArch64ISD::UZP2
, dl
, DAG
.getVTList(VT
, VT
), LHS
,
7397 // Use DUP for non-constant splats. For f32 constant splats, reduce to
7398 // i32 and try again.
7399 if (usesOnlyOneValue
) {
7401 if (Value
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
7402 Value
.getValueType() != VT
) {
7404 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7405 return DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, Value
);
7408 // This is actually a DUPLANExx operation, which keeps everything vectory.
7410 SDValue Lane
= Value
.getOperand(1);
7411 Value
= Value
.getOperand(0);
7412 if (Value
.getValueSizeInBits() == 64) {
7414 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7416 Value
= WidenVector(Value
, DAG
);
7419 unsigned Opcode
= getDUPLANEOp(VT
.getVectorElementType());
7420 return DAG
.getNode(Opcode
, dl
, VT
, Value
, Lane
);
7423 if (VT
.getVectorElementType().isFloatingPoint()) {
7424 SmallVector
<SDValue
, 8> Ops
;
7425 EVT EltTy
= VT
.getVectorElementType();
7426 assert ((EltTy
== MVT::f16
|| EltTy
== MVT::f32
|| EltTy
== MVT::f64
) &&
7427 "Unsupported floating-point vector type");
7429 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7430 "BITCASTS, and try again\n");
7431 MVT NewType
= MVT::getIntegerVT(EltTy
.getSizeInBits());
7432 for (unsigned i
= 0; i
< NumElts
; ++i
)
7433 Ops
.push_back(DAG
.getNode(ISD::BITCAST
, dl
, NewType
, Op
.getOperand(i
)));
7434 EVT VecVT
= EVT::getVectorVT(*DAG
.getContext(), NewType
, NumElts
);
7435 SDValue Val
= DAG
.getBuildVector(VecVT
, dl
, Ops
);
7436 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7438 Val
= LowerBUILD_VECTOR(Val
, DAG
);
7440 return DAG
.getNode(ISD::BITCAST
, dl
, VT
, Val
);
7444 // If there was only one constant value used and for more than one lane,
7445 // start by splatting that value, then replace the non-constant lanes. This
7446 // is better than the default, which will perform a separate initialization
7448 if (NumConstantLanes
> 0 && usesOnlyOneConstantValue
) {
7449 // Firstly, try to materialize the splat constant.
7450 SDValue Vec
= DAG
.getSplatBuildVector(VT
, dl
, ConstantValue
),
7451 Val
= ConstantBuildVector(Vec
, DAG
);
7453 // Otherwise, materialize the constant and splat it.
7454 Val
= DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, ConstantValue
);
7455 DAG
.ReplaceAllUsesWith(Vec
.getNode(), &Val
);
7458 // Now insert the non-constant lanes.
7459 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7460 SDValue V
= Op
.getOperand(i
);
7461 SDValue LaneIdx
= DAG
.getConstant(i
, dl
, MVT::i64
);
7462 if (!isa
<ConstantSDNode
>(V
) && !isa
<ConstantFPSDNode
>(V
))
7463 // Note that type legalization likely mucked about with the VT of the
7464 // source operand, so we may have to convert it here before inserting.
7465 Val
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, dl
, VT
, Val
, V
, LaneIdx
);
7470 // This will generate a load from the constant pool.
7473 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7478 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7480 if (SDValue shuffle
= ReconstructShuffle(Op
, DAG
))
7484 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7485 // know the default expansion would otherwise fall back on something even
7486 // worse. For a vector with one or two non-undef values, that's
7487 // scalar_to_vector for the elements followed by a shuffle (provided the
7488 // shuffle is valid for the target) and materialization element by element
7489 // on the stack followed by a load for everything else.
7490 if (!isConstant
&& !usesOnlyOneValue
) {
7492 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7493 "of INSERT_VECTOR_ELT\n");
7495 SDValue Vec
= DAG
.getUNDEF(VT
);
7496 SDValue Op0
= Op
.getOperand(0);
7499 // Use SCALAR_TO_VECTOR for lane zero to
7500 // a) Avoid a RMW dependency on the full vector register, and
7501 // b) Allow the register coalescer to fold away the copy if the
7502 // value is already in an S or D register, and we're forced to emit an
7503 // INSERT_SUBREG that we can't fold anywhere.
7505 // We also allow types like i8 and i16 which are illegal scalar but legal
7506 // vector element types. After type-legalization the inserted value is
7507 // extended (i32) and it is safe to cast them to the vector type by ignoring
7508 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7509 if (!Op0
.isUndef()) {
7510 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7511 Vec
= DAG
.getNode(ISD::SCALAR_TO_VECTOR
, dl
, VT
, Op0
);
7514 LLVM_DEBUG(if (i
< NumElts
) dbgs()
7515 << "Creating nodes for the other vector elements:\n";);
7516 for (; i
< NumElts
; ++i
) {
7517 SDValue V
= Op
.getOperand(i
);
7520 SDValue LaneIdx
= DAG
.getConstant(i
, dl
, MVT::i64
);
7521 Vec
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, dl
, VT
, Vec
, V
, LaneIdx
);
7527 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7528 "better alternative\n");
7532 SDValue
AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op
,
7533 SelectionDAG
&DAG
) const {
7534 assert(Op
.getOpcode() == ISD::INSERT_VECTOR_ELT
&& "Unknown opcode!");
7536 // Check for non-constant or out of range lane.
7537 EVT VT
= Op
.getOperand(0).getValueType();
7538 ConstantSDNode
*CI
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
7539 if (!CI
|| CI
->getZExtValue() >= VT
.getVectorNumElements())
7543 // Insertion/extraction are legal for V128 types.
7544 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
||
7545 VT
== MVT::v2i64
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
||
7549 if (VT
!= MVT::v8i8
&& VT
!= MVT::v4i16
&& VT
!= MVT::v2i32
&&
7550 VT
!= MVT::v1i64
&& VT
!= MVT::v2f32
&& VT
!= MVT::v4f16
)
7553 // For V64 types, we perform insertion by expanding the value
7554 // to a V128 type and perform the insertion on that.
7556 SDValue WideVec
= WidenVector(Op
.getOperand(0), DAG
);
7557 EVT WideTy
= WideVec
.getValueType();
7559 SDValue Node
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, DL
, WideTy
, WideVec
,
7560 Op
.getOperand(1), Op
.getOperand(2));
7561 // Re-narrow the resultant vector.
7562 return NarrowVector(Node
, DAG
);
7566 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op
,
7567 SelectionDAG
&DAG
) const {
7568 assert(Op
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&& "Unknown opcode!");
7570 // Check for non-constant or out of range lane.
7571 EVT VT
= Op
.getOperand(0).getValueType();
7572 ConstantSDNode
*CI
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
7573 if (!CI
|| CI
->getZExtValue() >= VT
.getVectorNumElements())
7577 // Insertion/extraction are legal for V128 types.
7578 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
||
7579 VT
== MVT::v2i64
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
||
7583 if (VT
!= MVT::v8i8
&& VT
!= MVT::v4i16
&& VT
!= MVT::v2i32
&&
7584 VT
!= MVT::v1i64
&& VT
!= MVT::v2f32
&& VT
!= MVT::v4f16
)
7587 // For V64 types, we perform extraction by expanding the value
7588 // to a V128 type and perform the extraction on that.
7590 SDValue WideVec
= WidenVector(Op
.getOperand(0), DAG
);
7591 EVT WideTy
= WideVec
.getValueType();
7593 EVT ExtrTy
= WideTy
.getVectorElementType();
7594 if (ExtrTy
== MVT::i16
|| ExtrTy
== MVT::i8
)
7597 // For extractions, we just return the result directly.
7598 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ExtrTy
, WideVec
,
7602 SDValue
AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op
,
7603 SelectionDAG
&DAG
) const {
7604 EVT VT
= Op
.getOperand(0).getValueType();
7610 ConstantSDNode
*Cst
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
7613 unsigned Val
= Cst
->getZExtValue();
7615 unsigned Size
= Op
.getValueSizeInBits();
7617 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7621 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7623 if (Size
== 64 && Val
* VT
.getScalarSizeInBits() == 64)
7629 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef
<int> M
, EVT VT
) const {
7630 if (VT
.getVectorNumElements() == 4 &&
7631 (VT
.is128BitVector() || VT
.is64BitVector())) {
7632 unsigned PFIndexes
[4];
7633 for (unsigned i
= 0; i
!= 4; ++i
) {
7637 PFIndexes
[i
] = M
[i
];
7640 // Compute the index in the perfect shuffle table.
7641 unsigned PFTableIndex
= PFIndexes
[0] * 9 * 9 * 9 + PFIndexes
[1] * 9 * 9 +
7642 PFIndexes
[2] * 9 + PFIndexes
[3];
7643 unsigned PFEntry
= PerfectShuffleTable
[PFTableIndex
];
7644 unsigned Cost
= (PFEntry
>> 30);
7652 unsigned DummyUnsigned
;
7654 return (ShuffleVectorSDNode::isSplatMask(&M
[0], VT
) || isREVMask(M
, VT
, 64) ||
7655 isREVMask(M
, VT
, 32) || isREVMask(M
, VT
, 16) ||
7656 isEXTMask(M
, VT
, DummyBool
, DummyUnsigned
) ||
7657 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7658 isTRNMask(M
, VT
, DummyUnsigned
) || isUZPMask(M
, VT
, DummyUnsigned
) ||
7659 isZIPMask(M
, VT
, DummyUnsigned
) ||
7660 isTRN_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7661 isUZP_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7662 isZIP_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7663 isINSMask(M
, VT
.getVectorNumElements(), DummyBool
, DummyInt
) ||
7664 isConcatMask(M
, VT
, VT
.getSizeInBits() == 128));
7667 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7668 /// operand of a vector shift operation, where all the elements of the
7669 /// build_vector must have the same constant integer value.
7670 static bool getVShiftImm(SDValue Op
, unsigned ElementBits
, int64_t &Cnt
) {
7671 // Ignore bit_converts.
7672 while (Op
.getOpcode() == ISD::BITCAST
)
7673 Op
= Op
.getOperand(0);
7674 BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(Op
.getNode());
7675 APInt SplatBits
, SplatUndef
;
7676 unsigned SplatBitSize
;
7678 if (!BVN
|| !BVN
->isConstantSplat(SplatBits
, SplatUndef
, SplatBitSize
,
7679 HasAnyUndefs
, ElementBits
) ||
7680 SplatBitSize
> ElementBits
)
7682 Cnt
= SplatBits
.getSExtValue();
7686 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7687 /// operand of a vector shift left operation. That value must be in the range:
7688 /// 0 <= Value < ElementBits for a left shift; or
7689 /// 0 <= Value <= ElementBits for a long left shift.
7690 static bool isVShiftLImm(SDValue Op
, EVT VT
, bool isLong
, int64_t &Cnt
) {
7691 assert(VT
.isVector() && "vector shift count is not a vector type");
7692 int64_t ElementBits
= VT
.getScalarSizeInBits();
7693 if (!getVShiftImm(Op
, ElementBits
, Cnt
))
7695 return (Cnt
>= 0 && (isLong
? Cnt
- 1 : Cnt
) < ElementBits
);
7698 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7699 /// operand of a vector shift right operation. The value must be in the range:
7700 /// 1 <= Value <= ElementBits for a right shift; or
7701 static bool isVShiftRImm(SDValue Op
, EVT VT
, bool isNarrow
, int64_t &Cnt
) {
7702 assert(VT
.isVector() && "vector shift count is not a vector type");
7703 int64_t ElementBits
= VT
.getScalarSizeInBits();
7704 if (!getVShiftImm(Op
, ElementBits
, Cnt
))
7706 return (Cnt
>= 1 && Cnt
<= (isNarrow
? ElementBits
/ 2 : ElementBits
));
7709 SDValue
AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op
,
7710 SelectionDAG
&DAG
) const {
7711 EVT VT
= Op
.getValueType();
7715 if (!Op
.getOperand(1).getValueType().isVector())
7717 unsigned EltSize
= VT
.getScalarSizeInBits();
7719 switch (Op
.getOpcode()) {
7721 llvm_unreachable("unexpected shift opcode");
7724 if (isVShiftLImm(Op
.getOperand(1), VT
, false, Cnt
) && Cnt
< EltSize
)
7725 return DAG
.getNode(AArch64ISD::VSHL
, DL
, VT
, Op
.getOperand(0),
7726 DAG
.getConstant(Cnt
, DL
, MVT::i32
));
7727 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7728 DAG
.getConstant(Intrinsic::aarch64_neon_ushl
, DL
,
7730 Op
.getOperand(0), Op
.getOperand(1));
7733 // Right shift immediate
7734 if (isVShiftRImm(Op
.getOperand(1), VT
, false, Cnt
) && Cnt
< EltSize
) {
7736 (Op
.getOpcode() == ISD::SRA
) ? AArch64ISD::VASHR
: AArch64ISD::VLSHR
;
7737 return DAG
.getNode(Opc
, DL
, VT
, Op
.getOperand(0),
7738 DAG
.getConstant(Cnt
, DL
, MVT::i32
));
7741 // Right shift register. Note, there is not a shift right register
7742 // instruction, but the shift left register instruction takes a signed
7743 // value, where negative numbers specify a right shift.
7744 unsigned Opc
= (Op
.getOpcode() == ISD::SRA
) ? Intrinsic::aarch64_neon_sshl
7745 : Intrinsic::aarch64_neon_ushl
;
7746 // negate the shift amount
7747 SDValue NegShift
= DAG
.getNode(AArch64ISD::NEG
, DL
, VT
, Op
.getOperand(1));
7748 SDValue NegShiftLeft
=
7749 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7750 DAG
.getConstant(Opc
, DL
, MVT::i32
), Op
.getOperand(0),
7752 return NegShiftLeft
;
7758 static SDValue
EmitVectorComparison(SDValue LHS
, SDValue RHS
,
7759 AArch64CC::CondCode CC
, bool NoNans
, EVT VT
,
7760 const SDLoc
&dl
, SelectionDAG
&DAG
) {
7761 EVT SrcVT
= LHS
.getValueType();
7762 assert(VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
7763 "function only supposed to emit natural comparisons");
7765 BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(RHS
.getNode());
7766 APInt
CnstBits(VT
.getSizeInBits(), 0);
7767 APInt
UndefBits(VT
.getSizeInBits(), 0);
7768 bool IsCnst
= BVN
&& resolveBuildVector(BVN
, CnstBits
, UndefBits
);
7769 bool IsZero
= IsCnst
&& (CnstBits
== 0);
7771 if (SrcVT
.getVectorElementType().isFloatingPoint()) {
7775 case AArch64CC::NE
: {
7778 Fcmeq
= DAG
.getNode(AArch64ISD::FCMEQz
, dl
, VT
, LHS
);
7780 Fcmeq
= DAG
.getNode(AArch64ISD::FCMEQ
, dl
, VT
, LHS
, RHS
);
7781 return DAG
.getNode(AArch64ISD::NOT
, dl
, VT
, Fcmeq
);
7785 return DAG
.getNode(AArch64ISD::FCMEQz
, dl
, VT
, LHS
);
7786 return DAG
.getNode(AArch64ISD::FCMEQ
, dl
, VT
, LHS
, RHS
);
7789 return DAG
.getNode(AArch64ISD::FCMGEz
, dl
, VT
, LHS
);
7790 return DAG
.getNode(AArch64ISD::FCMGE
, dl
, VT
, LHS
, RHS
);
7793 return DAG
.getNode(AArch64ISD::FCMGTz
, dl
, VT
, LHS
);
7794 return DAG
.getNode(AArch64ISD::FCMGT
, dl
, VT
, LHS
, RHS
);
7797 return DAG
.getNode(AArch64ISD::FCMLEz
, dl
, VT
, LHS
);
7798 return DAG
.getNode(AArch64ISD::FCMGE
, dl
, VT
, RHS
, LHS
);
7802 // If we ignore NaNs then we can use to the MI implementation.
7806 return DAG
.getNode(AArch64ISD::FCMLTz
, dl
, VT
, LHS
);
7807 return DAG
.getNode(AArch64ISD::FCMGT
, dl
, VT
, RHS
, LHS
);
7814 case AArch64CC::NE
: {
7817 Cmeq
= DAG
.getNode(AArch64ISD::CMEQz
, dl
, VT
, LHS
);
7819 Cmeq
= DAG
.getNode(AArch64ISD::CMEQ
, dl
, VT
, LHS
, RHS
);
7820 return DAG
.getNode(AArch64ISD::NOT
, dl
, VT
, Cmeq
);
7824 return DAG
.getNode(AArch64ISD::CMEQz
, dl
, VT
, LHS
);
7825 return DAG
.getNode(AArch64ISD::CMEQ
, dl
, VT
, LHS
, RHS
);
7828 return DAG
.getNode(AArch64ISD::CMGEz
, dl
, VT
, LHS
);
7829 return DAG
.getNode(AArch64ISD::CMGE
, dl
, VT
, LHS
, RHS
);
7832 return DAG
.getNode(AArch64ISD::CMGTz
, dl
, VT
, LHS
);
7833 return DAG
.getNode(AArch64ISD::CMGT
, dl
, VT
, LHS
, RHS
);
7836 return DAG
.getNode(AArch64ISD::CMLEz
, dl
, VT
, LHS
);
7837 return DAG
.getNode(AArch64ISD::CMGE
, dl
, VT
, RHS
, LHS
);
7839 return DAG
.getNode(AArch64ISD::CMHS
, dl
, VT
, RHS
, LHS
);
7841 return DAG
.getNode(AArch64ISD::CMHI
, dl
, VT
, RHS
, LHS
);
7844 return DAG
.getNode(AArch64ISD::CMLTz
, dl
, VT
, LHS
);
7845 return DAG
.getNode(AArch64ISD::CMGT
, dl
, VT
, RHS
, LHS
);
7847 return DAG
.getNode(AArch64ISD::CMHI
, dl
, VT
, LHS
, RHS
);
7849 return DAG
.getNode(AArch64ISD::CMHS
, dl
, VT
, LHS
, RHS
);
7853 SDValue
AArch64TargetLowering::LowerVSETCC(SDValue Op
,
7854 SelectionDAG
&DAG
) const {
7855 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
7856 SDValue LHS
= Op
.getOperand(0);
7857 SDValue RHS
= Op
.getOperand(1);
7858 EVT CmpVT
= LHS
.getValueType().changeVectorElementTypeToInteger();
7861 if (LHS
.getValueType().getVectorElementType().isInteger()) {
7862 assert(LHS
.getValueType() == RHS
.getValueType());
7863 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
7865 EmitVectorComparison(LHS
, RHS
, AArch64CC
, false, CmpVT
, dl
, DAG
);
7866 return DAG
.getSExtOrTrunc(Cmp
, dl
, Op
.getValueType());
7869 const bool FullFP16
=
7870 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
7872 // Make v4f16 (only) fcmp operations utilise vector instructions
7873 // v8f16 support will be a litle more complicated
7874 if (!FullFP16
&& LHS
.getValueType().getVectorElementType() == MVT::f16
) {
7875 if (LHS
.getValueType().getVectorNumElements() == 4) {
7876 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::v4f32
, LHS
);
7877 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::v4f32
, RHS
);
7878 SDValue NewSetcc
= DAG
.getSetCC(dl
, MVT::v4i16
, LHS
, RHS
, CC
);
7879 DAG
.ReplaceAllUsesWith(Op
, NewSetcc
);
7885 assert((!FullFP16
&& LHS
.getValueType().getVectorElementType() != MVT::f16
) ||
7886 LHS
.getValueType().getVectorElementType() != MVT::f128
);
7888 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7889 // clean. Some of them require two branches to implement.
7890 AArch64CC::CondCode CC1
, CC2
;
7892 changeVectorFPCCToAArch64CC(CC
, CC1
, CC2
, ShouldInvert
);
7894 bool NoNaNs
= getTargetMachine().Options
.NoNaNsFPMath
;
7896 EmitVectorComparison(LHS
, RHS
, CC1
, NoNaNs
, CmpVT
, dl
, DAG
);
7900 if (CC2
!= AArch64CC::AL
) {
7902 EmitVectorComparison(LHS
, RHS
, CC2
, NoNaNs
, CmpVT
, dl
, DAG
);
7903 if (!Cmp2
.getNode())
7906 Cmp
= DAG
.getNode(ISD::OR
, dl
, CmpVT
, Cmp
, Cmp2
);
7909 Cmp
= DAG
.getSExtOrTrunc(Cmp
, dl
, Op
.getValueType());
7912 Cmp
= DAG
.getNOT(dl
, Cmp
, Cmp
.getValueType());
7917 static SDValue
getReductionSDNode(unsigned Op
, SDLoc DL
, SDValue ScalarOp
,
7918 SelectionDAG
&DAG
) {
7919 SDValue VecOp
= ScalarOp
.getOperand(0);
7920 auto Rdx
= DAG
.getNode(Op
, DL
, VecOp
.getSimpleValueType(), VecOp
);
7921 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ScalarOp
.getValueType(), Rdx
,
7922 DAG
.getConstant(0, DL
, MVT::i64
));
7925 SDValue
AArch64TargetLowering::LowerVECREDUCE(SDValue Op
,
7926 SelectionDAG
&DAG
) const {
7928 switch (Op
.getOpcode()) {
7929 case ISD::VECREDUCE_ADD
:
7930 return getReductionSDNode(AArch64ISD::UADDV
, dl
, Op
, DAG
);
7931 case ISD::VECREDUCE_SMAX
:
7932 return getReductionSDNode(AArch64ISD::SMAXV
, dl
, Op
, DAG
);
7933 case ISD::VECREDUCE_SMIN
:
7934 return getReductionSDNode(AArch64ISD::SMINV
, dl
, Op
, DAG
);
7935 case ISD::VECREDUCE_UMAX
:
7936 return getReductionSDNode(AArch64ISD::UMAXV
, dl
, Op
, DAG
);
7937 case ISD::VECREDUCE_UMIN
:
7938 return getReductionSDNode(AArch64ISD::UMINV
, dl
, Op
, DAG
);
7939 case ISD::VECREDUCE_FMAX
: {
7940 assert(Op
->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7942 ISD::INTRINSIC_WO_CHAIN
, dl
, Op
.getValueType(),
7943 DAG
.getConstant(Intrinsic::aarch64_neon_fmaxnmv
, dl
, MVT::i32
),
7946 case ISD::VECREDUCE_FMIN
: {
7947 assert(Op
->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7949 ISD::INTRINSIC_WO_CHAIN
, dl
, Op
.getValueType(),
7950 DAG
.getConstant(Intrinsic::aarch64_neon_fminnmv
, dl
, MVT::i32
),
7954 llvm_unreachable("Unhandled reduction");
7958 SDValue
AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op
,
7959 SelectionDAG
&DAG
) const {
7960 auto &Subtarget
= static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget());
7961 if (!Subtarget
.hasLSE())
7964 // LSE has an atomic load-add instruction, but not a load-sub.
7966 MVT VT
= Op
.getSimpleValueType();
7967 SDValue RHS
= Op
.getOperand(2);
7968 AtomicSDNode
*AN
= cast
<AtomicSDNode
>(Op
.getNode());
7969 RHS
= DAG
.getNode(ISD::SUB
, dl
, VT
, DAG
.getConstant(0, dl
, VT
), RHS
);
7970 return DAG
.getAtomic(ISD::ATOMIC_LOAD_ADD
, dl
, AN
->getMemoryVT(),
7971 Op
.getOperand(0), Op
.getOperand(1), RHS
,
7972 AN
->getMemOperand());
7975 SDValue
AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op
,
7976 SelectionDAG
&DAG
) const {
7977 auto &Subtarget
= static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget());
7978 if (!Subtarget
.hasLSE())
7981 // LSE has an atomic load-clear instruction, but not a load-and.
7983 MVT VT
= Op
.getSimpleValueType();
7984 SDValue RHS
= Op
.getOperand(2);
7985 AtomicSDNode
*AN
= cast
<AtomicSDNode
>(Op
.getNode());
7986 RHS
= DAG
.getNode(ISD::XOR
, dl
, VT
, DAG
.getConstant(-1ULL, dl
, VT
), RHS
);
7987 return DAG
.getAtomic(ISD::ATOMIC_LOAD_CLR
, dl
, AN
->getMemoryVT(),
7988 Op
.getOperand(0), Op
.getOperand(1), RHS
,
7989 AN
->getMemOperand());
7992 SDValue
AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7993 SDValue Op
, SDValue Chain
, SDValue
&Size
, SelectionDAG
&DAG
) const {
7995 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
7996 SDValue Callee
= DAG
.getTargetExternalSymbol("__chkstk", PtrVT
, 0);
7998 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
7999 const uint32_t *Mask
= TRI
->getWindowsStackProbePreservedMask();
8000 if (Subtarget
->hasCustomCallingConv())
8001 TRI
->UpdateCustomCallPreservedMask(DAG
.getMachineFunction(), &Mask
);
8003 Size
= DAG
.getNode(ISD::SRL
, dl
, MVT::i64
, Size
,
8004 DAG
.getConstant(4, dl
, MVT::i64
));
8005 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::X15
, Size
, SDValue());
8007 DAG
.getNode(AArch64ISD::CALL
, dl
, DAG
.getVTList(MVT::Other
, MVT::Glue
),
8008 Chain
, Callee
, DAG
.getRegister(AArch64::X15
, MVT::i64
),
8009 DAG
.getRegisterMask(Mask
), Chain
.getValue(1));
8010 // To match the actual intent better, we should read the output from X15 here
8011 // again (instead of potentially spilling it to the stack), but rereading Size
8012 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8015 Size
= DAG
.getNode(ISD::SHL
, dl
, MVT::i64
, Size
,
8016 DAG
.getConstant(4, dl
, MVT::i64
));
8021 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op
,
8022 SelectionDAG
&DAG
) const {
8023 assert(Subtarget
->isTargetWindows() &&
8024 "Only Windows alloca probing supported");
8027 SDNode
*Node
= Op
.getNode();
8028 SDValue Chain
= Op
.getOperand(0);
8029 SDValue Size
= Op
.getOperand(1);
8030 unsigned Align
= cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue();
8031 EVT VT
= Node
->getValueType(0);
8033 if (DAG
.getMachineFunction().getFunction().hasFnAttribute(
8034 "no-stack-arg-probe")) {
8035 SDValue SP
= DAG
.getCopyFromReg(Chain
, dl
, AArch64::SP
, MVT::i64
);
8036 Chain
= SP
.getValue(1);
8037 SP
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, SP
, Size
);
8039 SP
= DAG
.getNode(ISD::AND
, dl
, VT
, SP
.getValue(0),
8040 DAG
.getConstant(-(uint64_t)Align
, dl
, VT
));
8041 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::SP
, SP
);
8042 SDValue Ops
[2] = {SP
, Chain
};
8043 return DAG
.getMergeValues(Ops
, dl
);
8046 Chain
= DAG
.getCALLSEQ_START(Chain
, 0, 0, dl
);
8048 Chain
= LowerWindowsDYNAMIC_STACKALLOC(Op
, Chain
, Size
, DAG
);
8050 SDValue SP
= DAG
.getCopyFromReg(Chain
, dl
, AArch64::SP
, MVT::i64
);
8051 Chain
= SP
.getValue(1);
8052 SP
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, SP
, Size
);
8054 SP
= DAG
.getNode(ISD::AND
, dl
, VT
, SP
.getValue(0),
8055 DAG
.getConstant(-(uint64_t)Align
, dl
, VT
));
8056 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::SP
, SP
);
8058 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(0, dl
, true),
8059 DAG
.getIntPtrConstant(0, dl
, true), SDValue(), dl
);
8061 SDValue Ops
[2] = {SP
, Chain
};
8062 return DAG
.getMergeValues(Ops
, dl
);
8065 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8066 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8067 /// specified in the intrinsic calls.
8068 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo
&Info
,
8070 MachineFunction
&MF
,
8071 unsigned Intrinsic
) const {
8072 auto &DL
= I
.getModule()->getDataLayout();
8073 switch (Intrinsic
) {
8074 case Intrinsic::aarch64_neon_ld2
:
8075 case Intrinsic::aarch64_neon_ld3
:
8076 case Intrinsic::aarch64_neon_ld4
:
8077 case Intrinsic::aarch64_neon_ld1x2
:
8078 case Intrinsic::aarch64_neon_ld1x3
:
8079 case Intrinsic::aarch64_neon_ld1x4
:
8080 case Intrinsic::aarch64_neon_ld2lane
:
8081 case Intrinsic::aarch64_neon_ld3lane
:
8082 case Intrinsic::aarch64_neon_ld4lane
:
8083 case Intrinsic::aarch64_neon_ld2r
:
8084 case Intrinsic::aarch64_neon_ld3r
:
8085 case Intrinsic::aarch64_neon_ld4r
: {
8086 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8087 // Conservatively set memVT to the entire set of vectors loaded.
8088 uint64_t NumElts
= DL
.getTypeSizeInBits(I
.getType()) / 64;
8089 Info
.memVT
= EVT::getVectorVT(I
.getType()->getContext(), MVT::i64
, NumElts
);
8090 Info
.ptrVal
= I
.getArgOperand(I
.getNumArgOperands() - 1);
8093 // volatile loads with NEON intrinsics not supported
8094 Info
.flags
= MachineMemOperand::MOLoad
;
8097 case Intrinsic::aarch64_neon_st2
:
8098 case Intrinsic::aarch64_neon_st3
:
8099 case Intrinsic::aarch64_neon_st4
:
8100 case Intrinsic::aarch64_neon_st1x2
:
8101 case Intrinsic::aarch64_neon_st1x3
:
8102 case Intrinsic::aarch64_neon_st1x4
:
8103 case Intrinsic::aarch64_neon_st2lane
:
8104 case Intrinsic::aarch64_neon_st3lane
:
8105 case Intrinsic::aarch64_neon_st4lane
: {
8106 Info
.opc
= ISD::INTRINSIC_VOID
;
8107 // Conservatively set memVT to the entire set of vectors stored.
8108 unsigned NumElts
= 0;
8109 for (unsigned ArgI
= 0, ArgE
= I
.getNumArgOperands(); ArgI
< ArgE
; ++ArgI
) {
8110 Type
*ArgTy
= I
.getArgOperand(ArgI
)->getType();
8111 if (!ArgTy
->isVectorTy())
8113 NumElts
+= DL
.getTypeSizeInBits(ArgTy
) / 64;
8115 Info
.memVT
= EVT::getVectorVT(I
.getType()->getContext(), MVT::i64
, NumElts
);
8116 Info
.ptrVal
= I
.getArgOperand(I
.getNumArgOperands() - 1);
8119 // volatile stores with NEON intrinsics not supported
8120 Info
.flags
= MachineMemOperand::MOStore
;
8123 case Intrinsic::aarch64_ldaxr
:
8124 case Intrinsic::aarch64_ldxr
: {
8125 PointerType
*PtrTy
= cast
<PointerType
>(I
.getArgOperand(0)->getType());
8126 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8127 Info
.memVT
= MVT::getVT(PtrTy
->getElementType());
8128 Info
.ptrVal
= I
.getArgOperand(0);
8130 Info
.align
= DL
.getABITypeAlignment(PtrTy
->getElementType());
8131 Info
.flags
= MachineMemOperand::MOLoad
| MachineMemOperand::MOVolatile
;
8134 case Intrinsic::aarch64_stlxr
:
8135 case Intrinsic::aarch64_stxr
: {
8136 PointerType
*PtrTy
= cast
<PointerType
>(I
.getArgOperand(1)->getType());
8137 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8138 Info
.memVT
= MVT::getVT(PtrTy
->getElementType());
8139 Info
.ptrVal
= I
.getArgOperand(1);
8141 Info
.align
= DL
.getABITypeAlignment(PtrTy
->getElementType());
8142 Info
.flags
= MachineMemOperand::MOStore
| MachineMemOperand::MOVolatile
;
8145 case Intrinsic::aarch64_ldaxp
:
8146 case Intrinsic::aarch64_ldxp
:
8147 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8148 Info
.memVT
= MVT::i128
;
8149 Info
.ptrVal
= I
.getArgOperand(0);
8152 Info
.flags
= MachineMemOperand::MOLoad
| MachineMemOperand::MOVolatile
;
8154 case Intrinsic::aarch64_stlxp
:
8155 case Intrinsic::aarch64_stxp
:
8156 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8157 Info
.memVT
= MVT::i128
;
8158 Info
.ptrVal
= I
.getArgOperand(2);
8161 Info
.flags
= MachineMemOperand::MOStore
| MachineMemOperand::MOVolatile
;
8170 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode
*Load
,
8171 ISD::LoadExtType ExtTy
,
8173 // TODO: This may be worth removing. Check regression tests for diffs.
8174 if (!TargetLoweringBase::shouldReduceLoadWidth(Load
, ExtTy
, NewVT
))
8177 // If we're reducing the load width in order to avoid having to use an extra
8178 // instruction to do extension then it's probably a good idea.
8179 if (ExtTy
!= ISD::NON_EXTLOAD
)
8181 // Don't reduce load width if it would prevent us from combining a shift into
8183 MemSDNode
*Mem
= dyn_cast
<MemSDNode
>(Load
);
8185 const SDValue
&Base
= Mem
->getBasePtr();
8186 if (Base
.getOpcode() == ISD::ADD
&&
8187 Base
.getOperand(1).getOpcode() == ISD::SHL
&&
8188 Base
.getOperand(1).hasOneUse() &&
8189 Base
.getOperand(1).getOperand(1).getOpcode() == ISD::Constant
) {
8190 // The shift can be combined if it matches the size of the value being
8191 // loaded (and so reducing the width would make it not match).
8192 uint64_t ShiftAmount
= Base
.getOperand(1).getConstantOperandVal(1);
8193 uint64_t LoadBytes
= Mem
->getMemoryVT().getSizeInBits()/8;
8194 if (ShiftAmount
== Log2_32(LoadBytes
))
8197 // We have no reason to disallow reducing the load width, so allow it.
8201 // Truncations from 64-bit GPR to 32-bit GPR is free.
8202 bool AArch64TargetLowering::isTruncateFree(Type
*Ty1
, Type
*Ty2
) const {
8203 if (!Ty1
->isIntegerTy() || !Ty2
->isIntegerTy())
8205 unsigned NumBits1
= Ty1
->getPrimitiveSizeInBits();
8206 unsigned NumBits2
= Ty2
->getPrimitiveSizeInBits();
8207 return NumBits1
> NumBits2
;
8209 bool AArch64TargetLowering::isTruncateFree(EVT VT1
, EVT VT2
) const {
8210 if (VT1
.isVector() || VT2
.isVector() || !VT1
.isInteger() || !VT2
.isInteger())
8212 unsigned NumBits1
= VT1
.getSizeInBits();
8213 unsigned NumBits2
= VT2
.getSizeInBits();
8214 return NumBits1
> NumBits2
;
8217 /// Check if it is profitable to hoist instruction in then/else to if.
8218 /// Not profitable if I and it's user can form a FMA instruction
8219 /// because we prefer FMSUB/FMADD.
8220 bool AArch64TargetLowering::isProfitableToHoist(Instruction
*I
) const {
8221 if (I
->getOpcode() != Instruction::FMul
)
8224 if (!I
->hasOneUse())
8227 Instruction
*User
= I
->user_back();
8230 !(User
->getOpcode() == Instruction::FSub
||
8231 User
->getOpcode() == Instruction::FAdd
))
8234 const TargetOptions
&Options
= getTargetMachine().Options
;
8235 const DataLayout
&DL
= I
->getModule()->getDataLayout();
8236 EVT VT
= getValueType(DL
, User
->getOperand(0)->getType());
8238 return !(isFMAFasterThanFMulAndFAdd(VT
) &&
8239 isOperationLegalOrCustom(ISD::FMA
, VT
) &&
8240 (Options
.AllowFPOpFusion
== FPOpFusion::Fast
||
8241 Options
.UnsafeFPMath
));
8244 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8246 bool AArch64TargetLowering::isZExtFree(Type
*Ty1
, Type
*Ty2
) const {
8247 if (!Ty1
->isIntegerTy() || !Ty2
->isIntegerTy())
8249 unsigned NumBits1
= Ty1
->getPrimitiveSizeInBits();
8250 unsigned NumBits2
= Ty2
->getPrimitiveSizeInBits();
8251 return NumBits1
== 32 && NumBits2
== 64;
8253 bool AArch64TargetLowering::isZExtFree(EVT VT1
, EVT VT2
) const {
8254 if (VT1
.isVector() || VT2
.isVector() || !VT1
.isInteger() || !VT2
.isInteger())
8256 unsigned NumBits1
= VT1
.getSizeInBits();
8257 unsigned NumBits2
= VT2
.getSizeInBits();
8258 return NumBits1
== 32 && NumBits2
== 64;
8261 bool AArch64TargetLowering::isZExtFree(SDValue Val
, EVT VT2
) const {
8262 EVT VT1
= Val
.getValueType();
8263 if (isZExtFree(VT1
, VT2
)) {
8267 if (Val
.getOpcode() != ISD::LOAD
)
8270 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8271 return (VT1
.isSimple() && !VT1
.isVector() && VT1
.isInteger() &&
8272 VT2
.isSimple() && !VT2
.isVector() && VT2
.isInteger() &&
8273 VT1
.getSizeInBits() <= 32);
8276 bool AArch64TargetLowering::isExtFreeImpl(const Instruction
*Ext
) const {
8277 if (isa
<FPExtInst
>(Ext
))
8280 // Vector types are not free.
8281 if (Ext
->getType()->isVectorTy())
8284 for (const Use
&U
: Ext
->uses()) {
8285 // The extension is free if we can fold it with a left shift in an
8286 // addressing mode or an arithmetic operation: add, sub, and cmp.
8288 // Is there a shift?
8289 const Instruction
*Instr
= cast
<Instruction
>(U
.getUser());
8291 // Is this a constant shift?
8292 switch (Instr
->getOpcode()) {
8293 case Instruction::Shl
:
8294 if (!isa
<ConstantInt
>(Instr
->getOperand(1)))
8297 case Instruction::GetElementPtr
: {
8298 gep_type_iterator GTI
= gep_type_begin(Instr
);
8299 auto &DL
= Ext
->getModule()->getDataLayout();
8300 std::advance(GTI
, U
.getOperandNo()-1);
8301 Type
*IdxTy
= GTI
.getIndexedType();
8302 // This extension will end up with a shift because of the scaling factor.
8303 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8304 // Get the shift amount based on the scaling factor:
8305 // log2(sizeof(IdxTy)) - log2(8).
8307 countTrailingZeros(DL
.getTypeStoreSizeInBits(IdxTy
)) - 3;
8308 // Is the constant foldable in the shift of the addressing mode?
8309 // I.e., shift amount is between 1 and 4 inclusive.
8310 if (ShiftAmt
== 0 || ShiftAmt
> 4)
8314 case Instruction::Trunc
:
8315 // Check if this is a noop.
8316 // trunc(sext ty1 to ty2) to ty1.
8317 if (Instr
->getType() == Ext
->getOperand(0)->getType())
8324 // At this point we can use the bfm family, so this extension is free
8330 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8331 /// or upper half of the vector elements.
8332 static bool areExtractShuffleVectors(Value
*Op1
, Value
*Op2
) {
8333 auto areTypesHalfed
= [](Value
*FullV
, Value
*HalfV
) {
8334 auto *FullVT
= cast
<VectorType
>(FullV
->getType());
8335 auto *HalfVT
= cast
<VectorType
>(HalfV
->getType());
8336 return FullVT
->getBitWidth() == 2 * HalfVT
->getBitWidth();
8339 auto extractHalf
= [](Value
*FullV
, Value
*HalfV
) {
8340 auto *FullVT
= cast
<VectorType
>(FullV
->getType());
8341 auto *HalfVT
= cast
<VectorType
>(HalfV
->getType());
8342 return FullVT
->getNumElements() == 2 * HalfVT
->getNumElements();
8346 Value
*S1Op1
, *S2Op1
;
8347 if (!match(Op1
, m_ShuffleVector(m_Value(S1Op1
), m_Undef(), m_Constant(M1
))) ||
8348 !match(Op2
, m_ShuffleVector(m_Value(S2Op1
), m_Undef(), m_Constant(M2
))))
8351 // Check that the operands are half as wide as the result and we extract
8352 // half of the elements of the input vectors.
8353 if (!areTypesHalfed(S1Op1
, Op1
) || !areTypesHalfed(S2Op1
, Op2
) ||
8354 !extractHalf(S1Op1
, Op1
) || !extractHalf(S2Op1
, Op2
))
8357 // Check the mask extracts either the lower or upper half of vector
8361 int NumElements
= cast
<VectorType
>(Op1
->getType())->getNumElements() * 2;
8362 if (!ShuffleVectorInst::isExtractSubvectorMask(M1
, NumElements
, M1Start
) ||
8363 !ShuffleVectorInst::isExtractSubvectorMask(M2
, NumElements
, M2Start
) ||
8364 M1Start
!= M2Start
|| (M1Start
!= 0 && M2Start
!= (NumElements
/ 2)))
8370 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8371 /// of the vector elements.
8372 static bool areExtractExts(Value
*Ext1
, Value
*Ext2
) {
8373 auto areExtDoubled
= [](Instruction
*Ext
) {
8374 return Ext
->getType()->getScalarSizeInBits() ==
8375 2 * Ext
->getOperand(0)->getType()->getScalarSizeInBits();
8378 if (!match(Ext1
, m_ZExtOrSExt(m_Value())) ||
8379 !match(Ext2
, m_ZExtOrSExt(m_Value())) ||
8380 !areExtDoubled(cast
<Instruction
>(Ext1
)) ||
8381 !areExtDoubled(cast
<Instruction
>(Ext2
)))
8387 /// Check if sinking \p I's operands to I's basic block is profitable, because
8388 /// the operands can be folded into a target instruction, e.g.
8389 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8390 bool AArch64TargetLowering::shouldSinkOperands(
8391 Instruction
*I
, SmallVectorImpl
<Use
*> &Ops
) const {
8392 if (!I
->getType()->isVectorTy())
8395 if (IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(I
)) {
8396 switch (II
->getIntrinsicID()) {
8397 case Intrinsic::aarch64_neon_umull
:
8398 if (!areExtractShuffleVectors(II
->getOperand(0), II
->getOperand(1)))
8400 Ops
.push_back(&II
->getOperandUse(0));
8401 Ops
.push_back(&II
->getOperandUse(1));
8408 switch (I
->getOpcode()) {
8409 case Instruction::Sub
:
8410 case Instruction::Add
: {
8411 if (!areExtractExts(I
->getOperand(0), I
->getOperand(1)))
8414 // If the exts' operands extract either the lower or upper elements, we
8415 // can sink them too.
8416 auto Ext1
= cast
<Instruction
>(I
->getOperand(0));
8417 auto Ext2
= cast
<Instruction
>(I
->getOperand(1));
8418 if (areExtractShuffleVectors(Ext1
, Ext2
)) {
8419 Ops
.push_back(&Ext1
->getOperandUse(0));
8420 Ops
.push_back(&Ext2
->getOperandUse(0));
8423 Ops
.push_back(&I
->getOperandUse(0));
8424 Ops
.push_back(&I
->getOperandUse(1));
8434 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType
,
8435 unsigned &RequiredAligment
) const {
8436 if (!LoadedType
.isSimple() ||
8437 (!LoadedType
.isInteger() && !LoadedType
.isFloatingPoint()))
8439 // Cyclone supports unaligned accesses.
8440 RequiredAligment
= 0;
8441 unsigned NumBits
= LoadedType
.getSizeInBits();
8442 return NumBits
== 32 || NumBits
== 64;
8445 /// A helper function for determining the number of interleaved accesses we
8446 /// will generate when lowering accesses of the given type.
8448 AArch64TargetLowering::getNumInterleavedAccesses(VectorType
*VecTy
,
8449 const DataLayout
&DL
) const {
8450 return (DL
.getTypeSizeInBits(VecTy
) + 127) / 128;
8453 MachineMemOperand::Flags
8454 AArch64TargetLowering::getMMOFlags(const Instruction
&I
) const {
8455 if (Subtarget
->getProcFamily() == AArch64Subtarget::Falkor
&&
8456 I
.getMetadata(FALKOR_STRIDED_ACCESS_MD
) != nullptr)
8457 return MOStridedAccess
;
8458 return MachineMemOperand::MONone
;
8461 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8462 VectorType
*VecTy
, const DataLayout
&DL
) const {
8464 unsigned VecSize
= DL
.getTypeSizeInBits(VecTy
);
8465 unsigned ElSize
= DL
.getTypeSizeInBits(VecTy
->getElementType());
8467 // Ensure the number of vector elements is greater than 1.
8468 if (VecTy
->getNumElements() < 2)
8471 // Ensure the element type is legal.
8472 if (ElSize
!= 8 && ElSize
!= 16 && ElSize
!= 32 && ElSize
!= 64)
8475 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8476 // 128 will be split into multiple interleaved accesses.
8477 return VecSize
== 64 || VecSize
% 128 == 0;
8480 /// Lower an interleaved load into a ldN intrinsic.
8482 /// E.g. Lower an interleaved load (Factor = 2):
8483 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8484 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8485 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8488 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8489 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8490 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8491 bool AArch64TargetLowering::lowerInterleavedLoad(
8492 LoadInst
*LI
, ArrayRef
<ShuffleVectorInst
*> Shuffles
,
8493 ArrayRef
<unsigned> Indices
, unsigned Factor
) const {
8494 assert(Factor
>= 2 && Factor
<= getMaxSupportedInterleaveFactor() &&
8495 "Invalid interleave factor");
8496 assert(!Shuffles
.empty() && "Empty shufflevector input");
8497 assert(Shuffles
.size() == Indices
.size() &&
8498 "Unmatched number of shufflevectors and indices");
8500 const DataLayout
&DL
= LI
->getModule()->getDataLayout();
8502 VectorType
*VecTy
= Shuffles
[0]->getType();
8504 // Skip if we do not have NEON and skip illegal vector types. We can
8505 // "legalize" wide vector types into multiple interleaved accesses as long as
8506 // the vector types are divisible by 128.
8507 if (!Subtarget
->hasNEON() || !isLegalInterleavedAccessType(VecTy
, DL
))
8510 unsigned NumLoads
= getNumInterleavedAccesses(VecTy
, DL
);
8512 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8513 // load integer vectors first and then convert to pointer vectors.
8514 Type
*EltTy
= VecTy
->getVectorElementType();
8515 if (EltTy
->isPointerTy())
8517 VectorType::get(DL
.getIntPtrType(EltTy
), VecTy
->getVectorNumElements());
8519 IRBuilder
<> Builder(LI
);
8521 // The base address of the load.
8522 Value
*BaseAddr
= LI
->getPointerOperand();
8525 // If we're going to generate more than one load, reset the sub-vector type
8526 // to something legal.
8527 VecTy
= VectorType::get(VecTy
->getVectorElementType(),
8528 VecTy
->getVectorNumElements() / NumLoads
);
8530 // We will compute the pointer operand of each load from the original base
8531 // address using GEPs. Cast the base address to a pointer to the scalar
8533 BaseAddr
= Builder
.CreateBitCast(
8534 BaseAddr
, VecTy
->getVectorElementType()->getPointerTo(
8535 LI
->getPointerAddressSpace()));
8538 Type
*PtrTy
= VecTy
->getPointerTo(LI
->getPointerAddressSpace());
8539 Type
*Tys
[2] = {VecTy
, PtrTy
};
8540 static const Intrinsic::ID LoadInts
[3] = {Intrinsic::aarch64_neon_ld2
,
8541 Intrinsic::aarch64_neon_ld3
,
8542 Intrinsic::aarch64_neon_ld4
};
8544 Intrinsic::getDeclaration(LI
->getModule(), LoadInts
[Factor
- 2], Tys
);
8546 // Holds sub-vectors extracted from the load intrinsic return values. The
8547 // sub-vectors are associated with the shufflevector instructions they will
8549 DenseMap
<ShuffleVectorInst
*, SmallVector
<Value
*, 4>> SubVecs
;
8551 for (unsigned LoadCount
= 0; LoadCount
< NumLoads
; ++LoadCount
) {
8553 // If we're generating more than one load, compute the base address of
8554 // subsequent loads as an offset from the previous.
8557 Builder
.CreateConstGEP1_32(VecTy
->getVectorElementType(), BaseAddr
,
8558 VecTy
->getVectorNumElements() * Factor
);
8560 CallInst
*LdN
= Builder
.CreateCall(
8561 LdNFunc
, Builder
.CreateBitCast(BaseAddr
, PtrTy
), "ldN");
8563 // Extract and store the sub-vectors returned by the load intrinsic.
8564 for (unsigned i
= 0; i
< Shuffles
.size(); i
++) {
8565 ShuffleVectorInst
*SVI
= Shuffles
[i
];
8566 unsigned Index
= Indices
[i
];
8568 Value
*SubVec
= Builder
.CreateExtractValue(LdN
, Index
);
8570 // Convert the integer vector to pointer vector if the element is pointer.
8571 if (EltTy
->isPointerTy())
8572 SubVec
= Builder
.CreateIntToPtr(
8573 SubVec
, VectorType::get(SVI
->getType()->getVectorElementType(),
8574 VecTy
->getVectorNumElements()));
8575 SubVecs
[SVI
].push_back(SubVec
);
8579 // Replace uses of the shufflevector instructions with the sub-vectors
8580 // returned by the load intrinsic. If a shufflevector instruction is
8581 // associated with more than one sub-vector, those sub-vectors will be
8582 // concatenated into a single wide vector.
8583 for (ShuffleVectorInst
*SVI
: Shuffles
) {
8584 auto &SubVec
= SubVecs
[SVI
];
8586 SubVec
.size() > 1 ? concatenateVectors(Builder
, SubVec
) : SubVec
[0];
8587 SVI
->replaceAllUsesWith(WideVec
);
8593 /// Lower an interleaved store into a stN intrinsic.
8595 /// E.g. Lower an interleaved store (Factor = 3):
8596 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8597 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8598 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8601 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8602 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8603 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8604 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8606 /// Note that the new shufflevectors will be removed and we'll only generate one
8607 /// st3 instruction in CodeGen.
8609 /// Example for a more general valid mask (Factor 3). Lower:
8610 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8611 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8612 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8615 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8616 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8617 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8618 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8619 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst
*SI
,
8620 ShuffleVectorInst
*SVI
,
8621 unsigned Factor
) const {
8622 assert(Factor
>= 2 && Factor
<= getMaxSupportedInterleaveFactor() &&
8623 "Invalid interleave factor");
8625 VectorType
*VecTy
= SVI
->getType();
8626 assert(VecTy
->getVectorNumElements() % Factor
== 0 &&
8627 "Invalid interleaved store");
8629 unsigned LaneLen
= VecTy
->getVectorNumElements() / Factor
;
8630 Type
*EltTy
= VecTy
->getVectorElementType();
8631 VectorType
*SubVecTy
= VectorType::get(EltTy
, LaneLen
);
8633 const DataLayout
&DL
= SI
->getModule()->getDataLayout();
8635 // Skip if we do not have NEON and skip illegal vector types. We can
8636 // "legalize" wide vector types into multiple interleaved accesses as long as
8637 // the vector types are divisible by 128.
8638 if (!Subtarget
->hasNEON() || !isLegalInterleavedAccessType(SubVecTy
, DL
))
8641 unsigned NumStores
= getNumInterleavedAccesses(SubVecTy
, DL
);
8643 Value
*Op0
= SVI
->getOperand(0);
8644 Value
*Op1
= SVI
->getOperand(1);
8645 IRBuilder
<> Builder(SI
);
8647 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8648 // vectors to integer vectors.
8649 if (EltTy
->isPointerTy()) {
8650 Type
*IntTy
= DL
.getIntPtrType(EltTy
);
8651 unsigned NumOpElts
= Op0
->getType()->getVectorNumElements();
8653 // Convert to the corresponding integer vector.
8654 Type
*IntVecTy
= VectorType::get(IntTy
, NumOpElts
);
8655 Op0
= Builder
.CreatePtrToInt(Op0
, IntVecTy
);
8656 Op1
= Builder
.CreatePtrToInt(Op1
, IntVecTy
);
8658 SubVecTy
= VectorType::get(IntTy
, LaneLen
);
8661 // The base address of the store.
8662 Value
*BaseAddr
= SI
->getPointerOperand();
8664 if (NumStores
> 1) {
8665 // If we're going to generate more than one store, reset the lane length
8666 // and sub-vector type to something legal.
8667 LaneLen
/= NumStores
;
8668 SubVecTy
= VectorType::get(SubVecTy
->getVectorElementType(), LaneLen
);
8670 // We will compute the pointer operand of each store from the original base
8671 // address using GEPs. Cast the base address to a pointer to the scalar
8673 BaseAddr
= Builder
.CreateBitCast(
8674 BaseAddr
, SubVecTy
->getVectorElementType()->getPointerTo(
8675 SI
->getPointerAddressSpace()));
8678 auto Mask
= SVI
->getShuffleMask();
8680 Type
*PtrTy
= SubVecTy
->getPointerTo(SI
->getPointerAddressSpace());
8681 Type
*Tys
[2] = {SubVecTy
, PtrTy
};
8682 static const Intrinsic::ID StoreInts
[3] = {Intrinsic::aarch64_neon_st2
,
8683 Intrinsic::aarch64_neon_st3
,
8684 Intrinsic::aarch64_neon_st4
};
8686 Intrinsic::getDeclaration(SI
->getModule(), StoreInts
[Factor
- 2], Tys
);
8688 for (unsigned StoreCount
= 0; StoreCount
< NumStores
; ++StoreCount
) {
8690 SmallVector
<Value
*, 5> Ops
;
8692 // Split the shufflevector operands into sub vectors for the new stN call.
8693 for (unsigned i
= 0; i
< Factor
; i
++) {
8694 unsigned IdxI
= StoreCount
* LaneLen
* Factor
+ i
;
8695 if (Mask
[IdxI
] >= 0) {
8696 Ops
.push_back(Builder
.CreateShuffleVector(
8697 Op0
, Op1
, createSequentialMask(Builder
, Mask
[IdxI
], LaneLen
, 0)));
8699 unsigned StartMask
= 0;
8700 for (unsigned j
= 1; j
< LaneLen
; j
++) {
8701 unsigned IdxJ
= StoreCount
* LaneLen
* Factor
+ j
;
8702 if (Mask
[IdxJ
* Factor
+ IdxI
] >= 0) {
8703 StartMask
= Mask
[IdxJ
* Factor
+ IdxI
] - IdxJ
;
8707 // Note: Filling undef gaps with random elements is ok, since
8708 // those elements were being written anyway (with undefs).
8709 // In the case of all undefs we're defaulting to using elems from 0
8710 // Note: StartMask cannot be negative, it's checked in
8711 // isReInterleaveMask
8712 Ops
.push_back(Builder
.CreateShuffleVector(
8713 Op0
, Op1
, createSequentialMask(Builder
, StartMask
, LaneLen
, 0)));
8717 // If we generating more than one store, we compute the base address of
8718 // subsequent stores as an offset from the previous.
8720 BaseAddr
= Builder
.CreateConstGEP1_32(SubVecTy
->getVectorElementType(),
8721 BaseAddr
, LaneLen
* Factor
);
8723 Ops
.push_back(Builder
.CreateBitCast(BaseAddr
, PtrTy
));
8724 Builder
.CreateCall(StNFunc
, Ops
);
8729 static bool memOpAlign(unsigned DstAlign
, unsigned SrcAlign
,
8730 unsigned AlignCheck
) {
8731 return ((SrcAlign
== 0 || SrcAlign
% AlignCheck
== 0) &&
8732 (DstAlign
== 0 || DstAlign
% AlignCheck
== 0));
8735 EVT
AArch64TargetLowering::getOptimalMemOpType(
8736 uint64_t Size
, unsigned DstAlign
, unsigned SrcAlign
, bool IsMemset
,
8737 bool ZeroMemset
, bool MemcpyStrSrc
,
8738 const AttributeList
&FuncAttributes
) const {
8739 bool CanImplicitFloat
=
8740 !FuncAttributes
.hasFnAttribute(Attribute::NoImplicitFloat
);
8741 bool CanUseNEON
= Subtarget
->hasNEON() && CanImplicitFloat
;
8742 bool CanUseFP
= Subtarget
->hasFPARMv8() && CanImplicitFloat
;
8743 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8744 // taken one instruction to materialize the v2i64 zero and one store (with
8745 // restrictive addressing mode). Just do i64 stores.
8746 bool IsSmallMemset
= IsMemset
&& Size
< 32;
8747 auto AlignmentIsAcceptable
= [&](EVT VT
, unsigned AlignCheck
) {
8748 if (memOpAlign(SrcAlign
, DstAlign
, AlignCheck
))
8751 return allowsMisalignedMemoryAccesses(VT
, 0, 1, MachineMemOperand::MONone
,
8756 if (CanUseNEON
&& IsMemset
&& !IsSmallMemset
&&
8757 AlignmentIsAcceptable(MVT::v2i64
, 16))
8759 if (CanUseFP
&& !IsSmallMemset
&& AlignmentIsAcceptable(MVT::f128
, 16))
8761 if (Size
>= 8 && AlignmentIsAcceptable(MVT::i64
, 8))
8763 if (Size
>= 4 && AlignmentIsAcceptable(MVT::i32
, 4))
8768 LLT
AArch64TargetLowering::getOptimalMemOpLLT(
8769 uint64_t Size
, unsigned DstAlign
, unsigned SrcAlign
, bool IsMemset
,
8770 bool ZeroMemset
, bool MemcpyStrSrc
,
8771 const AttributeList
&FuncAttributes
) const {
8772 bool CanImplicitFloat
=
8773 !FuncAttributes
.hasFnAttribute(Attribute::NoImplicitFloat
);
8774 bool CanUseNEON
= Subtarget
->hasNEON() && CanImplicitFloat
;
8775 bool CanUseFP
= Subtarget
->hasFPARMv8() && CanImplicitFloat
;
8776 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8777 // taken one instruction to materialize the v2i64 zero and one store (with
8778 // restrictive addressing mode). Just do i64 stores.
8779 bool IsSmallMemset
= IsMemset
&& Size
< 32;
8780 auto AlignmentIsAcceptable
= [&](EVT VT
, unsigned AlignCheck
) {
8781 if (memOpAlign(SrcAlign
, DstAlign
, AlignCheck
))
8784 return allowsMisalignedMemoryAccesses(VT
, 0, 1, MachineMemOperand::MONone
,
8789 if (CanUseNEON
&& IsMemset
&& !IsSmallMemset
&&
8790 AlignmentIsAcceptable(MVT::v2i64
, 16))
8791 return LLT::vector(2, 64);
8792 if (CanUseFP
&& !IsSmallMemset
&& AlignmentIsAcceptable(MVT::f128
, 16))
8793 return LLT::scalar(128);
8794 if (Size
>= 8 && AlignmentIsAcceptable(MVT::i64
, 8))
8795 return LLT::scalar(64);
8796 if (Size
>= 4 && AlignmentIsAcceptable(MVT::i32
, 4))
8797 return LLT::scalar(32);
8801 // 12-bit optionally shifted immediates are legal for adds.
8802 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed
) const {
8803 if (Immed
== std::numeric_limits
<int64_t>::min()) {
8804 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8805 << ": avoid UB for INT64_MIN\n");
8808 // Same encoding for add/sub, just flip the sign.
8809 Immed
= std::abs(Immed
);
8810 bool IsLegal
= ((Immed
>> 12) == 0 ||
8811 ((Immed
& 0xfff) == 0 && Immed
>> 24 == 0));
8812 LLVM_DEBUG(dbgs() << "Is " << Immed
8813 << " legal add imm: " << (IsLegal
? "yes" : "no") << "\n");
8817 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8818 // immediates is the same as for an add or a sub.
8819 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed
) const {
8820 return isLegalAddImmediate(Immed
);
8823 /// isLegalAddressingMode - Return true if the addressing mode represented
8824 /// by AM is legal for this target, for a load/store of the specified type.
8825 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout
&DL
,
8826 const AddrMode
&AM
, Type
*Ty
,
8827 unsigned AS
, Instruction
*I
) const {
8828 // AArch64 has five basic addressing modes:
8830 // reg + 9-bit signed offset
8831 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8833 // reg + SIZE_IN_BYTES * reg
8835 // No global is ever allowed as a base.
8839 // No reg+reg+imm addressing.
8840 if (AM
.HasBaseReg
&& AM
.BaseOffs
&& AM
.Scale
)
8843 // check reg + imm case:
8844 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8845 uint64_t NumBytes
= 0;
8846 if (Ty
->isSized()) {
8847 uint64_t NumBits
= DL
.getTypeSizeInBits(Ty
);
8848 NumBytes
= NumBits
/ 8;
8849 if (!isPowerOf2_64(NumBits
))
8854 int64_t Offset
= AM
.BaseOffs
;
8856 // 9-bit signed offset
8857 if (isInt
<9>(Offset
))
8860 // 12-bit unsigned offset
8861 unsigned shift
= Log2_64(NumBytes
);
8862 if (NumBytes
&& Offset
> 0 && (Offset
/ NumBytes
) <= (1LL << 12) - 1 &&
8863 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8864 (Offset
>> shift
) << shift
== Offset
)
8869 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8871 return AM
.Scale
== 1 || (AM
.Scale
> 0 && (uint64_t)AM
.Scale
== NumBytes
);
8874 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8875 // Consider splitting large offset of struct or array.
8879 int AArch64TargetLowering::getScalingFactorCost(const DataLayout
&DL
,
8880 const AddrMode
&AM
, Type
*Ty
,
8881 unsigned AS
) const {
8882 // Scaling factors are not free at all.
8883 // Operands | Rt Latency
8884 // -------------------------------------------
8886 // -------------------------------------------
8887 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8888 // Rt, [Xn, Wm, <extend> #imm] |
8889 if (isLegalAddressingMode(DL
, AM
, Ty
, AS
))
8890 // Scale represents reg2 * scale, thus account for 1 if
8891 // it is not equal to 0 or 1.
8892 return AM
.Scale
!= 0 && AM
.Scale
!= 1;
8896 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT
) const {
8897 VT
= VT
.getScalarType();
8902 switch (VT
.getSimpleVT().SimpleTy
) {
8914 AArch64TargetLowering::getScratchRegisters(CallingConv::ID
) const {
8915 // LR is a callee-save register, but we must treat it as clobbered by any call
8916 // site. Hence we include LR in the scratch registers, which are in turn added
8917 // as implicit-defs for stackmaps and patchpoints.
8918 static const MCPhysReg ScratchRegs
[] = {
8919 AArch64::X16
, AArch64::X17
, AArch64::LR
, 0
8925 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode
*N
,
8926 CombineLevel Level
) const {
8927 N
= N
->getOperand(0).getNode();
8928 EVT VT
= N
->getValueType(0);
8929 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8930 // it with shift to let it be lowered to UBFX.
8931 if (N
->getOpcode() == ISD::AND
&& (VT
== MVT::i32
|| VT
== MVT::i64
) &&
8932 isa
<ConstantSDNode
>(N
->getOperand(1))) {
8933 uint64_t TruncMask
= N
->getConstantOperandVal(1);
8934 if (isMask_64(TruncMask
) &&
8935 N
->getOperand(0).getOpcode() == ISD::SRL
&&
8936 isa
<ConstantSDNode
>(N
->getOperand(0)->getOperand(1)))
8942 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt
&Imm
,
8944 assert(Ty
->isIntegerTy());
8946 unsigned BitSize
= Ty
->getPrimitiveSizeInBits();
8950 int64_t Val
= Imm
.getSExtValue();
8951 if (Val
== 0 || AArch64_AM::isLogicalImmediate(Val
, BitSize
))
8954 if ((int64_t)Val
< 0)
8957 Val
&= (1LL << 32) - 1;
8959 unsigned LZ
= countLeadingZeros((uint64_t)Val
);
8960 unsigned Shift
= (63 - LZ
) / 16;
8961 // MOVZ is free so return true for one or fewer MOVK.
8965 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT
, EVT SrcVT
,
8966 unsigned Index
) const {
8967 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR
, ResVT
))
8970 return (Index
== 0 || Index
== ResVT
.getVectorNumElements());
8973 /// Turn vector tests of the signbit in the form of:
8974 /// xor (sra X, elt_size(X)-1), -1
8977 static SDValue
foldVectorXorShiftIntoCmp(SDNode
*N
, SelectionDAG
&DAG
,
8978 const AArch64Subtarget
*Subtarget
) {
8979 EVT VT
= N
->getValueType(0);
8980 if (!Subtarget
->hasNEON() || !VT
.isVector())
8983 // There must be a shift right algebraic before the xor, and the xor must be a
8985 SDValue Shift
= N
->getOperand(0);
8986 SDValue Ones
= N
->getOperand(1);
8987 if (Shift
.getOpcode() != AArch64ISD::VASHR
|| !Shift
.hasOneUse() ||
8988 !ISD::isBuildVectorAllOnes(Ones
.getNode()))
8991 // The shift should be smearing the sign bit across each vector element.
8992 auto *ShiftAmt
= dyn_cast
<ConstantSDNode
>(Shift
.getOperand(1));
8993 EVT ShiftEltTy
= Shift
.getValueType().getVectorElementType();
8994 if (!ShiftAmt
|| ShiftAmt
->getZExtValue() != ShiftEltTy
.getSizeInBits() - 1)
8997 return DAG
.getNode(AArch64ISD::CMGEz
, SDLoc(N
), VT
, Shift
.getOperand(0));
9000 // Generate SUBS and CSEL for integer abs.
9001 static SDValue
performIntegerAbsCombine(SDNode
*N
, SelectionDAG
&DAG
) {
9002 EVT VT
= N
->getValueType(0);
9004 SDValue N0
= N
->getOperand(0);
9005 SDValue N1
= N
->getOperand(1);
9008 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9009 // and change it to SUB and CSEL.
9010 if (VT
.isInteger() && N
->getOpcode() == ISD::XOR
&&
9011 N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(1) == N1
&&
9012 N1
.getOpcode() == ISD::SRA
&& N1
.getOperand(0) == N0
.getOperand(0))
9013 if (ConstantSDNode
*Y1C
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1)))
9014 if (Y1C
->getAPIntValue() == VT
.getSizeInBits() - 1) {
9015 SDValue Neg
= DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
),
9017 // Generate SUBS & CSEL.
9019 DAG
.getNode(AArch64ISD::SUBS
, DL
, DAG
.getVTList(VT
, MVT::i32
),
9020 N0
.getOperand(0), DAG
.getConstant(0, DL
, VT
));
9021 return DAG
.getNode(AArch64ISD::CSEL
, DL
, VT
, N0
.getOperand(0), Neg
,
9022 DAG
.getConstant(AArch64CC::PL
, DL
, MVT::i32
),
9023 SDValue(Cmp
.getNode(), 1));
9028 static SDValue
performXorCombine(SDNode
*N
, SelectionDAG
&DAG
,
9029 TargetLowering::DAGCombinerInfo
&DCI
,
9030 const AArch64Subtarget
*Subtarget
) {
9031 if (DCI
.isBeforeLegalizeOps())
9034 if (SDValue Cmp
= foldVectorXorShiftIntoCmp(N
, DAG
, Subtarget
))
9037 return performIntegerAbsCombine(N
, DAG
);
9041 AArch64TargetLowering::BuildSDIVPow2(SDNode
*N
, const APInt
&Divisor
,
9043 SmallVectorImpl
<SDNode
*> &Created
) const {
9044 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
9045 if (isIntDivCheap(N
->getValueType(0), Attr
))
9046 return SDValue(N
,0); // Lower SDIV as SDIV
9048 // fold (sdiv X, pow2)
9049 EVT VT
= N
->getValueType(0);
9050 if ((VT
!= MVT::i32
&& VT
!= MVT::i64
) ||
9051 !(Divisor
.isPowerOf2() || (-Divisor
).isPowerOf2()))
9055 SDValue N0
= N
->getOperand(0);
9056 unsigned Lg2
= Divisor
.countTrailingZeros();
9057 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
9058 SDValue Pow2MinusOne
= DAG
.getConstant((1ULL << Lg2
) - 1, DL
, VT
);
9060 // Add (N0 < 0) ? Pow2 - 1 : 0;
9062 SDValue Cmp
= getAArch64Cmp(N0
, Zero
, ISD::SETLT
, CCVal
, DAG
, DL
);
9063 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Pow2MinusOne
);
9064 SDValue CSel
= DAG
.getNode(AArch64ISD::CSEL
, DL
, VT
, Add
, N0
, CCVal
, Cmp
);
9066 Created
.push_back(Cmp
.getNode());
9067 Created
.push_back(Add
.getNode());
9068 Created
.push_back(CSel
.getNode());
9072 DAG
.getNode(ISD::SRA
, DL
, VT
, CSel
, DAG
.getConstant(Lg2
, DL
, MVT::i64
));
9074 // If we're dividing by a positive value, we're done. Otherwise, we must
9075 // negate the result.
9076 if (Divisor
.isNonNegative())
9079 Created
.push_back(SRA
.getNode());
9080 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), SRA
);
9083 static SDValue
performMulCombine(SDNode
*N
, SelectionDAG
&DAG
,
9084 TargetLowering::DAGCombinerInfo
&DCI
,
9085 const AArch64Subtarget
*Subtarget
) {
9086 if (DCI
.isBeforeLegalizeOps())
9089 // The below optimizations require a constant RHS.
9090 if (!isa
<ConstantSDNode
>(N
->getOperand(1)))
9093 ConstantSDNode
*C
= cast
<ConstantSDNode
>(N
->getOperand(1));
9094 const APInt
&ConstValue
= C
->getAPIntValue();
9096 // Multiplication of a power of two plus/minus one can be done more
9097 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9098 // future CPUs have a cheaper MADD instruction, this may need to be
9099 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9100 // 64-bit is 5 cycles, so this is always a win.
9101 // More aggressively, some multiplications N0 * C can be lowered to
9102 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9103 // e.g. 6=3*2=(2+1)*2.
9104 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9105 // which equals to (1+2)*16-(1+2).
9106 SDValue N0
= N
->getOperand(0);
9107 // TrailingZeroes is used to test if the mul can be lowered to
9109 unsigned TrailingZeroes
= ConstValue
.countTrailingZeros();
9110 if (TrailingZeroes
) {
9111 // Conservatively do not lower to shift+add+shift if the mul might be
9112 // folded into smul or umul.
9113 if (N0
->hasOneUse() && (isSignExtended(N0
.getNode(), DAG
) ||
9114 isZeroExtended(N0
.getNode(), DAG
)))
9116 // Conservatively do not lower to shift+add+shift if the mul might be
9117 // folded into madd or msub.
9118 if (N
->hasOneUse() && (N
->use_begin()->getOpcode() == ISD::ADD
||
9119 N
->use_begin()->getOpcode() == ISD::SUB
))
9122 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9123 // and shift+add+shift.
9124 APInt ShiftedConstValue
= ConstValue
.ashr(TrailingZeroes
);
9126 unsigned ShiftAmt
, AddSubOpc
;
9127 // Is the shifted value the LHS operand of the add/sub?
9128 bool ShiftValUseIsN0
= true;
9129 // Do we need to negate the result?
9130 bool NegateResult
= false;
9132 if (ConstValue
.isNonNegative()) {
9133 // (mul x, 2^N + 1) => (add (shl x, N), x)
9134 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9135 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9136 APInt SCVMinus1
= ShiftedConstValue
- 1;
9137 APInt CVPlus1
= ConstValue
+ 1;
9138 if (SCVMinus1
.isPowerOf2()) {
9139 ShiftAmt
= SCVMinus1
.logBase2();
9140 AddSubOpc
= ISD::ADD
;
9141 } else if (CVPlus1
.isPowerOf2()) {
9142 ShiftAmt
= CVPlus1
.logBase2();
9143 AddSubOpc
= ISD::SUB
;
9147 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9148 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9149 APInt CVNegPlus1
= -ConstValue
+ 1;
9150 APInt CVNegMinus1
= -ConstValue
- 1;
9151 if (CVNegPlus1
.isPowerOf2()) {
9152 ShiftAmt
= CVNegPlus1
.logBase2();
9153 AddSubOpc
= ISD::SUB
;
9154 ShiftValUseIsN0
= false;
9155 } else if (CVNegMinus1
.isPowerOf2()) {
9156 ShiftAmt
= CVNegMinus1
.logBase2();
9157 AddSubOpc
= ISD::ADD
;
9158 NegateResult
= true;
9164 EVT VT
= N
->getValueType(0);
9165 SDValue ShiftedVal
= DAG
.getNode(ISD::SHL
, DL
, VT
, N0
,
9166 DAG
.getConstant(ShiftAmt
, DL
, MVT::i64
));
9168 SDValue AddSubN0
= ShiftValUseIsN0
? ShiftedVal
: N0
;
9169 SDValue AddSubN1
= ShiftValUseIsN0
? N0
: ShiftedVal
;
9170 SDValue Res
= DAG
.getNode(AddSubOpc
, DL
, VT
, AddSubN0
, AddSubN1
);
9171 assert(!(NegateResult
&& TrailingZeroes
) &&
9172 "NegateResult and TrailingZeroes cannot both be true for now.");
9173 // Negate the result.
9175 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), Res
);
9176 // Shift the result.
9178 return DAG
.getNode(ISD::SHL
, DL
, VT
, Res
,
9179 DAG
.getConstant(TrailingZeroes
, DL
, MVT::i64
));
9183 static SDValue
performVectorCompareAndMaskUnaryOpCombine(SDNode
*N
,
9184 SelectionDAG
&DAG
) {
9185 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9186 // optimize away operation when it's from a constant.
9188 // The general transformation is:
9189 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9190 // AND(VECTOR_CMP(x,y), constant2)
9191 // constant2 = UNARYOP(constant)
9193 // Early exit if this isn't a vector operation, the operand of the
9194 // unary operation isn't a bitwise AND, or if the sizes of the operations
9196 EVT VT
= N
->getValueType(0);
9197 if (!VT
.isVector() || N
->getOperand(0)->getOpcode() != ISD::AND
||
9198 N
->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC
||
9199 VT
.getSizeInBits() != N
->getOperand(0)->getValueType(0).getSizeInBits())
9202 // Now check that the other operand of the AND is a constant. We could
9203 // make the transformation for non-constant splats as well, but it's unclear
9204 // that would be a benefit as it would not eliminate any operations, just
9205 // perform one more step in scalar code before moving to the vector unit.
9206 if (BuildVectorSDNode
*BV
=
9207 dyn_cast
<BuildVectorSDNode
>(N
->getOperand(0)->getOperand(1))) {
9208 // Bail out if the vector isn't a constant.
9209 if (!BV
->isConstant())
9212 // Everything checks out. Build up the new and improved node.
9214 EVT IntVT
= BV
->getValueType(0);
9215 // Create a new constant of the appropriate type for the transformed
9217 SDValue SourceConst
= DAG
.getNode(N
->getOpcode(), DL
, VT
, SDValue(BV
, 0));
9218 // The AND node needs bitcasts to/from an integer vector type around it.
9219 SDValue MaskConst
= DAG
.getNode(ISD::BITCAST
, DL
, IntVT
, SourceConst
);
9220 SDValue NewAnd
= DAG
.getNode(ISD::AND
, DL
, IntVT
,
9221 N
->getOperand(0)->getOperand(0), MaskConst
);
9222 SDValue Res
= DAG
.getNode(ISD::BITCAST
, DL
, VT
, NewAnd
);
9229 static SDValue
performIntToFpCombine(SDNode
*N
, SelectionDAG
&DAG
,
9230 const AArch64Subtarget
*Subtarget
) {
9231 // First try to optimize away the conversion when it's conditionally from
9232 // a constant. Vectors only.
9233 if (SDValue Res
= performVectorCompareAndMaskUnaryOpCombine(N
, DAG
))
9236 EVT VT
= N
->getValueType(0);
9237 if (VT
!= MVT::f32
&& VT
!= MVT::f64
)
9240 // Only optimize when the source and destination types have the same width.
9241 if (VT
.getSizeInBits() != N
->getOperand(0).getValueSizeInBits())
9244 // If the result of an integer load is only used by an integer-to-float
9245 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9246 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9247 SDValue N0
= N
->getOperand(0);
9248 if (Subtarget
->hasNEON() && ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
9249 // Do not change the width of a volatile load.
9250 !cast
<LoadSDNode
>(N0
)->isVolatile()) {
9251 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9252 SDValue Load
= DAG
.getLoad(VT
, SDLoc(N
), LN0
->getChain(), LN0
->getBasePtr(),
9253 LN0
->getPointerInfo(), LN0
->getAlignment(),
9254 LN0
->getMemOperand()->getFlags());
9256 // Make sure successors of the original load stay after it by updating them
9257 // to use the new Chain.
9258 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), Load
.getValue(1));
9261 (N
->getOpcode() == ISD::SINT_TO_FP
) ? AArch64ISD::SITOF
: AArch64ISD::UITOF
;
9262 return DAG
.getNode(Opcode
, SDLoc(N
), VT
, Load
);
9268 /// Fold a floating-point multiply by power of two into floating-point to
9269 /// fixed-point conversion.
9270 static SDValue
performFpToIntCombine(SDNode
*N
, SelectionDAG
&DAG
,
9271 TargetLowering::DAGCombinerInfo
&DCI
,
9272 const AArch64Subtarget
*Subtarget
) {
9273 if (!Subtarget
->hasNEON())
9276 if (!N
->getValueType(0).isSimple())
9279 SDValue Op
= N
->getOperand(0);
9280 if (!Op
.getValueType().isVector() || !Op
.getValueType().isSimple() ||
9281 Op
.getOpcode() != ISD::FMUL
)
9284 SDValue ConstVec
= Op
->getOperand(1);
9285 if (!isa
<BuildVectorSDNode
>(ConstVec
))
9288 MVT FloatTy
= Op
.getSimpleValueType().getVectorElementType();
9289 uint32_t FloatBits
= FloatTy
.getSizeInBits();
9290 if (FloatBits
!= 32 && FloatBits
!= 64)
9293 MVT IntTy
= N
->getSimpleValueType(0).getVectorElementType();
9294 uint32_t IntBits
= IntTy
.getSizeInBits();
9295 if (IntBits
!= 16 && IntBits
!= 32 && IntBits
!= 64)
9298 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9299 if (IntBits
> FloatBits
)
9302 BitVector UndefElements
;
9303 BuildVectorSDNode
*BV
= cast
<BuildVectorSDNode
>(ConstVec
);
9304 int32_t Bits
= IntBits
== 64 ? 64 : 32;
9305 int32_t C
= BV
->getConstantFPSplatPow2ToLog2Int(&UndefElements
, Bits
+ 1);
9306 if (C
== -1 || C
== 0 || C
> Bits
)
9310 unsigned NumLanes
= Op
.getValueType().getVectorNumElements();
9315 ResTy
= FloatBits
== 32 ? MVT::v2i32
: MVT::v2i64
;
9318 ResTy
= FloatBits
== 32 ? MVT::v4i32
: MVT::v4i64
;
9322 if (ResTy
== MVT::v4i64
&& DCI
.isBeforeLegalizeOps())
9325 assert((ResTy
!= MVT::v4i64
|| DCI
.isBeforeLegalizeOps()) &&
9326 "Illegal vector type after legalization");
9329 bool IsSigned
= N
->getOpcode() == ISD::FP_TO_SINT
;
9330 unsigned IntrinsicOpcode
= IsSigned
? Intrinsic::aarch64_neon_vcvtfp2fxs
9331 : Intrinsic::aarch64_neon_vcvtfp2fxu
;
9333 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, ResTy
,
9334 DAG
.getConstant(IntrinsicOpcode
, DL
, MVT::i32
),
9335 Op
->getOperand(0), DAG
.getConstant(C
, DL
, MVT::i32
));
9336 // We can handle smaller integers by generating an extra trunc.
9337 if (IntBits
< FloatBits
)
9338 FixConv
= DAG
.getNode(ISD::TRUNCATE
, DL
, N
->getValueType(0), FixConv
);
9343 /// Fold a floating-point divide by power of two into fixed-point to
9344 /// floating-point conversion.
9345 static SDValue
performFDivCombine(SDNode
*N
, SelectionDAG
&DAG
,
9346 TargetLowering::DAGCombinerInfo
&DCI
,
9347 const AArch64Subtarget
*Subtarget
) {
9348 if (!Subtarget
->hasNEON())
9351 SDValue Op
= N
->getOperand(0);
9352 unsigned Opc
= Op
->getOpcode();
9353 if (!Op
.getValueType().isVector() || !Op
.getValueType().isSimple() ||
9354 !Op
.getOperand(0).getValueType().isSimple() ||
9355 (Opc
!= ISD::SINT_TO_FP
&& Opc
!= ISD::UINT_TO_FP
))
9358 SDValue ConstVec
= N
->getOperand(1);
9359 if (!isa
<BuildVectorSDNode
>(ConstVec
))
9362 MVT IntTy
= Op
.getOperand(0).getSimpleValueType().getVectorElementType();
9363 int32_t IntBits
= IntTy
.getSizeInBits();
9364 if (IntBits
!= 16 && IntBits
!= 32 && IntBits
!= 64)
9367 MVT FloatTy
= N
->getSimpleValueType(0).getVectorElementType();
9368 int32_t FloatBits
= FloatTy
.getSizeInBits();
9369 if (FloatBits
!= 32 && FloatBits
!= 64)
9372 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9373 if (IntBits
> FloatBits
)
9376 BitVector UndefElements
;
9377 BuildVectorSDNode
*BV
= cast
<BuildVectorSDNode
>(ConstVec
);
9378 int32_t C
= BV
->getConstantFPSplatPow2ToLog2Int(&UndefElements
, FloatBits
+ 1);
9379 if (C
== -1 || C
== 0 || C
> FloatBits
)
9383 unsigned NumLanes
= Op
.getValueType().getVectorNumElements();
9388 ResTy
= FloatBits
== 32 ? MVT::v2i32
: MVT::v2i64
;
9391 ResTy
= FloatBits
== 32 ? MVT::v4i32
: MVT::v4i64
;
9395 if (ResTy
== MVT::v4i64
&& DCI
.isBeforeLegalizeOps())
9399 SDValue ConvInput
= Op
.getOperand(0);
9400 bool IsSigned
= Opc
== ISD::SINT_TO_FP
;
9401 if (IntBits
< FloatBits
)
9402 ConvInput
= DAG
.getNode(IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
, DL
,
9405 unsigned IntrinsicOpcode
= IsSigned
? Intrinsic::aarch64_neon_vcvtfxs2fp
9406 : Intrinsic::aarch64_neon_vcvtfxu2fp
;
9407 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, Op
.getValueType(),
9408 DAG
.getConstant(IntrinsicOpcode
, DL
, MVT::i32
), ConvInput
,
9409 DAG
.getConstant(C
, DL
, MVT::i32
));
9412 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9413 /// searches for and classifies those shifts.
9414 static bool findEXTRHalf(SDValue N
, SDValue
&Src
, uint32_t &ShiftAmount
,
9416 if (N
.getOpcode() == ISD::SHL
)
9418 else if (N
.getOpcode() == ISD::SRL
)
9423 if (!isa
<ConstantSDNode
>(N
.getOperand(1)))
9426 ShiftAmount
= N
->getConstantOperandVal(1);
9427 Src
= N
->getOperand(0);
9431 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9432 /// registers viewed as a high/low pair. This function looks for the pattern:
9433 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9434 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9435 /// aren't independent.
9436 static SDValue
tryCombineToEXTR(SDNode
*N
,
9437 TargetLowering::DAGCombinerInfo
&DCI
) {
9438 SelectionDAG
&DAG
= DCI
.DAG
;
9440 EVT VT
= N
->getValueType(0);
9442 assert(N
->getOpcode() == ISD::OR
&& "Unexpected root");
9444 if (VT
!= MVT::i32
&& VT
!= MVT::i64
)
9448 uint32_t ShiftLHS
= 0;
9449 bool LHSFromHi
= false;
9450 if (!findEXTRHalf(N
->getOperand(0), LHS
, ShiftLHS
, LHSFromHi
))
9454 uint32_t ShiftRHS
= 0;
9455 bool RHSFromHi
= false;
9456 if (!findEXTRHalf(N
->getOperand(1), RHS
, ShiftRHS
, RHSFromHi
))
9459 // If they're both trying to come from the high part of the register, they're
9460 // not really an EXTR.
9461 if (LHSFromHi
== RHSFromHi
)
9464 if (ShiftLHS
+ ShiftRHS
!= VT
.getSizeInBits())
9468 std::swap(LHS
, RHS
);
9469 std::swap(ShiftLHS
, ShiftRHS
);
9472 return DAG
.getNode(AArch64ISD::EXTR
, DL
, VT
, LHS
, RHS
,
9473 DAG
.getConstant(ShiftRHS
, DL
, MVT::i64
));
9476 static SDValue
tryCombineToBSL(SDNode
*N
,
9477 TargetLowering::DAGCombinerInfo
&DCI
) {
9478 EVT VT
= N
->getValueType(0);
9479 SelectionDAG
&DAG
= DCI
.DAG
;
9485 SDValue N0
= N
->getOperand(0);
9486 if (N0
.getOpcode() != ISD::AND
)
9489 SDValue N1
= N
->getOperand(1);
9490 if (N1
.getOpcode() != ISD::AND
)
9493 // We only have to look for constant vectors here since the general, variable
9494 // case can be handled in TableGen.
9495 unsigned Bits
= VT
.getScalarSizeInBits();
9496 uint64_t BitMask
= Bits
== 64 ? -1ULL : ((1ULL << Bits
) - 1);
9497 for (int i
= 1; i
>= 0; --i
)
9498 for (int j
= 1; j
>= 0; --j
) {
9499 BuildVectorSDNode
*BVN0
= dyn_cast
<BuildVectorSDNode
>(N0
->getOperand(i
));
9500 BuildVectorSDNode
*BVN1
= dyn_cast
<BuildVectorSDNode
>(N1
->getOperand(j
));
9504 bool FoundMatch
= true;
9505 for (unsigned k
= 0; k
< VT
.getVectorNumElements(); ++k
) {
9506 ConstantSDNode
*CN0
= dyn_cast
<ConstantSDNode
>(BVN0
->getOperand(k
));
9507 ConstantSDNode
*CN1
= dyn_cast
<ConstantSDNode
>(BVN1
->getOperand(k
));
9509 CN0
->getZExtValue() != (BitMask
& ~CN1
->getZExtValue())) {
9516 return DAG
.getNode(AArch64ISD::BSL
, DL
, VT
, SDValue(BVN0
, 0),
9517 N0
->getOperand(1 - i
), N1
->getOperand(1 - j
));
9523 static SDValue
performORCombine(SDNode
*N
, TargetLowering::DAGCombinerInfo
&DCI
,
9524 const AArch64Subtarget
*Subtarget
) {
9525 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9526 SelectionDAG
&DAG
= DCI
.DAG
;
9527 EVT VT
= N
->getValueType(0);
9529 if (!DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
9532 if (SDValue Res
= tryCombineToEXTR(N
, DCI
))
9535 if (SDValue Res
= tryCombineToBSL(N
, DCI
))
9541 static SDValue
performANDCombine(SDNode
*N
,
9542 TargetLowering::DAGCombinerInfo
&DCI
) {
9543 SelectionDAG
&DAG
= DCI
.DAG
;
9544 SDValue LHS
= N
->getOperand(0);
9545 EVT VT
= N
->getValueType(0);
9546 if (!VT
.isVector() || !DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
9549 BuildVectorSDNode
*BVN
=
9550 dyn_cast
<BuildVectorSDNode
>(N
->getOperand(1).getNode());
9554 // AND does not accept an immediate, so check if we can use a BIC immediate
9555 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9556 // pattern in isel, because some immediates may be lowered to the preferred
9557 // (and x, (movi imm)) form, even though an mvni representation also exists.
9558 APInt
DefBits(VT
.getSizeInBits(), 0);
9559 APInt
UndefBits(VT
.getSizeInBits(), 0);
9560 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
9564 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9566 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9570 UndefBits
= ~UndefBits
;
9571 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9572 UndefBits
, &LHS
)) ||
9573 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9581 static SDValue
performSRLCombine(SDNode
*N
,
9582 TargetLowering::DAGCombinerInfo
&DCI
) {
9583 SelectionDAG
&DAG
= DCI
.DAG
;
9584 EVT VT
= N
->getValueType(0);
9585 if (VT
!= MVT::i32
&& VT
!= MVT::i64
)
9588 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9589 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9590 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9591 SDValue N0
= N
->getOperand(0);
9592 if (N0
.getOpcode() == ISD::BSWAP
) {
9594 SDValue N1
= N
->getOperand(1);
9595 SDValue N00
= N0
.getOperand(0);
9596 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N1
)) {
9597 uint64_t ShiftAmt
= C
->getZExtValue();
9598 if (VT
== MVT::i32
&& ShiftAmt
== 16 &&
9599 DAG
.MaskedValueIsZero(N00
, APInt::getHighBitsSet(32, 16)))
9600 return DAG
.getNode(ISD::ROTR
, DL
, VT
, N0
, N1
);
9601 if (VT
== MVT::i64
&& ShiftAmt
== 32 &&
9602 DAG
.MaskedValueIsZero(N00
, APInt::getHighBitsSet(64, 32)))
9603 return DAG
.getNode(ISD::ROTR
, DL
, VT
, N0
, N1
);
9609 static SDValue
performBitcastCombine(SDNode
*N
,
9610 TargetLowering::DAGCombinerInfo
&DCI
,
9611 SelectionDAG
&DAG
) {
9612 // Wait 'til after everything is legalized to try this. That way we have
9613 // legal vector types and such.
9614 if (DCI
.isBeforeLegalizeOps())
9617 // Remove extraneous bitcasts around an extract_subvector.
9619 // (v4i16 (bitconvert
9620 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9622 // (extract_subvector ((v8i16 ...), (i64 4)))
9624 // Only interested in 64-bit vectors as the ultimate result.
9625 EVT VT
= N
->getValueType(0);
9628 if (VT
.getSimpleVT().getSizeInBits() != 64)
9630 // Is the operand an extract_subvector starting at the beginning or halfway
9631 // point of the vector? A low half may also come through as an
9632 // EXTRACT_SUBREG, so look for that, too.
9633 SDValue Op0
= N
->getOperand(0);
9634 if (Op0
->getOpcode() != ISD::EXTRACT_SUBVECTOR
&&
9635 !(Op0
->isMachineOpcode() &&
9636 Op0
->getMachineOpcode() == AArch64::EXTRACT_SUBREG
))
9638 uint64_t idx
= cast
<ConstantSDNode
>(Op0
->getOperand(1))->getZExtValue();
9639 if (Op0
->getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
9640 if (Op0
->getValueType(0).getVectorNumElements() != idx
&& idx
!= 0)
9642 } else if (Op0
->getMachineOpcode() == AArch64::EXTRACT_SUBREG
) {
9643 if (idx
!= AArch64::dsub
)
9645 // The dsub reference is equivalent to a lane zero subvector reference.
9648 // Look through the bitcast of the input to the extract.
9649 if (Op0
->getOperand(0)->getOpcode() != ISD::BITCAST
)
9651 SDValue Source
= Op0
->getOperand(0)->getOperand(0);
9652 // If the source type has twice the number of elements as our destination
9653 // type, we know this is an extract of the high or low half of the vector.
9654 EVT SVT
= Source
->getValueType(0);
9655 if (!SVT
.isVector() ||
9656 SVT
.getVectorNumElements() != VT
.getVectorNumElements() * 2)
9660 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9662 // Create the simplified form to just extract the low or high half of the
9663 // vector directly rather than bothering with the bitcasts.
9665 unsigned NumElements
= VT
.getVectorNumElements();
9667 SDValue HalfIdx
= DAG
.getConstant(NumElements
, dl
, MVT::i64
);
9668 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, Source
, HalfIdx
);
9670 SDValue SubReg
= DAG
.getTargetConstant(AArch64::dsub
, dl
, MVT::i32
);
9671 return SDValue(DAG
.getMachineNode(TargetOpcode::EXTRACT_SUBREG
, dl
, VT
,
9677 static SDValue
performConcatVectorsCombine(SDNode
*N
,
9678 TargetLowering::DAGCombinerInfo
&DCI
,
9679 SelectionDAG
&DAG
) {
9681 EVT VT
= N
->getValueType(0);
9682 SDValue N0
= N
->getOperand(0), N1
= N
->getOperand(1);
9684 // Optimize concat_vectors of truncated vectors, where the intermediate
9685 // type is illegal, to avoid said illegality, e.g.,
9686 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9687 // (v2i16 (truncate (v2i64)))))
9689 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9690 // (v4i32 (bitcast (v2i64))),
9692 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9693 // on both input and result type, so we might generate worse code.
9694 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9695 if (N
->getNumOperands() == 2 &&
9696 N0
->getOpcode() == ISD::TRUNCATE
&&
9697 N1
->getOpcode() == ISD::TRUNCATE
) {
9698 SDValue N00
= N0
->getOperand(0);
9699 SDValue N10
= N1
->getOperand(0);
9700 EVT N00VT
= N00
.getValueType();
9702 if (N00VT
== N10
.getValueType() &&
9703 (N00VT
== MVT::v2i64
|| N00VT
== MVT::v4i32
) &&
9704 N00VT
.getScalarSizeInBits() == 4 * VT
.getScalarSizeInBits()) {
9705 MVT MidVT
= (N00VT
== MVT::v2i64
? MVT::v4i32
: MVT::v8i16
);
9706 SmallVector
<int, 8> Mask(MidVT
.getVectorNumElements());
9707 for (size_t i
= 0; i
< Mask
.size(); ++i
)
9709 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
9710 DAG
.getVectorShuffle(
9712 DAG
.getNode(ISD::BITCAST
, dl
, MidVT
, N00
),
9713 DAG
.getNode(ISD::BITCAST
, dl
, MidVT
, N10
), Mask
));
9717 // Wait 'til after everything is legalized to try this. That way we have
9718 // legal vector types and such.
9719 if (DCI
.isBeforeLegalizeOps())
9722 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9723 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9724 // canonicalise to that.
9725 if (N0
== N1
&& VT
.getVectorNumElements() == 2) {
9726 assert(VT
.getScalarSizeInBits() == 64);
9727 return DAG
.getNode(AArch64ISD::DUPLANE64
, dl
, VT
, WidenVector(N0
, DAG
),
9728 DAG
.getConstant(0, dl
, MVT::i64
));
9731 // Canonicalise concat_vectors so that the right-hand vector has as few
9732 // bit-casts as possible before its real operation. The primary matching
9733 // destination for these operations will be the narrowing "2" instructions,
9734 // which depend on the operation being performed on this right-hand vector.
9736 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9738 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9740 if (N1
->getOpcode() != ISD::BITCAST
)
9742 SDValue RHS
= N1
->getOperand(0);
9743 MVT RHSTy
= RHS
.getValueType().getSimpleVT();
9744 // If the RHS is not a vector, this is not the pattern we're looking for.
9745 if (!RHSTy
.isVector())
9749 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9751 MVT ConcatTy
= MVT::getVectorVT(RHSTy
.getVectorElementType(),
9752 RHSTy
.getVectorNumElements() * 2);
9753 return DAG
.getNode(ISD::BITCAST
, dl
, VT
,
9754 DAG
.getNode(ISD::CONCAT_VECTORS
, dl
, ConcatTy
,
9755 DAG
.getNode(ISD::BITCAST
, dl
, RHSTy
, N0
),
9759 static SDValue
tryCombineFixedPointConvert(SDNode
*N
,
9760 TargetLowering::DAGCombinerInfo
&DCI
,
9761 SelectionDAG
&DAG
) {
9762 // Wait until after everything is legalized to try this. That way we have
9763 // legal vector types and such.
9764 if (DCI
.isBeforeLegalizeOps())
9766 // Transform a scalar conversion of a value from a lane extract into a
9767 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9768 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9769 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9771 // The second form interacts better with instruction selection and the
9772 // register allocator to avoid cross-class register copies that aren't
9773 // coalescable due to a lane reference.
9775 // Check the operand and see if it originates from a lane extract.
9776 SDValue Op1
= N
->getOperand(1);
9777 if (Op1
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
) {
9778 // Yep, no additional predication needed. Perform the transform.
9779 SDValue IID
= N
->getOperand(0);
9780 SDValue Shift
= N
->getOperand(2);
9781 SDValue Vec
= Op1
.getOperand(0);
9782 SDValue Lane
= Op1
.getOperand(1);
9783 EVT ResTy
= N
->getValueType(0);
9787 // The vector width should be 128 bits by the time we get here, even
9788 // if it started as 64 bits (the extract_vector handling will have
9790 assert(Vec
.getValueSizeInBits() == 128 &&
9791 "unexpected vector size on extract_vector_elt!");
9792 if (Vec
.getValueType() == MVT::v4i32
)
9793 VecResTy
= MVT::v4f32
;
9794 else if (Vec
.getValueType() == MVT::v2i64
)
9795 VecResTy
= MVT::v2f64
;
9797 llvm_unreachable("unexpected vector type!");
9800 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VecResTy
, IID
, Vec
, Shift
);
9801 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ResTy
, Convert
, Lane
);
9806 // AArch64 high-vector "long" operations are formed by performing the non-high
9807 // version on an extract_subvector of each operand which gets the high half:
9809 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9811 // However, there are cases which don't have an extract_high explicitly, but
9812 // have another operation that can be made compatible with one for free. For
9815 // (dupv64 scalar) --> (extract_high (dup128 scalar))
9817 // This routine does the actual conversion of such DUPs, once outer routines
9818 // have determined that everything else is in order.
9819 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9821 static SDValue
tryExtendDUPToExtractHigh(SDValue N
, SelectionDAG
&DAG
) {
9822 switch (N
.getOpcode()) {
9823 case AArch64ISD::DUP
:
9824 case AArch64ISD::DUPLANE8
:
9825 case AArch64ISD::DUPLANE16
:
9826 case AArch64ISD::DUPLANE32
:
9827 case AArch64ISD::DUPLANE64
:
9828 case AArch64ISD::MOVI
:
9829 case AArch64ISD::MOVIshift
:
9830 case AArch64ISD::MOVIedit
:
9831 case AArch64ISD::MOVImsl
:
9832 case AArch64ISD::MVNIshift
:
9833 case AArch64ISD::MVNImsl
:
9836 // FMOV could be supported, but isn't very useful, as it would only occur
9837 // if you passed a bitcast' floating point immediate to an eligible long
9838 // integer op (addl, smull, ...).
9842 MVT NarrowTy
= N
.getSimpleValueType();
9843 if (!NarrowTy
.is64BitVector())
9846 MVT ElementTy
= NarrowTy
.getVectorElementType();
9847 unsigned NumElems
= NarrowTy
.getVectorNumElements();
9848 MVT NewVT
= MVT::getVectorVT(ElementTy
, NumElems
* 2);
9851 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, NarrowTy
,
9852 DAG
.getNode(N
->getOpcode(), dl
, NewVT
, N
->ops()),
9853 DAG
.getConstant(NumElems
, dl
, MVT::i64
));
9856 static bool isEssentiallyExtractHighSubvector(SDValue N
) {
9857 if (N
.getOpcode() == ISD::BITCAST
)
9858 N
= N
.getOperand(0);
9859 if (N
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
9861 return cast
<ConstantSDNode
>(N
.getOperand(1))->getAPIntValue() ==
9862 N
.getOperand(0).getValueType().getVectorNumElements() / 2;
9865 /// Helper structure to keep track of ISD::SET_CC operands.
9866 struct GenericSetCCInfo
{
9867 const SDValue
*Opnd0
;
9868 const SDValue
*Opnd1
;
9872 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9873 struct AArch64SetCCInfo
{
9875 AArch64CC::CondCode CC
;
9878 /// Helper structure to keep track of SetCC information.
9880 GenericSetCCInfo Generic
;
9881 AArch64SetCCInfo AArch64
;
9884 /// Helper structure to be able to read SetCC information. If set to
9885 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9886 /// GenericSetCCInfo.
9887 struct SetCCInfoAndKind
{
9892 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9894 /// AArch64 lowered one.
9895 /// \p SetCCInfo is filled accordingly.
9896 /// \post SetCCInfo is meanginfull only when this function returns true.
9897 /// \return True when Op is a kind of SET_CC operation.
9898 static bool isSetCC(SDValue Op
, SetCCInfoAndKind
&SetCCInfo
) {
9899 // If this is a setcc, this is straight forward.
9900 if (Op
.getOpcode() == ISD::SETCC
) {
9901 SetCCInfo
.Info
.Generic
.Opnd0
= &Op
.getOperand(0);
9902 SetCCInfo
.Info
.Generic
.Opnd1
= &Op
.getOperand(1);
9903 SetCCInfo
.Info
.Generic
.CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
9904 SetCCInfo
.IsAArch64
= false;
9907 // Otherwise, check if this is a matching csel instruction.
9911 if (Op
.getOpcode() != AArch64ISD::CSEL
)
9913 // Set the information about the operands.
9914 // TODO: we want the operands of the Cmp not the csel
9915 SetCCInfo
.Info
.AArch64
.Cmp
= &Op
.getOperand(3);
9916 SetCCInfo
.IsAArch64
= true;
9917 SetCCInfo
.Info
.AArch64
.CC
= static_cast<AArch64CC::CondCode
>(
9918 cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue());
9920 // Check that the operands matches the constraints:
9921 // (1) Both operands must be constants.
9922 // (2) One must be 1 and the other must be 0.
9923 ConstantSDNode
*TValue
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(0));
9924 ConstantSDNode
*FValue
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
9927 if (!TValue
|| !FValue
)
9931 if (!TValue
->isOne()) {
9932 // Update the comparison when we are interested in !cc.
9933 std::swap(TValue
, FValue
);
9934 SetCCInfo
.Info
.AArch64
.CC
=
9935 AArch64CC::getInvertedCondCode(SetCCInfo
.Info
.AArch64
.CC
);
9937 return TValue
->isOne() && FValue
->isNullValue();
9940 // Returns true if Op is setcc or zext of setcc.
9941 static bool isSetCCOrZExtSetCC(const SDValue
& Op
, SetCCInfoAndKind
&Info
) {
9942 if (isSetCC(Op
, Info
))
9944 return ((Op
.getOpcode() == ISD::ZERO_EXTEND
) &&
9945 isSetCC(Op
->getOperand(0), Info
));
9948 // The folding we want to perform is:
9949 // (add x, [zext] (setcc cc ...) )
9951 // (csel x, (add x, 1), !cc ...)
9953 // The latter will get matched to a CSINC instruction.
9954 static SDValue
performSetccAddFolding(SDNode
*Op
, SelectionDAG
&DAG
) {
9955 assert(Op
&& Op
->getOpcode() == ISD::ADD
&& "Unexpected operation!");
9956 SDValue LHS
= Op
->getOperand(0);
9957 SDValue RHS
= Op
->getOperand(1);
9958 SetCCInfoAndKind InfoAndKind
;
9960 // If neither operand is a SET_CC, give up.
9961 if (!isSetCCOrZExtSetCC(LHS
, InfoAndKind
)) {
9962 std::swap(LHS
, RHS
);
9963 if (!isSetCCOrZExtSetCC(LHS
, InfoAndKind
))
9967 // FIXME: This could be generatized to work for FP comparisons.
9968 EVT CmpVT
= InfoAndKind
.IsAArch64
9969 ? InfoAndKind
.Info
.AArch64
.Cmp
->getOperand(0).getValueType()
9970 : InfoAndKind
.Info
.Generic
.Opnd0
->getValueType();
9971 if (CmpVT
!= MVT::i32
&& CmpVT
!= MVT::i64
)
9977 if (InfoAndKind
.IsAArch64
) {
9978 CCVal
= DAG
.getConstant(
9979 AArch64CC::getInvertedCondCode(InfoAndKind
.Info
.AArch64
.CC
), dl
,
9981 Cmp
= *InfoAndKind
.Info
.AArch64
.Cmp
;
9983 Cmp
= getAArch64Cmp(*InfoAndKind
.Info
.Generic
.Opnd0
,
9984 *InfoAndKind
.Info
.Generic
.Opnd1
,
9985 ISD::getSetCCInverse(InfoAndKind
.Info
.Generic
.CC
, true),
9988 EVT VT
= Op
->getValueType(0);
9989 LHS
= DAG
.getNode(ISD::ADD
, dl
, VT
, RHS
, DAG
.getConstant(1, dl
, VT
));
9990 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, RHS
, LHS
, CCVal
, Cmp
);
9993 // The basic add/sub long vector instructions have variants with "2" on the end
9994 // which act on the high-half of their inputs. They are normally matched by
9997 // (add (zeroext (extract_high LHS)),
9998 // (zeroext (extract_high RHS)))
9999 // -> uaddl2 vD, vN, vM
10001 // However, if one of the extracts is something like a duplicate, this
10002 // instruction can still be used profitably. This function puts the DAG into a
10003 // more appropriate form for those patterns to trigger.
10004 static SDValue
performAddSubLongCombine(SDNode
*N
,
10005 TargetLowering::DAGCombinerInfo
&DCI
,
10006 SelectionDAG
&DAG
) {
10007 if (DCI
.isBeforeLegalizeOps())
10010 MVT VT
= N
->getSimpleValueType(0);
10011 if (!VT
.is128BitVector()) {
10012 if (N
->getOpcode() == ISD::ADD
)
10013 return performSetccAddFolding(N
, DAG
);
10017 // Make sure both branches are extended in the same way.
10018 SDValue LHS
= N
->getOperand(0);
10019 SDValue RHS
= N
->getOperand(1);
10020 if ((LHS
.getOpcode() != ISD::ZERO_EXTEND
&&
10021 LHS
.getOpcode() != ISD::SIGN_EXTEND
) ||
10022 LHS
.getOpcode() != RHS
.getOpcode())
10025 unsigned ExtType
= LHS
.getOpcode();
10027 // It's not worth doing if at least one of the inputs isn't already an
10028 // extract, but we don't know which it'll be so we have to try both.
10029 if (isEssentiallyExtractHighSubvector(LHS
.getOperand(0))) {
10030 RHS
= tryExtendDUPToExtractHigh(RHS
.getOperand(0), DAG
);
10031 if (!RHS
.getNode())
10034 RHS
= DAG
.getNode(ExtType
, SDLoc(N
), VT
, RHS
);
10035 } else if (isEssentiallyExtractHighSubvector(RHS
.getOperand(0))) {
10036 LHS
= tryExtendDUPToExtractHigh(LHS
.getOperand(0), DAG
);
10037 if (!LHS
.getNode())
10040 LHS
= DAG
.getNode(ExtType
, SDLoc(N
), VT
, LHS
);
10043 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, LHS
, RHS
);
10046 // Massage DAGs which we can use the high-half "long" operations on into
10047 // something isel will recognize better. E.g.
10049 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10050 // (aarch64_neon_umull (extract_high (v2i64 vec)))
10051 // (extract_high (v2i64 (dup128 scalar)))))
10053 static SDValue
tryCombineLongOpWithDup(unsigned IID
, SDNode
*N
,
10054 TargetLowering::DAGCombinerInfo
&DCI
,
10055 SelectionDAG
&DAG
) {
10056 if (DCI
.isBeforeLegalizeOps())
10059 SDValue LHS
= N
->getOperand(1);
10060 SDValue RHS
= N
->getOperand(2);
10061 assert(LHS
.getValueType().is64BitVector() &&
10062 RHS
.getValueType().is64BitVector() &&
10063 "unexpected shape for long operation");
10065 // Either node could be a DUP, but it's not worth doing both of them (you'd
10066 // just as well use the non-high version) so look for a corresponding extract
10067 // operation on the other "wing".
10068 if (isEssentiallyExtractHighSubvector(LHS
)) {
10069 RHS
= tryExtendDUPToExtractHigh(RHS
, DAG
);
10070 if (!RHS
.getNode())
10072 } else if (isEssentiallyExtractHighSubvector(RHS
)) {
10073 LHS
= tryExtendDUPToExtractHigh(LHS
, DAG
);
10074 if (!LHS
.getNode())
10078 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, SDLoc(N
), N
->getValueType(0),
10079 N
->getOperand(0), LHS
, RHS
);
10082 static SDValue
tryCombineShiftImm(unsigned IID
, SDNode
*N
, SelectionDAG
&DAG
) {
10083 MVT ElemTy
= N
->getSimpleValueType(0).getScalarType();
10084 unsigned ElemBits
= ElemTy
.getSizeInBits();
10086 int64_t ShiftAmount
;
10087 if (BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(N
->getOperand(2))) {
10088 APInt SplatValue
, SplatUndef
;
10089 unsigned SplatBitSize
;
10091 if (!BVN
->isConstantSplat(SplatValue
, SplatUndef
, SplatBitSize
,
10092 HasAnyUndefs
, ElemBits
) ||
10093 SplatBitSize
!= ElemBits
)
10096 ShiftAmount
= SplatValue
.getSExtValue();
10097 } else if (ConstantSDNode
*CVN
= dyn_cast
<ConstantSDNode
>(N
->getOperand(2))) {
10098 ShiftAmount
= CVN
->getSExtValue();
10106 llvm_unreachable("Unknown shift intrinsic");
10107 case Intrinsic::aarch64_neon_sqshl
:
10108 Opcode
= AArch64ISD::SQSHL_I
;
10109 IsRightShift
= false;
10111 case Intrinsic::aarch64_neon_uqshl
:
10112 Opcode
= AArch64ISD::UQSHL_I
;
10113 IsRightShift
= false;
10115 case Intrinsic::aarch64_neon_srshl
:
10116 Opcode
= AArch64ISD::SRSHR_I
;
10117 IsRightShift
= true;
10119 case Intrinsic::aarch64_neon_urshl
:
10120 Opcode
= AArch64ISD::URSHR_I
;
10121 IsRightShift
= true;
10123 case Intrinsic::aarch64_neon_sqshlu
:
10124 Opcode
= AArch64ISD::SQSHLU_I
;
10125 IsRightShift
= false;
10129 if (IsRightShift
&& ShiftAmount
<= -1 && ShiftAmount
>= -(int)ElemBits
) {
10131 return DAG
.getNode(Opcode
, dl
, N
->getValueType(0), N
->getOperand(1),
10132 DAG
.getConstant(-ShiftAmount
, dl
, MVT::i32
));
10133 } else if (!IsRightShift
&& ShiftAmount
>= 0 && ShiftAmount
< ElemBits
) {
10135 return DAG
.getNode(Opcode
, dl
, N
->getValueType(0), N
->getOperand(1),
10136 DAG
.getConstant(ShiftAmount
, dl
, MVT::i32
));
10142 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10143 // the intrinsics must be legal and take an i32, this means there's almost
10144 // certainly going to be a zext in the DAG which we can eliminate.
10145 static SDValue
tryCombineCRC32(unsigned Mask
, SDNode
*N
, SelectionDAG
&DAG
) {
10146 SDValue AndN
= N
->getOperand(2);
10147 if (AndN
.getOpcode() != ISD::AND
)
10150 ConstantSDNode
*CMask
= dyn_cast
<ConstantSDNode
>(AndN
.getOperand(1));
10151 if (!CMask
|| CMask
->getZExtValue() != Mask
)
10154 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, SDLoc(N
), MVT::i32
,
10155 N
->getOperand(0), N
->getOperand(1), AndN
.getOperand(0));
10158 static SDValue
combineAcrossLanesIntrinsic(unsigned Opc
, SDNode
*N
,
10159 SelectionDAG
&DAG
) {
10161 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, dl
, N
->getValueType(0),
10162 DAG
.getNode(Opc
, dl
,
10163 N
->getOperand(1).getSimpleValueType(),
10165 DAG
.getConstant(0, dl
, MVT::i64
));
10168 static SDValue
performIntrinsicCombine(SDNode
*N
,
10169 TargetLowering::DAGCombinerInfo
&DCI
,
10170 const AArch64Subtarget
*Subtarget
) {
10171 SelectionDAG
&DAG
= DCI
.DAG
;
10172 unsigned IID
= getIntrinsicID(N
);
10176 case Intrinsic::aarch64_neon_vcvtfxs2fp
:
10177 case Intrinsic::aarch64_neon_vcvtfxu2fp
:
10178 return tryCombineFixedPointConvert(N
, DCI
, DAG
);
10179 case Intrinsic::aarch64_neon_saddv
:
10180 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV
, N
, DAG
);
10181 case Intrinsic::aarch64_neon_uaddv
:
10182 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV
, N
, DAG
);
10183 case Intrinsic::aarch64_neon_sminv
:
10184 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV
, N
, DAG
);
10185 case Intrinsic::aarch64_neon_uminv
:
10186 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV
, N
, DAG
);
10187 case Intrinsic::aarch64_neon_smaxv
:
10188 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV
, N
, DAG
);
10189 case Intrinsic::aarch64_neon_umaxv
:
10190 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV
, N
, DAG
);
10191 case Intrinsic::aarch64_neon_fmax
:
10192 return DAG
.getNode(ISD::FMAXIMUM
, SDLoc(N
), N
->getValueType(0),
10193 N
->getOperand(1), N
->getOperand(2));
10194 case Intrinsic::aarch64_neon_fmin
:
10195 return DAG
.getNode(ISD::FMINIMUM
, SDLoc(N
), N
->getValueType(0),
10196 N
->getOperand(1), N
->getOperand(2));
10197 case Intrinsic::aarch64_neon_fmaxnm
:
10198 return DAG
.getNode(ISD::FMAXNUM
, SDLoc(N
), N
->getValueType(0),
10199 N
->getOperand(1), N
->getOperand(2));
10200 case Intrinsic::aarch64_neon_fminnm
:
10201 return DAG
.getNode(ISD::FMINNUM
, SDLoc(N
), N
->getValueType(0),
10202 N
->getOperand(1), N
->getOperand(2));
10203 case Intrinsic::aarch64_neon_smull
:
10204 case Intrinsic::aarch64_neon_umull
:
10205 case Intrinsic::aarch64_neon_pmull
:
10206 case Intrinsic::aarch64_neon_sqdmull
:
10207 return tryCombineLongOpWithDup(IID
, N
, DCI
, DAG
);
10208 case Intrinsic::aarch64_neon_sqshl
:
10209 case Intrinsic::aarch64_neon_uqshl
:
10210 case Intrinsic::aarch64_neon_sqshlu
:
10211 case Intrinsic::aarch64_neon_srshl
:
10212 case Intrinsic::aarch64_neon_urshl
:
10213 return tryCombineShiftImm(IID
, N
, DAG
);
10214 case Intrinsic::aarch64_crc32b
:
10215 case Intrinsic::aarch64_crc32cb
:
10216 return tryCombineCRC32(0xff, N
, DAG
);
10217 case Intrinsic::aarch64_crc32h
:
10218 case Intrinsic::aarch64_crc32ch
:
10219 return tryCombineCRC32(0xffff, N
, DAG
);
10224 static SDValue
performExtendCombine(SDNode
*N
,
10225 TargetLowering::DAGCombinerInfo
&DCI
,
10226 SelectionDAG
&DAG
) {
10227 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10228 // we can convert that DUP into another extract_high (of a bigger DUP), which
10229 // helps the backend to decide that an sabdl2 would be useful, saving a real
10230 // extract_high operation.
10231 if (!DCI
.isBeforeLegalizeOps() && N
->getOpcode() == ISD::ZERO_EXTEND
&&
10232 N
->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN
) {
10233 SDNode
*ABDNode
= N
->getOperand(0).getNode();
10234 unsigned IID
= getIntrinsicID(ABDNode
);
10235 if (IID
== Intrinsic::aarch64_neon_sabd
||
10236 IID
== Intrinsic::aarch64_neon_uabd
) {
10237 SDValue NewABD
= tryCombineLongOpWithDup(IID
, ABDNode
, DCI
, DAG
);
10238 if (!NewABD
.getNode())
10241 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
), N
->getValueType(0),
10246 // This is effectively a custom type legalization for AArch64.
10248 // Type legalization will split an extend of a small, legal, type to a larger
10249 // illegal type by first splitting the destination type, often creating
10250 // illegal source types, which then get legalized in isel-confusing ways,
10251 // leading to really terrible codegen. E.g.,
10252 // %result = v8i32 sext v8i8 %value
10254 // %losrc = extract_subreg %value, ...
10255 // %hisrc = extract_subreg %value, ...
10256 // %lo = v4i32 sext v4i8 %losrc
10257 // %hi = v4i32 sext v4i8 %hisrc
10258 // Things go rapidly downhill from there.
10260 // For AArch64, the [sz]ext vector instructions can only go up one element
10261 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10262 // take two instructions.
10264 // This implies that the most efficient way to do the extend from v8i8
10265 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10266 // the normal splitting to happen for the v8i16->v8i32.
10268 // This is pre-legalization to catch some cases where the default
10269 // type legalization will create ill-tempered code.
10270 if (!DCI
.isBeforeLegalizeOps())
10273 // We're only interested in cleaning things up for non-legal vector types
10274 // here. If both the source and destination are legal, things will just
10275 // work naturally without any fiddling.
10276 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
10277 EVT ResVT
= N
->getValueType(0);
10278 if (!ResVT
.isVector() || TLI
.isTypeLegal(ResVT
))
10280 // If the vector type isn't a simple VT, it's beyond the scope of what
10281 // we're worried about here. Let legalization do its thing and hope for
10283 SDValue Src
= N
->getOperand(0);
10284 EVT SrcVT
= Src
->getValueType(0);
10285 if (!ResVT
.isSimple() || !SrcVT
.isSimple())
10288 // If the source VT is a 64-bit vector, we can play games and get the
10289 // better results we want.
10290 if (SrcVT
.getSizeInBits() != 64)
10293 unsigned SrcEltSize
= SrcVT
.getScalarSizeInBits();
10294 unsigned ElementCount
= SrcVT
.getVectorNumElements();
10295 SrcVT
= MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize
* 2), ElementCount
);
10297 Src
= DAG
.getNode(N
->getOpcode(), DL
, SrcVT
, Src
);
10299 // Now split the rest of the operation into two halves, each with a 64
10303 unsigned NumElements
= ResVT
.getVectorNumElements();
10304 assert(!(NumElements
& 1) && "Splitting vector, but not in half!");
10305 LoVT
= HiVT
= EVT::getVectorVT(*DAG
.getContext(),
10306 ResVT
.getVectorElementType(), NumElements
/ 2);
10308 EVT InNVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
.getVectorElementType(),
10309 LoVT
.getVectorNumElements());
10310 Lo
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InNVT
, Src
,
10311 DAG
.getConstant(0, DL
, MVT::i64
));
10312 Hi
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InNVT
, Src
,
10313 DAG
.getConstant(InNVT
.getVectorNumElements(), DL
, MVT::i64
));
10314 Lo
= DAG
.getNode(N
->getOpcode(), DL
, LoVT
, Lo
);
10315 Hi
= DAG
.getNode(N
->getOpcode(), DL
, HiVT
, Hi
);
10317 // Now combine the parts back together so we still have a single result
10318 // like the combiner expects.
10319 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, ResVT
, Lo
, Hi
);
10322 static SDValue
splitStoreSplat(SelectionDAG
&DAG
, StoreSDNode
&St
,
10323 SDValue SplatVal
, unsigned NumVecElts
) {
10324 assert(!St
.isTruncatingStore() && "cannot split truncating vector store");
10325 unsigned OrigAlignment
= St
.getAlignment();
10326 unsigned EltOffset
= SplatVal
.getValueType().getSizeInBits() / 8;
10328 // Create scalar stores. This is at least as good as the code sequence for a
10329 // split unaligned store which is a dup.s, ext.b, and two stores.
10330 // Most of the time the three stores should be replaced by store pair
10331 // instructions (stp).
10333 SDValue BasePtr
= St
.getBasePtr();
10334 uint64_t BaseOffset
= 0;
10336 const MachinePointerInfo
&PtrInfo
= St
.getPointerInfo();
10338 DAG
.getStore(St
.getChain(), DL
, SplatVal
, BasePtr
, PtrInfo
,
10339 OrigAlignment
, St
.getMemOperand()->getFlags());
10341 // As this in ISel, we will not merge this add which may degrade results.
10342 if (BasePtr
->getOpcode() == ISD::ADD
&&
10343 isa
<ConstantSDNode
>(BasePtr
->getOperand(1))) {
10344 BaseOffset
= cast
<ConstantSDNode
>(BasePtr
->getOperand(1))->getSExtValue();
10345 BasePtr
= BasePtr
->getOperand(0);
10348 unsigned Offset
= EltOffset
;
10349 while (--NumVecElts
) {
10350 unsigned Alignment
= MinAlign(OrigAlignment
, Offset
);
10351 SDValue OffsetPtr
=
10352 DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, BasePtr
,
10353 DAG
.getConstant(BaseOffset
+ Offset
, DL
, MVT::i64
));
10354 NewST1
= DAG
.getStore(NewST1
.getValue(0), DL
, SplatVal
, OffsetPtr
,
10355 PtrInfo
.getWithOffset(Offset
), Alignment
,
10356 St
.getMemOperand()->getFlags());
10357 Offset
+= EltOffset
;
10362 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10363 /// load store optimizer pass will merge them to store pair stores. This should
10364 /// be better than a movi to create the vector zero followed by a vector store
10365 /// if the zero constant is not re-used, since one instructions and one register
10366 /// live range will be removed.
10368 /// For example, the final generated code should be:
10370 /// stp xzr, xzr, [x0]
10377 static SDValue
replaceZeroVectorStore(SelectionDAG
&DAG
, StoreSDNode
&St
) {
10378 SDValue StVal
= St
.getValue();
10379 EVT VT
= StVal
.getValueType();
10381 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10382 // 2, 3 or 4 i32 elements.
10383 int NumVecElts
= VT
.getVectorNumElements();
10384 if (!(((NumVecElts
== 2 || NumVecElts
== 3) &&
10385 VT
.getVectorElementType().getSizeInBits() == 64) ||
10386 ((NumVecElts
== 2 || NumVecElts
== 3 || NumVecElts
== 4) &&
10387 VT
.getVectorElementType().getSizeInBits() == 32)))
10390 if (StVal
.getOpcode() != ISD::BUILD_VECTOR
)
10393 // If the zero constant has more than one use then the vector store could be
10394 // better since the constant mov will be amortized and stp q instructions
10395 // should be able to be formed.
10396 if (!StVal
.hasOneUse())
10399 // If the store is truncating then it's going down to i16 or smaller, which
10400 // means it can be implemented in a single store anyway.
10401 if (St
.isTruncatingStore())
10404 // If the immediate offset of the address operand is too large for the stp
10405 // instruction, then bail out.
10406 if (DAG
.isBaseWithConstantOffset(St
.getBasePtr())) {
10407 int64_t Offset
= St
.getBasePtr()->getConstantOperandVal(1);
10408 if (Offset
< -512 || Offset
> 504)
10412 for (int I
= 0; I
< NumVecElts
; ++I
) {
10413 SDValue EltVal
= StVal
.getOperand(I
);
10414 if (!isNullConstant(EltVal
) && !isNullFPConstant(EltVal
))
10418 // Use a CopyFromReg WZR/XZR here to prevent
10419 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10423 if (VT
.getVectorElementType().getSizeInBits() == 32) {
10424 ZeroReg
= AArch64::WZR
;
10427 ZeroReg
= AArch64::XZR
;
10431 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, ZeroReg
, ZeroVT
);
10432 return splitStoreSplat(DAG
, St
, SplatVal
, NumVecElts
);
10435 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10436 /// value. The load store optimizer pass will merge them to store pair stores.
10437 /// This has better performance than a splat of the scalar followed by a split
10438 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10439 /// followed by an ext.b and two stores.
10440 static SDValue
replaceSplatVectorStore(SelectionDAG
&DAG
, StoreSDNode
&St
) {
10441 SDValue StVal
= St
.getValue();
10442 EVT VT
= StVal
.getValueType();
10444 // Don't replace floating point stores, they possibly won't be transformed to
10445 // stp because of the store pair suppress pass.
10446 if (VT
.isFloatingPoint())
10449 // We can express a splat as store pair(s) for 2 or 4 elements.
10450 unsigned NumVecElts
= VT
.getVectorNumElements();
10451 if (NumVecElts
!= 4 && NumVecElts
!= 2)
10454 // If the store is truncating then it's going down to i16 or smaller, which
10455 // means it can be implemented in a single store anyway.
10456 if (St
.isTruncatingStore())
10459 // Check that this is a splat.
10460 // Make sure that each of the relevant vector element locations are inserted
10461 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10462 std::bitset
<4> IndexNotInserted((1 << NumVecElts
) - 1);
10464 for (unsigned I
= 0; I
< NumVecElts
; ++I
) {
10465 // Check for insert vector elements.
10466 if (StVal
.getOpcode() != ISD::INSERT_VECTOR_ELT
)
10469 // Check that same value is inserted at each vector element.
10471 SplatVal
= StVal
.getOperand(1);
10472 else if (StVal
.getOperand(1) != SplatVal
)
10475 // Check insert element index.
10476 ConstantSDNode
*CIndex
= dyn_cast
<ConstantSDNode
>(StVal
.getOperand(2));
10479 uint64_t IndexVal
= CIndex
->getZExtValue();
10480 if (IndexVal
>= NumVecElts
)
10482 IndexNotInserted
.reset(IndexVal
);
10484 StVal
= StVal
.getOperand(0);
10486 // Check that all vector element locations were inserted to.
10487 if (IndexNotInserted
.any())
10490 return splitStoreSplat(DAG
, St
, SplatVal
, NumVecElts
);
10493 static SDValue
splitStores(SDNode
*N
, TargetLowering::DAGCombinerInfo
&DCI
,
10495 const AArch64Subtarget
*Subtarget
) {
10497 StoreSDNode
*S
= cast
<StoreSDNode
>(N
);
10498 if (S
->isVolatile() || S
->isIndexed())
10501 SDValue StVal
= S
->getValue();
10502 EVT VT
= StVal
.getValueType();
10503 if (!VT
.isVector())
10506 // If we get a splat of zeros, convert this vector store to a store of
10507 // scalars. They will be merged into store pairs of xzr thereby removing one
10508 // instruction and one register.
10509 if (SDValue ReplacedZeroSplat
= replaceZeroVectorStore(DAG
, *S
))
10510 return ReplacedZeroSplat
;
10512 // FIXME: The logic for deciding if an unaligned store should be split should
10513 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10514 // a call to that function here.
10516 if (!Subtarget
->isMisaligned128StoreSlow())
10519 // Don't split at -Oz.
10520 if (DAG
.getMachineFunction().getFunction().hasMinSize())
10523 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10524 // those up regresses performance on micro-benchmarks and olden/bh.
10525 if (VT
.getVectorNumElements() < 2 || VT
== MVT::v2i64
)
10528 // Split unaligned 16B stores. They are terrible for performance.
10529 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10530 // extensions can use this to mark that it does not want splitting to happen
10531 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10532 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10533 if (VT
.getSizeInBits() != 128 || S
->getAlignment() >= 16 ||
10534 S
->getAlignment() <= 2)
10537 // If we get a splat of a scalar convert this vector store to a store of
10538 // scalars. They will be merged into store pairs thereby removing two
10540 if (SDValue ReplacedSplat
= replaceSplatVectorStore(DAG
, *S
))
10541 return ReplacedSplat
;
10544 unsigned NumElts
= VT
.getVectorNumElements() / 2;
10545 // Split VT into two.
10547 EVT::getVectorVT(*DAG
.getContext(), VT
.getVectorElementType(), NumElts
);
10548 SDValue SubVector0
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, HalfVT
, StVal
,
10549 DAG
.getConstant(0, DL
, MVT::i64
));
10550 SDValue SubVector1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, HalfVT
, StVal
,
10551 DAG
.getConstant(NumElts
, DL
, MVT::i64
));
10552 SDValue BasePtr
= S
->getBasePtr();
10554 DAG
.getStore(S
->getChain(), DL
, SubVector0
, BasePtr
, S
->getPointerInfo(),
10555 S
->getAlignment(), S
->getMemOperand()->getFlags());
10556 SDValue OffsetPtr
= DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, BasePtr
,
10557 DAG
.getConstant(8, DL
, MVT::i64
));
10558 return DAG
.getStore(NewST1
.getValue(0), DL
, SubVector1
, OffsetPtr
,
10559 S
->getPointerInfo(), S
->getAlignment(),
10560 S
->getMemOperand()->getFlags());
10563 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10564 /// post-increment LD1R.
10565 static SDValue
performPostLD1Combine(SDNode
*N
,
10566 TargetLowering::DAGCombinerInfo
&DCI
,
10568 if (DCI
.isBeforeLegalizeOps())
10571 SelectionDAG
&DAG
= DCI
.DAG
;
10572 EVT VT
= N
->getValueType(0);
10574 unsigned LoadIdx
= IsLaneOp
? 1 : 0;
10575 SDNode
*LD
= N
->getOperand(LoadIdx
).getNode();
10576 // If it is not LOAD, can not do such combine.
10577 if (LD
->getOpcode() != ISD::LOAD
)
10580 // The vector lane must be a constant in the LD1LANE opcode.
10583 Lane
= N
->getOperand(2);
10584 auto *LaneC
= dyn_cast
<ConstantSDNode
>(Lane
);
10585 if (!LaneC
|| LaneC
->getZExtValue() >= VT
.getVectorNumElements())
10589 LoadSDNode
*LoadSDN
= cast
<LoadSDNode
>(LD
);
10590 EVT MemVT
= LoadSDN
->getMemoryVT();
10591 // Check if memory operand is the same type as the vector element.
10592 if (MemVT
!= VT
.getVectorElementType())
10595 // Check if there are other uses. If so, do not combine as it will introduce
10597 for (SDNode::use_iterator UI
= LD
->use_begin(), UE
= LD
->use_end(); UI
!= UE
;
10599 if (UI
.getUse().getResNo() == 1) // Ignore uses of the chain result.
10605 SDValue Addr
= LD
->getOperand(1);
10606 SDValue Vector
= N
->getOperand(0);
10607 // Search for a use of the address operand that is an increment.
10608 for (SDNode::use_iterator UI
= Addr
.getNode()->use_begin(), UE
=
10609 Addr
.getNode()->use_end(); UI
!= UE
; ++UI
) {
10610 SDNode
*User
= *UI
;
10611 if (User
->getOpcode() != ISD::ADD
10612 || UI
.getUse().getResNo() != Addr
.getResNo())
10615 // If the increment is a constant, it must match the memory ref size.
10616 SDValue Inc
= User
->getOperand(User
->getOperand(0) == Addr
? 1 : 0);
10617 if (ConstantSDNode
*CInc
= dyn_cast
<ConstantSDNode
>(Inc
.getNode())) {
10618 uint32_t IncVal
= CInc
->getZExtValue();
10619 unsigned NumBytes
= VT
.getScalarSizeInBits() / 8;
10620 if (IncVal
!= NumBytes
)
10622 Inc
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
10625 // To avoid cycle construction make sure that neither the load nor the add
10626 // are predecessors to each other or the Vector.
10627 SmallPtrSet
<const SDNode
*, 32> Visited
;
10628 SmallVector
<const SDNode
*, 16> Worklist
;
10630 Worklist
.push_back(User
);
10631 Worklist
.push_back(LD
);
10632 Worklist
.push_back(Vector
.getNode());
10633 if (SDNode::hasPredecessorHelper(LD
, Visited
, Worklist
) ||
10634 SDNode::hasPredecessorHelper(User
, Visited
, Worklist
))
10637 SmallVector
<SDValue
, 8> Ops
;
10638 Ops
.push_back(LD
->getOperand(0)); // Chain
10640 Ops
.push_back(Vector
); // The vector to be inserted
10641 Ops
.push_back(Lane
); // The lane to be inserted in the vector
10643 Ops
.push_back(Addr
);
10644 Ops
.push_back(Inc
);
10646 EVT Tys
[3] = { VT
, MVT::i64
, MVT::Other
};
10647 SDVTList SDTys
= DAG
.getVTList(Tys
);
10648 unsigned NewOp
= IsLaneOp
? AArch64ISD::LD1LANEpost
: AArch64ISD::LD1DUPpost
;
10649 SDValue UpdN
= DAG
.getMemIntrinsicNode(NewOp
, SDLoc(N
), SDTys
, Ops
,
10651 LoadSDN
->getMemOperand());
10653 // Update the uses.
10654 SDValue NewResults
[] = {
10655 SDValue(LD
, 0), // The result of load
10656 SDValue(UpdN
.getNode(), 2) // Chain
10658 DCI
.CombineTo(LD
, NewResults
);
10659 DCI
.CombineTo(N
, SDValue(UpdN
.getNode(), 0)); // Dup/Inserted Result
10660 DCI
.CombineTo(User
, SDValue(UpdN
.getNode(), 1)); // Write back register
10667 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10668 /// address translation.
10669 static bool performTBISimplification(SDValue Addr
,
10670 TargetLowering::DAGCombinerInfo
&DCI
,
10671 SelectionDAG
&DAG
) {
10672 APInt DemandedMask
= APInt::getLowBitsSet(64, 56);
10674 TargetLowering::TargetLoweringOpt
TLO(DAG
, !DCI
.isBeforeLegalize(),
10675 !DCI
.isBeforeLegalizeOps());
10676 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
10677 if (TLI
.SimplifyDemandedBits(Addr
, DemandedMask
, Known
, TLO
)) {
10678 DCI
.CommitTargetLoweringOpt(TLO
);
10684 static SDValue
performSTORECombine(SDNode
*N
,
10685 TargetLowering::DAGCombinerInfo
&DCI
,
10687 const AArch64Subtarget
*Subtarget
) {
10688 if (SDValue Split
= splitStores(N
, DCI
, DAG
, Subtarget
))
10691 if (Subtarget
->supportsAddressTopByteIgnored() &&
10692 performTBISimplification(N
->getOperand(2), DCI
, DAG
))
10693 return SDValue(N
, 0);
10699 /// Target-specific DAG combine function for NEON load/store intrinsics
10700 /// to merge base address updates.
10701 static SDValue
performNEONPostLDSTCombine(SDNode
*N
,
10702 TargetLowering::DAGCombinerInfo
&DCI
,
10703 SelectionDAG
&DAG
) {
10704 if (DCI
.isBeforeLegalize() || DCI
.isCalledByLegalizer())
10707 unsigned AddrOpIdx
= N
->getNumOperands() - 1;
10708 SDValue Addr
= N
->getOperand(AddrOpIdx
);
10710 // Search for a use of the address operand that is an increment.
10711 for (SDNode::use_iterator UI
= Addr
.getNode()->use_begin(),
10712 UE
= Addr
.getNode()->use_end(); UI
!= UE
; ++UI
) {
10713 SDNode
*User
= *UI
;
10714 if (User
->getOpcode() != ISD::ADD
||
10715 UI
.getUse().getResNo() != Addr
.getResNo())
10718 // Check that the add is independent of the load/store. Otherwise, folding
10719 // it would create a cycle.
10720 SmallPtrSet
<const SDNode
*, 32> Visited
;
10721 SmallVector
<const SDNode
*, 16> Worklist
;
10722 Visited
.insert(Addr
.getNode());
10723 Worklist
.push_back(N
);
10724 Worklist
.push_back(User
);
10725 if (SDNode::hasPredecessorHelper(N
, Visited
, Worklist
) ||
10726 SDNode::hasPredecessorHelper(User
, Visited
, Worklist
))
10729 // Find the new opcode for the updating load/store.
10730 bool IsStore
= false;
10731 bool IsLaneOp
= false;
10732 bool IsDupOp
= false;
10733 unsigned NewOpc
= 0;
10734 unsigned NumVecs
= 0;
10735 unsigned IntNo
= cast
<ConstantSDNode
>(N
->getOperand(1))->getZExtValue();
10737 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10738 case Intrinsic::aarch64_neon_ld2
: NewOpc
= AArch64ISD::LD2post
;
10739 NumVecs
= 2; break;
10740 case Intrinsic::aarch64_neon_ld3
: NewOpc
= AArch64ISD::LD3post
;
10741 NumVecs
= 3; break;
10742 case Intrinsic::aarch64_neon_ld4
: NewOpc
= AArch64ISD::LD4post
;
10743 NumVecs
= 4; break;
10744 case Intrinsic::aarch64_neon_st2
: NewOpc
= AArch64ISD::ST2post
;
10745 NumVecs
= 2; IsStore
= true; break;
10746 case Intrinsic::aarch64_neon_st3
: NewOpc
= AArch64ISD::ST3post
;
10747 NumVecs
= 3; IsStore
= true; break;
10748 case Intrinsic::aarch64_neon_st4
: NewOpc
= AArch64ISD::ST4post
;
10749 NumVecs
= 4; IsStore
= true; break;
10750 case Intrinsic::aarch64_neon_ld1x2
: NewOpc
= AArch64ISD::LD1x2post
;
10751 NumVecs
= 2; break;
10752 case Intrinsic::aarch64_neon_ld1x3
: NewOpc
= AArch64ISD::LD1x3post
;
10753 NumVecs
= 3; break;
10754 case Intrinsic::aarch64_neon_ld1x4
: NewOpc
= AArch64ISD::LD1x4post
;
10755 NumVecs
= 4; break;
10756 case Intrinsic::aarch64_neon_st1x2
: NewOpc
= AArch64ISD::ST1x2post
;
10757 NumVecs
= 2; IsStore
= true; break;
10758 case Intrinsic::aarch64_neon_st1x3
: NewOpc
= AArch64ISD::ST1x3post
;
10759 NumVecs
= 3; IsStore
= true; break;
10760 case Intrinsic::aarch64_neon_st1x4
: NewOpc
= AArch64ISD::ST1x4post
;
10761 NumVecs
= 4; IsStore
= true; break;
10762 case Intrinsic::aarch64_neon_ld2r
: NewOpc
= AArch64ISD::LD2DUPpost
;
10763 NumVecs
= 2; IsDupOp
= true; break;
10764 case Intrinsic::aarch64_neon_ld3r
: NewOpc
= AArch64ISD::LD3DUPpost
;
10765 NumVecs
= 3; IsDupOp
= true; break;
10766 case Intrinsic::aarch64_neon_ld4r
: NewOpc
= AArch64ISD::LD4DUPpost
;
10767 NumVecs
= 4; IsDupOp
= true; break;
10768 case Intrinsic::aarch64_neon_ld2lane
: NewOpc
= AArch64ISD::LD2LANEpost
;
10769 NumVecs
= 2; IsLaneOp
= true; break;
10770 case Intrinsic::aarch64_neon_ld3lane
: NewOpc
= AArch64ISD::LD3LANEpost
;
10771 NumVecs
= 3; IsLaneOp
= true; break;
10772 case Intrinsic::aarch64_neon_ld4lane
: NewOpc
= AArch64ISD::LD4LANEpost
;
10773 NumVecs
= 4; IsLaneOp
= true; break;
10774 case Intrinsic::aarch64_neon_st2lane
: NewOpc
= AArch64ISD::ST2LANEpost
;
10775 NumVecs
= 2; IsStore
= true; IsLaneOp
= true; break;
10776 case Intrinsic::aarch64_neon_st3lane
: NewOpc
= AArch64ISD::ST3LANEpost
;
10777 NumVecs
= 3; IsStore
= true; IsLaneOp
= true; break;
10778 case Intrinsic::aarch64_neon_st4lane
: NewOpc
= AArch64ISD::ST4LANEpost
;
10779 NumVecs
= 4; IsStore
= true; IsLaneOp
= true; break;
10784 VecTy
= N
->getOperand(2).getValueType();
10786 VecTy
= N
->getValueType(0);
10788 // If the increment is a constant, it must match the memory ref size.
10789 SDValue Inc
= User
->getOperand(User
->getOperand(0) == Addr
? 1 : 0);
10790 if (ConstantSDNode
*CInc
= dyn_cast
<ConstantSDNode
>(Inc
.getNode())) {
10791 uint32_t IncVal
= CInc
->getZExtValue();
10792 unsigned NumBytes
= NumVecs
* VecTy
.getSizeInBits() / 8;
10793 if (IsLaneOp
|| IsDupOp
)
10794 NumBytes
/= VecTy
.getVectorNumElements();
10795 if (IncVal
!= NumBytes
)
10797 Inc
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
10799 SmallVector
<SDValue
, 8> Ops
;
10800 Ops
.push_back(N
->getOperand(0)); // Incoming chain
10801 // Load lane and store have vector list as input.
10802 if (IsLaneOp
|| IsStore
)
10803 for (unsigned i
= 2; i
< AddrOpIdx
; ++i
)
10804 Ops
.push_back(N
->getOperand(i
));
10805 Ops
.push_back(Addr
); // Base register
10806 Ops
.push_back(Inc
);
10810 unsigned NumResultVecs
= (IsStore
? 0 : NumVecs
);
10812 for (n
= 0; n
< NumResultVecs
; ++n
)
10814 Tys
[n
++] = MVT::i64
; // Type of write back register
10815 Tys
[n
] = MVT::Other
; // Type of the chain
10816 SDVTList SDTys
= DAG
.getVTList(makeArrayRef(Tys
, NumResultVecs
+ 2));
10818 MemIntrinsicSDNode
*MemInt
= cast
<MemIntrinsicSDNode
>(N
);
10819 SDValue UpdN
= DAG
.getMemIntrinsicNode(NewOpc
, SDLoc(N
), SDTys
, Ops
,
10820 MemInt
->getMemoryVT(),
10821 MemInt
->getMemOperand());
10823 // Update the uses.
10824 std::vector
<SDValue
> NewResults
;
10825 for (unsigned i
= 0; i
< NumResultVecs
; ++i
) {
10826 NewResults
.push_back(SDValue(UpdN
.getNode(), i
));
10828 NewResults
.push_back(SDValue(UpdN
.getNode(), NumResultVecs
+ 1));
10829 DCI
.CombineTo(N
, NewResults
);
10830 DCI
.CombineTo(User
, SDValue(UpdN
.getNode(), NumResultVecs
));
10837 // Checks to see if the value is the prescribed width and returns information
10838 // about its extension mode.
10840 bool checkValueWidth(SDValue V
, unsigned width
, ISD::LoadExtType
&ExtType
) {
10841 ExtType
= ISD::NON_EXTLOAD
;
10842 switch(V
.getNode()->getOpcode()) {
10846 LoadSDNode
*LoadNode
= cast
<LoadSDNode
>(V
.getNode());
10847 if ((LoadNode
->getMemoryVT() == MVT::i8
&& width
== 8)
10848 || (LoadNode
->getMemoryVT() == MVT::i16
&& width
== 16)) {
10849 ExtType
= LoadNode
->getExtensionType();
10854 case ISD::AssertSext
: {
10855 VTSDNode
*TypeNode
= cast
<VTSDNode
>(V
.getNode()->getOperand(1));
10856 if ((TypeNode
->getVT() == MVT::i8
&& width
== 8)
10857 || (TypeNode
->getVT() == MVT::i16
&& width
== 16)) {
10858 ExtType
= ISD::SEXTLOAD
;
10863 case ISD::AssertZext
: {
10864 VTSDNode
*TypeNode
= cast
<VTSDNode
>(V
.getNode()->getOperand(1));
10865 if ((TypeNode
->getVT() == MVT::i8
&& width
== 8)
10866 || (TypeNode
->getVT() == MVT::i16
&& width
== 16)) {
10867 ExtType
= ISD::ZEXTLOAD
;
10872 case ISD::Constant
:
10873 case ISD::TargetConstant
: {
10874 return std::abs(cast
<ConstantSDNode
>(V
.getNode())->getSExtValue()) <
10875 1LL << (width
- 1);
10882 // This function does a whole lot of voodoo to determine if the tests are
10883 // equivalent without and with a mask. Essentially what happens is that given a
10886 // +-------------+ +-------------+ +-------------+ +-------------+
10887 // | Input | | AddConstant | | CompConstant| | CC |
10888 // +-------------+ +-------------+ +-------------+ +-------------+
10890 // V V | +----------+
10891 // +-------------+ +----+ | |
10892 // | ADD | |0xff| | |
10893 // +-------------+ +----+ | |
10896 // +-------------+ | |
10898 // +-------------+ | |
10907 // The AND node may be safely removed for some combinations of inputs. In
10908 // particular we need to take into account the extension type of the Input,
10909 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10910 // width of the input (this can work for any width inputs, the above graph is
10911 // specific to 8 bits.
10913 // The specific equations were worked out by generating output tables for each
10914 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10915 // problem was simplified by working with 4 bit inputs, which means we only
10916 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10917 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10918 // patterns present in both extensions (0,7). For every distinct set of
10919 // AddConstant and CompConstants bit patterns we can consider the masked and
10920 // unmasked versions to be equivalent if the result of this function is true for
10921 // all 16 distinct bit patterns of for the current extension type of Input (w0).
10924 // and w10, w8, #0x0f
10926 // cset w9, AArch64CC
10928 // cset w11, AArch64CC
10933 // Since the above function shows when the outputs are equivalent it defines
10934 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10935 // would be expensive to run during compiles. The equations below were written
10936 // in a test harness that confirmed they gave equivalent outputs to the above
10937 // for all inputs function, so they can be used determine if the removal is
10940 // isEquivalentMaskless() is the code for testing if the AND can be removed
10941 // factored out of the DAG recognition as the DAG can take several forms.
10943 static bool isEquivalentMaskless(unsigned CC
, unsigned width
,
10944 ISD::LoadExtType ExtType
, int AddConstant
,
10945 int CompConstant
) {
10946 // By being careful about our equations and only writing the in term
10947 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10948 // make them generally applicable to all bit widths.
10949 int MaxUInt
= (1 << width
);
10951 // For the purposes of these comparisons sign extending the type is
10952 // equivalent to zero extending the add and displacing it by half the integer
10953 // width. Provided we are careful and make sure our equations are valid over
10954 // the whole range we can just adjust the input and avoid writing equations
10955 // for sign extended inputs.
10956 if (ExtType
== ISD::SEXTLOAD
)
10957 AddConstant
-= (1 << (width
-1));
10960 case AArch64CC::LE
:
10961 case AArch64CC::GT
:
10962 if ((AddConstant
== 0) ||
10963 (CompConstant
== MaxUInt
- 1 && AddConstant
< 0) ||
10964 (AddConstant
>= 0 && CompConstant
< 0) ||
10965 (AddConstant
<= 0 && CompConstant
<= 0 && CompConstant
< AddConstant
))
10968 case AArch64CC::LT
:
10969 case AArch64CC::GE
:
10970 if ((AddConstant
== 0) ||
10971 (AddConstant
>= 0 && CompConstant
<= 0) ||
10972 (AddConstant
<= 0 && CompConstant
<= 0 && CompConstant
<= AddConstant
))
10975 case AArch64CC::HI
:
10976 case AArch64CC::LS
:
10977 if ((AddConstant
>= 0 && CompConstant
< 0) ||
10978 (AddConstant
<= 0 && CompConstant
>= -1 &&
10979 CompConstant
< AddConstant
+ MaxUInt
))
10982 case AArch64CC::PL
:
10983 case AArch64CC::MI
:
10984 if ((AddConstant
== 0) ||
10985 (AddConstant
> 0 && CompConstant
<= 0) ||
10986 (AddConstant
< 0 && CompConstant
<= AddConstant
))
10989 case AArch64CC::LO
:
10990 case AArch64CC::HS
:
10991 if ((AddConstant
>= 0 && CompConstant
<= 0) ||
10992 (AddConstant
<= 0 && CompConstant
>= 0 &&
10993 CompConstant
<= AddConstant
+ MaxUInt
))
10996 case AArch64CC::EQ
:
10997 case AArch64CC::NE
:
10998 if ((AddConstant
> 0 && CompConstant
< 0) ||
10999 (AddConstant
< 0 && CompConstant
>= 0 &&
11000 CompConstant
< AddConstant
+ MaxUInt
) ||
11001 (AddConstant
>= 0 && CompConstant
>= 0 &&
11002 CompConstant
>= AddConstant
) ||
11003 (AddConstant
<= 0 && CompConstant
< 0 && CompConstant
< AddConstant
))
11006 case AArch64CC::VS
:
11007 case AArch64CC::VC
:
11008 case AArch64CC::AL
:
11009 case AArch64CC::NV
:
11011 case AArch64CC::Invalid
:
11019 SDValue
performCONDCombine(SDNode
*N
,
11020 TargetLowering::DAGCombinerInfo
&DCI
,
11021 SelectionDAG
&DAG
, unsigned CCIndex
,
11022 unsigned CmpIndex
) {
11023 unsigned CC
= cast
<ConstantSDNode
>(N
->getOperand(CCIndex
))->getSExtValue();
11024 SDNode
*SubsNode
= N
->getOperand(CmpIndex
).getNode();
11025 unsigned CondOpcode
= SubsNode
->getOpcode();
11027 if (CondOpcode
!= AArch64ISD::SUBS
)
11030 // There is a SUBS feeding this condition. Is it fed by a mask we can
11033 SDNode
*AndNode
= SubsNode
->getOperand(0).getNode();
11034 unsigned MaskBits
= 0;
11036 if (AndNode
->getOpcode() != ISD::AND
)
11039 if (ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(AndNode
->getOperand(1))) {
11040 uint32_t CNV
= CN
->getZExtValue();
11043 else if (CNV
== 65535)
11050 SDValue AddValue
= AndNode
->getOperand(0);
11052 if (AddValue
.getOpcode() != ISD::ADD
)
11055 // The basic dag structure is correct, grab the inputs and validate them.
11057 SDValue AddInputValue1
= AddValue
.getNode()->getOperand(0);
11058 SDValue AddInputValue2
= AddValue
.getNode()->getOperand(1);
11059 SDValue SubsInputValue
= SubsNode
->getOperand(1);
11061 // The mask is present and the provenance of all the values is a smaller type,
11062 // lets see if the mask is superfluous.
11064 if (!isa
<ConstantSDNode
>(AddInputValue2
.getNode()) ||
11065 !isa
<ConstantSDNode
>(SubsInputValue
.getNode()))
11068 ISD::LoadExtType ExtType
;
11070 if (!checkValueWidth(SubsInputValue
, MaskBits
, ExtType
) ||
11071 !checkValueWidth(AddInputValue2
, MaskBits
, ExtType
) ||
11072 !checkValueWidth(AddInputValue1
, MaskBits
, ExtType
) )
11075 if(!isEquivalentMaskless(CC
, MaskBits
, ExtType
,
11076 cast
<ConstantSDNode
>(AddInputValue2
.getNode())->getSExtValue(),
11077 cast
<ConstantSDNode
>(SubsInputValue
.getNode())->getSExtValue()))
11080 // The AND is not necessary, remove it.
11082 SDVTList VTs
= DAG
.getVTList(SubsNode
->getValueType(0),
11083 SubsNode
->getValueType(1));
11084 SDValue Ops
[] = { AddValue
, SubsNode
->getOperand(1) };
11086 SDValue NewValue
= DAG
.getNode(CondOpcode
, SDLoc(SubsNode
), VTs
, Ops
);
11087 DAG
.ReplaceAllUsesWith(SubsNode
, NewValue
.getNode());
11089 return SDValue(N
, 0);
11092 // Optimize compare with zero and branch.
11093 static SDValue
performBRCONDCombine(SDNode
*N
,
11094 TargetLowering::DAGCombinerInfo
&DCI
,
11095 SelectionDAG
&DAG
) {
11096 MachineFunction
&MF
= DAG
.getMachineFunction();
11097 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11098 // will not be produced, as they are conditional branch instructions that do
11100 if (MF
.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening
))
11103 if (SDValue NV
= performCONDCombine(N
, DCI
, DAG
, 2, 3))
11105 SDValue Chain
= N
->getOperand(0);
11106 SDValue Dest
= N
->getOperand(1);
11107 SDValue CCVal
= N
->getOperand(2);
11108 SDValue Cmp
= N
->getOperand(3);
11110 assert(isa
<ConstantSDNode
>(CCVal
) && "Expected a ConstantSDNode here!");
11111 unsigned CC
= cast
<ConstantSDNode
>(CCVal
)->getZExtValue();
11112 if (CC
!= AArch64CC::EQ
&& CC
!= AArch64CC::NE
)
11115 unsigned CmpOpc
= Cmp
.getOpcode();
11116 if (CmpOpc
!= AArch64ISD::ADDS
&& CmpOpc
!= AArch64ISD::SUBS
)
11119 // Only attempt folding if there is only one use of the flag and no use of the
11121 if (!Cmp
->hasNUsesOfValue(0, 0) || !Cmp
->hasNUsesOfValue(1, 1))
11124 SDValue LHS
= Cmp
.getOperand(0);
11125 SDValue RHS
= Cmp
.getOperand(1);
11127 assert(LHS
.getValueType() == RHS
.getValueType() &&
11128 "Expected the value type to be the same for both operands!");
11129 if (LHS
.getValueType() != MVT::i32
&& LHS
.getValueType() != MVT::i64
)
11132 if (isNullConstant(LHS
))
11133 std::swap(LHS
, RHS
);
11135 if (!isNullConstant(RHS
))
11138 if (LHS
.getOpcode() == ISD::SHL
|| LHS
.getOpcode() == ISD::SRA
||
11139 LHS
.getOpcode() == ISD::SRL
)
11142 // Fold the compare into the branch instruction.
11144 if (CC
== AArch64CC::EQ
)
11145 BR
= DAG
.getNode(AArch64ISD::CBZ
, SDLoc(N
), MVT::Other
, Chain
, LHS
, Dest
);
11147 BR
= DAG
.getNode(AArch64ISD::CBNZ
, SDLoc(N
), MVT::Other
, Chain
, LHS
, Dest
);
11149 // Do not add new nodes to DAG combiner worklist.
11150 DCI
.CombineTo(N
, BR
, false);
11155 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11156 // as well as whether the test should be inverted. This code is required to
11157 // catch these cases (as opposed to standard dag combines) because
11158 // AArch64ISD::TBZ is matched during legalization.
11159 static SDValue
getTestBitOperand(SDValue Op
, unsigned &Bit
, bool &Invert
,
11160 SelectionDAG
&DAG
) {
11162 if (!Op
->hasOneUse())
11165 // We don't handle undef/constant-fold cases below, as they should have
11166 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11169 // (tbz (trunc x), b) -> (tbz x, b)
11170 // This case is just here to enable more of the below cases to be caught.
11171 if (Op
->getOpcode() == ISD::TRUNCATE
&&
11172 Bit
< Op
->getValueType(0).getSizeInBits()) {
11173 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11176 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11177 if (Op
->getOpcode() == ISD::ANY_EXTEND
&&
11178 Bit
< Op
->getOperand(0).getValueSizeInBits()) {
11179 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11182 if (Op
->getNumOperands() != 2)
11185 auto *C
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1));
11189 switch (Op
->getOpcode()) {
11193 // (tbz (and x, m), b) -> (tbz x, b)
11195 if ((C
->getZExtValue() >> Bit
) & 1)
11196 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11199 // (tbz (shl x, c), b) -> (tbz x, b-c)
11201 if (C
->getZExtValue() <= Bit
&&
11202 (Bit
- C
->getZExtValue()) < Op
->getValueType(0).getSizeInBits()) {
11203 Bit
= Bit
- C
->getZExtValue();
11204 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11208 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11210 Bit
= Bit
+ C
->getZExtValue();
11211 if (Bit
>= Op
->getValueType(0).getSizeInBits())
11212 Bit
= Op
->getValueType(0).getSizeInBits() - 1;
11213 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11215 // (tbz (srl x, c), b) -> (tbz x, b+c)
11217 if ((Bit
+ C
->getZExtValue()) < Op
->getValueType(0).getSizeInBits()) {
11218 Bit
= Bit
+ C
->getZExtValue();
11219 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11223 // (tbz (xor x, -1), b) -> (tbnz x, b)
11225 if ((C
->getZExtValue() >> Bit
) & 1)
11227 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11231 // Optimize test single bit zero/non-zero and branch.
11232 static SDValue
performTBZCombine(SDNode
*N
,
11233 TargetLowering::DAGCombinerInfo
&DCI
,
11234 SelectionDAG
&DAG
) {
11235 unsigned Bit
= cast
<ConstantSDNode
>(N
->getOperand(2))->getZExtValue();
11236 bool Invert
= false;
11237 SDValue TestSrc
= N
->getOperand(1);
11238 SDValue NewTestSrc
= getTestBitOperand(TestSrc
, Bit
, Invert
, DAG
);
11240 if (TestSrc
== NewTestSrc
)
11243 unsigned NewOpc
= N
->getOpcode();
11245 if (NewOpc
== AArch64ISD::TBZ
)
11246 NewOpc
= AArch64ISD::TBNZ
;
11248 assert(NewOpc
== AArch64ISD::TBNZ
);
11249 NewOpc
= AArch64ISD::TBZ
;
11254 return DAG
.getNode(NewOpc
, DL
, MVT::Other
, N
->getOperand(0), NewTestSrc
,
11255 DAG
.getConstant(Bit
, DL
, MVT::i64
), N
->getOperand(3));
11258 // vselect (v1i1 setcc) ->
11259 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
11260 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11261 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11263 static SDValue
performVSelectCombine(SDNode
*N
, SelectionDAG
&DAG
) {
11264 SDValue N0
= N
->getOperand(0);
11265 EVT CCVT
= N0
.getValueType();
11267 if (N0
.getOpcode() != ISD::SETCC
|| CCVT
.getVectorNumElements() != 1 ||
11268 CCVT
.getVectorElementType() != MVT::i1
)
11271 EVT ResVT
= N
->getValueType(0);
11272 EVT CmpVT
= N0
.getOperand(0).getValueType();
11273 // Only combine when the result type is of the same size as the compared
11275 if (ResVT
.getSizeInBits() != CmpVT
.getSizeInBits())
11278 SDValue IfTrue
= N
->getOperand(1);
11279 SDValue IfFalse
= N
->getOperand(2);
11281 DAG
.getSetCC(SDLoc(N
), CmpVT
.changeVectorElementTypeToInteger(),
11282 N0
.getOperand(0), N0
.getOperand(1),
11283 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
11284 return DAG
.getNode(ISD::VSELECT
, SDLoc(N
), ResVT
, SetCC
,
11288 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11289 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11290 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11291 /// with a vector one followed by a DUP shuffle on the result.
11292 static SDValue
performSelectCombine(SDNode
*N
,
11293 TargetLowering::DAGCombinerInfo
&DCI
) {
11294 SelectionDAG
&DAG
= DCI
.DAG
;
11295 SDValue N0
= N
->getOperand(0);
11296 EVT ResVT
= N
->getValueType(0);
11298 if (N0
.getOpcode() != ISD::SETCC
)
11301 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11302 // scalar SetCCResultType. We also don't expect vectors, because we assume
11303 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11304 assert((N0
.getValueType() == MVT::i1
|| N0
.getValueType() == MVT::i32
) &&
11305 "Scalar-SETCC feeding SELECT has unexpected result type!");
11307 // If NumMaskElts == 0, the comparison is larger than select result. The
11308 // largest real NEON comparison is 64-bits per lane, which means the result is
11309 // at most 32-bits and an illegal vector. Just bail out for now.
11310 EVT SrcVT
= N0
.getOperand(0).getValueType();
11312 // Don't try to do this optimization when the setcc itself has i1 operands.
11313 // There are no legal vectors of i1, so this would be pointless.
11314 if (SrcVT
== MVT::i1
)
11317 int NumMaskElts
= ResVT
.getSizeInBits() / SrcVT
.getSizeInBits();
11318 if (!ResVT
.isVector() || NumMaskElts
== 0)
11321 SrcVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
, NumMaskElts
);
11322 EVT CCVT
= SrcVT
.changeVectorElementTypeToInteger();
11324 // Also bail out if the vector CCVT isn't the same size as ResVT.
11325 // This can happen if the SETCC operand size doesn't divide the ResVT size
11326 // (e.g., f64 vs v3f32).
11327 if (CCVT
.getSizeInBits() != ResVT
.getSizeInBits())
11330 // Make sure we didn't create illegal types, if we're not supposed to.
11331 assert(DCI
.isBeforeLegalize() ||
11332 DAG
.getTargetLoweringInfo().isTypeLegal(SrcVT
));
11334 // First perform a vector comparison, where lane 0 is the one we're interested
11338 DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, SrcVT
, N0
.getOperand(0));
11340 DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, SrcVT
, N0
.getOperand(1));
11341 SDValue SetCC
= DAG
.getNode(ISD::SETCC
, DL
, CCVT
, LHS
, RHS
, N0
.getOperand(2));
11343 // Now duplicate the comparison mask we want across all other lanes.
11344 SmallVector
<int, 8> DUPMask(CCVT
.getVectorNumElements(), 0);
11345 SDValue Mask
= DAG
.getVectorShuffle(CCVT
, DL
, SetCC
, SetCC
, DUPMask
);
11346 Mask
= DAG
.getNode(ISD::BITCAST
, DL
,
11347 ResVT
.changeVectorElementTypeToInteger(), Mask
);
11349 return DAG
.getSelect(DL
, ResVT
, Mask
, N
->getOperand(1), N
->getOperand(2));
11352 /// Get rid of unnecessary NVCASTs (that don't change the type).
11353 static SDValue
performNVCASTCombine(SDNode
*N
) {
11354 if (N
->getValueType(0) == N
->getOperand(0).getValueType())
11355 return N
->getOperand(0);
11360 // If all users of the globaladdr are of the form (globaladdr + constant), find
11361 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11362 // globaladdr as (globaladdr + constant) - constant.
11363 static SDValue
performGlobalAddressCombine(SDNode
*N
, SelectionDAG
&DAG
,
11364 const AArch64Subtarget
*Subtarget
,
11365 const TargetMachine
&TM
) {
11366 auto *GN
= cast
<GlobalAddressSDNode
>(N
);
11367 if (Subtarget
->ClassifyGlobalReference(GN
->getGlobal(), TM
) !=
11368 AArch64II::MO_NO_FLAG
)
11371 uint64_t MinOffset
= -1ull;
11372 for (SDNode
*N
: GN
->uses()) {
11373 if (N
->getOpcode() != ISD::ADD
)
11375 auto *C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(0));
11377 C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
11380 MinOffset
= std::min(MinOffset
, C
->getZExtValue());
11382 uint64_t Offset
= MinOffset
+ GN
->getOffset();
11384 // Require that the new offset is larger than the existing one. Otherwise, we
11385 // can end up oscillating between two possible DAGs, for example,
11386 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11387 if (Offset
<= uint64_t(GN
->getOffset()))
11390 // Check whether folding this offset is legal. It must not go out of bounds of
11391 // the referenced object to avoid violating the code model, and must be
11392 // smaller than 2^21 because this is the largest offset expressible in all
11395 // This check also prevents us from folding negative offsets, which will end
11396 // up being treated in the same way as large positive ones. They could also
11397 // cause code model violations, and aren't really common enough to matter.
11398 if (Offset
>= (1 << 21))
11401 const GlobalValue
*GV
= GN
->getGlobal();
11402 Type
*T
= GV
->getValueType();
11403 if (!T
->isSized() ||
11404 Offset
> GV
->getParent()->getDataLayout().getTypeAllocSize(T
))
11408 SDValue Result
= DAG
.getGlobalAddress(GV
, DL
, MVT::i64
, Offset
);
11409 return DAG
.getNode(ISD::SUB
, DL
, MVT::i64
, Result
,
11410 DAG
.getConstant(MinOffset
, DL
, MVT::i64
));
11413 SDValue
AArch64TargetLowering::PerformDAGCombine(SDNode
*N
,
11414 DAGCombinerInfo
&DCI
) const {
11415 SelectionDAG
&DAG
= DCI
.DAG
;
11416 switch (N
->getOpcode()) {
11418 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11422 return performAddSubLongCombine(N
, DCI
, DAG
);
11424 return performXorCombine(N
, DAG
, DCI
, Subtarget
);
11426 return performMulCombine(N
, DAG
, DCI
, Subtarget
);
11427 case ISD::SINT_TO_FP
:
11428 case ISD::UINT_TO_FP
:
11429 return performIntToFpCombine(N
, DAG
, Subtarget
);
11430 case ISD::FP_TO_SINT
:
11431 case ISD::FP_TO_UINT
:
11432 return performFpToIntCombine(N
, DAG
, DCI
, Subtarget
);
11434 return performFDivCombine(N
, DAG
, DCI
, Subtarget
);
11436 return performORCombine(N
, DCI
, Subtarget
);
11438 return performANDCombine(N
, DCI
);
11440 return performSRLCombine(N
, DCI
);
11441 case ISD::INTRINSIC_WO_CHAIN
:
11442 return performIntrinsicCombine(N
, DCI
, Subtarget
);
11443 case ISD::ANY_EXTEND
:
11444 case ISD::ZERO_EXTEND
:
11445 case ISD::SIGN_EXTEND
:
11446 return performExtendCombine(N
, DCI
, DAG
);
11448 return performBitcastCombine(N
, DCI
, DAG
);
11449 case ISD::CONCAT_VECTORS
:
11450 return performConcatVectorsCombine(N
, DCI
, DAG
);
11452 return performSelectCombine(N
, DCI
);
11454 return performVSelectCombine(N
, DCI
.DAG
);
11456 if (performTBISimplification(N
->getOperand(1), DCI
, DAG
))
11457 return SDValue(N
, 0);
11460 return performSTORECombine(N
, DCI
, DAG
, Subtarget
);
11461 case AArch64ISD::BRCOND
:
11462 return performBRCONDCombine(N
, DCI
, DAG
);
11463 case AArch64ISD::TBNZ
:
11464 case AArch64ISD::TBZ
:
11465 return performTBZCombine(N
, DCI
, DAG
);
11466 case AArch64ISD::CSEL
:
11467 return performCONDCombine(N
, DCI
, DAG
, 2, 3);
11468 case AArch64ISD::DUP
:
11469 return performPostLD1Combine(N
, DCI
, false);
11470 case AArch64ISD::NVCAST
:
11471 return performNVCASTCombine(N
);
11472 case ISD::INSERT_VECTOR_ELT
:
11473 return performPostLD1Combine(N
, DCI
, true);
11474 case ISD::INTRINSIC_VOID
:
11475 case ISD::INTRINSIC_W_CHAIN
:
11476 switch (cast
<ConstantSDNode
>(N
->getOperand(1))->getZExtValue()) {
11477 case Intrinsic::aarch64_neon_ld2
:
11478 case Intrinsic::aarch64_neon_ld3
:
11479 case Intrinsic::aarch64_neon_ld4
:
11480 case Intrinsic::aarch64_neon_ld1x2
:
11481 case Intrinsic::aarch64_neon_ld1x3
:
11482 case Intrinsic::aarch64_neon_ld1x4
:
11483 case Intrinsic::aarch64_neon_ld2lane
:
11484 case Intrinsic::aarch64_neon_ld3lane
:
11485 case Intrinsic::aarch64_neon_ld4lane
:
11486 case Intrinsic::aarch64_neon_ld2r
:
11487 case Intrinsic::aarch64_neon_ld3r
:
11488 case Intrinsic::aarch64_neon_ld4r
:
11489 case Intrinsic::aarch64_neon_st2
:
11490 case Intrinsic::aarch64_neon_st3
:
11491 case Intrinsic::aarch64_neon_st4
:
11492 case Intrinsic::aarch64_neon_st1x2
:
11493 case Intrinsic::aarch64_neon_st1x3
:
11494 case Intrinsic::aarch64_neon_st1x4
:
11495 case Intrinsic::aarch64_neon_st2lane
:
11496 case Intrinsic::aarch64_neon_st3lane
:
11497 case Intrinsic::aarch64_neon_st4lane
:
11498 return performNEONPostLDSTCombine(N
, DCI
, DAG
);
11503 case ISD::GlobalAddress
:
11504 return performGlobalAddressCombine(N
, DAG
, Subtarget
, getTargetMachine());
11509 // Check if the return value is used as only a return value, as otherwise
11510 // we can't perform a tail-call. In particular, we need to check for
11511 // target ISD nodes that are returns and any other "odd" constructs
11512 // that the generic analysis code won't necessarily catch.
11513 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode
*N
,
11514 SDValue
&Chain
) const {
11515 if (N
->getNumValues() != 1)
11517 if (!N
->hasNUsesOfValue(1, 0))
11520 SDValue TCChain
= Chain
;
11521 SDNode
*Copy
= *N
->use_begin();
11522 if (Copy
->getOpcode() == ISD::CopyToReg
) {
11523 // If the copy has a glue operand, we conservatively assume it isn't safe to
11524 // perform a tail call.
11525 if (Copy
->getOperand(Copy
->getNumOperands() - 1).getValueType() ==
11528 TCChain
= Copy
->getOperand(0);
11529 } else if (Copy
->getOpcode() != ISD::FP_EXTEND
)
11532 bool HasRet
= false;
11533 for (SDNode
*Node
: Copy
->uses()) {
11534 if (Node
->getOpcode() != AArch64ISD::RET_FLAG
)
11546 // Return whether the an instruction can potentially be optimized to a tail
11547 // call. This will cause the optimizers to attempt to move, or duplicate,
11548 // return instructions to help enable tail call optimizations for this
11550 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst
*CI
) const {
11551 return CI
->isTailCall();
11554 bool AArch64TargetLowering::getIndexedAddressParts(SDNode
*Op
, SDValue
&Base
,
11556 ISD::MemIndexedMode
&AM
,
11558 SelectionDAG
&DAG
) const {
11559 if (Op
->getOpcode() != ISD::ADD
&& Op
->getOpcode() != ISD::SUB
)
11562 Base
= Op
->getOperand(0);
11563 // All of the indexed addressing mode instructions take a signed
11564 // 9 bit immediate offset.
11565 if (ConstantSDNode
*RHS
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1))) {
11566 int64_t RHSC
= RHS
->getSExtValue();
11567 if (Op
->getOpcode() == ISD::SUB
)
11568 RHSC
= -(uint64_t)RHSC
;
11569 if (!isInt
<9>(RHSC
))
11571 IsInc
= (Op
->getOpcode() == ISD::ADD
);
11572 Offset
= Op
->getOperand(1);
11578 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode
*N
, SDValue
&Base
,
11580 ISD::MemIndexedMode
&AM
,
11581 SelectionDAG
&DAG
) const {
11584 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
11585 VT
= LD
->getMemoryVT();
11586 Ptr
= LD
->getBasePtr();
11587 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
11588 VT
= ST
->getMemoryVT();
11589 Ptr
= ST
->getBasePtr();
11594 if (!getIndexedAddressParts(Ptr
.getNode(), Base
, Offset
, AM
, IsInc
, DAG
))
11596 AM
= IsInc
? ISD::PRE_INC
: ISD::PRE_DEC
;
11600 bool AArch64TargetLowering::getPostIndexedAddressParts(
11601 SDNode
*N
, SDNode
*Op
, SDValue
&Base
, SDValue
&Offset
,
11602 ISD::MemIndexedMode
&AM
, SelectionDAG
&DAG
) const {
11605 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
11606 VT
= LD
->getMemoryVT();
11607 Ptr
= LD
->getBasePtr();
11608 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
11609 VT
= ST
->getMemoryVT();
11610 Ptr
= ST
->getBasePtr();
11615 if (!getIndexedAddressParts(Op
, Base
, Offset
, AM
, IsInc
, DAG
))
11617 // Post-indexing updates the base, so it's not a valid transform
11618 // if that's not the same as the load's pointer.
11621 AM
= IsInc
? ISD::POST_INC
: ISD::POST_DEC
;
11625 static void ReplaceBITCASTResults(SDNode
*N
, SmallVectorImpl
<SDValue
> &Results
,
11626 SelectionDAG
&DAG
) {
11628 SDValue Op
= N
->getOperand(0);
11630 if (N
->getValueType(0) != MVT::i16
|| Op
.getValueType() != MVT::f16
)
11634 DAG
.getMachineNode(TargetOpcode::INSERT_SUBREG
, DL
, MVT::f32
,
11635 DAG
.getUNDEF(MVT::i32
), Op
,
11636 DAG
.getTargetConstant(AArch64::hsub
, DL
, MVT::i32
)),
11638 Op
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::i32
, Op
);
11639 Results
.push_back(DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i16
, Op
));
11642 static void ReplaceReductionResults(SDNode
*N
,
11643 SmallVectorImpl
<SDValue
> &Results
,
11644 SelectionDAG
&DAG
, unsigned InterOp
,
11645 unsigned AcrossOp
) {
11649 std::tie(LoVT
, HiVT
) = DAG
.GetSplitDestVTs(N
->getValueType(0));
11650 std::tie(Lo
, Hi
) = DAG
.SplitVectorOperand(N
, 0);
11651 SDValue InterVal
= DAG
.getNode(InterOp
, dl
, LoVT
, Lo
, Hi
);
11652 SDValue SplitVal
= DAG
.getNode(AcrossOp
, dl
, LoVT
, InterVal
);
11653 Results
.push_back(SplitVal
);
11656 static std::pair
<SDValue
, SDValue
> splitInt128(SDValue N
, SelectionDAG
&DAG
) {
11658 SDValue Lo
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i64
, N
);
11659 SDValue Hi
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i64
,
11660 DAG
.getNode(ISD::SRL
, DL
, MVT::i128
, N
,
11661 DAG
.getConstant(64, DL
, MVT::i64
)));
11662 return std::make_pair(Lo
, Hi
);
11665 // Create an even/odd pair of X registers holding integer value V.
11666 static SDValue
createGPRPairNode(SelectionDAG
&DAG
, SDValue V
) {
11667 SDLoc
dl(V
.getNode());
11668 SDValue VLo
= DAG
.getAnyExtOrTrunc(V
, dl
, MVT::i64
);
11669 SDValue VHi
= DAG
.getAnyExtOrTrunc(
11670 DAG
.getNode(ISD::SRL
, dl
, MVT::i128
, V
, DAG
.getConstant(64, dl
, MVT::i64
)),
11672 if (DAG
.getDataLayout().isBigEndian())
11673 std::swap (VLo
, VHi
);
11675 DAG
.getTargetConstant(AArch64::XSeqPairsClassRegClassID
, dl
, MVT::i32
);
11676 SDValue SubReg0
= DAG
.getTargetConstant(AArch64::sube64
, dl
, MVT::i32
);
11677 SDValue SubReg1
= DAG
.getTargetConstant(AArch64::subo64
, dl
, MVT::i32
);
11678 const SDValue Ops
[] = { RegClass
, VLo
, SubReg0
, VHi
, SubReg1
};
11680 DAG
.getMachineNode(TargetOpcode::REG_SEQUENCE
, dl
, MVT::Untyped
, Ops
), 0);
11683 static void ReplaceCMP_SWAP_128Results(SDNode
*N
,
11684 SmallVectorImpl
<SDValue
> &Results
,
11686 const AArch64Subtarget
*Subtarget
) {
11687 assert(N
->getValueType(0) == MVT::i128
&&
11688 "AtomicCmpSwap on types less than 128 should be legal");
11690 if (Subtarget
->hasLSE()) {
11691 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11692 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11694 createGPRPairNode(DAG
, N
->getOperand(2)), // Compare value
11695 createGPRPairNode(DAG
, N
->getOperand(3)), // Store value
11696 N
->getOperand(1), // Ptr
11697 N
->getOperand(0), // Chain in
11700 MachineMemOperand
*MemOp
= cast
<MemSDNode
>(N
)->getMemOperand();
11703 switch (MemOp
->getOrdering()) {
11704 case AtomicOrdering::Monotonic
:
11705 Opcode
= AArch64::CASPX
;
11707 case AtomicOrdering::Acquire
:
11708 Opcode
= AArch64::CASPAX
;
11710 case AtomicOrdering::Release
:
11711 Opcode
= AArch64::CASPLX
;
11713 case AtomicOrdering::AcquireRelease
:
11714 case AtomicOrdering::SequentiallyConsistent
:
11715 Opcode
= AArch64::CASPALX
;
11718 llvm_unreachable("Unexpected ordering!");
11721 MachineSDNode
*CmpSwap
= DAG
.getMachineNode(
11722 Opcode
, SDLoc(N
), DAG
.getVTList(MVT::Untyped
, MVT::Other
), Ops
);
11723 DAG
.setNodeMemRefs(CmpSwap
, {MemOp
});
11725 unsigned SubReg1
= AArch64::sube64
, SubReg2
= AArch64::subo64
;
11726 if (DAG
.getDataLayout().isBigEndian())
11727 std::swap(SubReg1
, SubReg2
);
11728 Results
.push_back(DAG
.getTargetExtractSubreg(SubReg1
, SDLoc(N
), MVT::i64
,
11729 SDValue(CmpSwap
, 0)));
11730 Results
.push_back(DAG
.getTargetExtractSubreg(SubReg2
, SDLoc(N
), MVT::i64
,
11731 SDValue(CmpSwap
, 0)));
11732 Results
.push_back(SDValue(CmpSwap
, 1)); // Chain out
11736 auto Desired
= splitInt128(N
->getOperand(2), DAG
);
11737 auto New
= splitInt128(N
->getOperand(3), DAG
);
11738 SDValue Ops
[] = {N
->getOperand(1), Desired
.first
, Desired
.second
,
11739 New
.first
, New
.second
, N
->getOperand(0)};
11740 SDNode
*CmpSwap
= DAG
.getMachineNode(
11741 AArch64::CMP_SWAP_128
, SDLoc(N
),
11742 DAG
.getVTList(MVT::i64
, MVT::i64
, MVT::i32
, MVT::Other
), Ops
);
11744 MachineMemOperand
*MemOp
= cast
<MemSDNode
>(N
)->getMemOperand();
11745 DAG
.setNodeMemRefs(cast
<MachineSDNode
>(CmpSwap
), {MemOp
});
11747 Results
.push_back(SDValue(CmpSwap
, 0));
11748 Results
.push_back(SDValue(CmpSwap
, 1));
11749 Results
.push_back(SDValue(CmpSwap
, 3));
11752 void AArch64TargetLowering::ReplaceNodeResults(
11753 SDNode
*N
, SmallVectorImpl
<SDValue
> &Results
, SelectionDAG
&DAG
) const {
11754 switch (N
->getOpcode()) {
11756 llvm_unreachable("Don't know how to custom expand this");
11758 ReplaceBITCASTResults(N
, Results
, DAG
);
11760 case ISD::VECREDUCE_ADD
:
11761 case ISD::VECREDUCE_SMAX
:
11762 case ISD::VECREDUCE_SMIN
:
11763 case ISD::VECREDUCE_UMAX
:
11764 case ISD::VECREDUCE_UMIN
:
11765 Results
.push_back(LowerVECREDUCE(SDValue(N
, 0), DAG
));
11768 case AArch64ISD::SADDV
:
11769 ReplaceReductionResults(N
, Results
, DAG
, ISD::ADD
, AArch64ISD::SADDV
);
11771 case AArch64ISD::UADDV
:
11772 ReplaceReductionResults(N
, Results
, DAG
, ISD::ADD
, AArch64ISD::UADDV
);
11774 case AArch64ISD::SMINV
:
11775 ReplaceReductionResults(N
, Results
, DAG
, ISD::SMIN
, AArch64ISD::SMINV
);
11777 case AArch64ISD::UMINV
:
11778 ReplaceReductionResults(N
, Results
, DAG
, ISD::UMIN
, AArch64ISD::UMINV
);
11780 case AArch64ISD::SMAXV
:
11781 ReplaceReductionResults(N
, Results
, DAG
, ISD::SMAX
, AArch64ISD::SMAXV
);
11783 case AArch64ISD::UMAXV
:
11784 ReplaceReductionResults(N
, Results
, DAG
, ISD::UMAX
, AArch64ISD::UMAXV
);
11786 case ISD::FP_TO_UINT
:
11787 case ISD::FP_TO_SINT
:
11788 assert(N
->getValueType(0) == MVT::i128
&& "unexpected illegal conversion");
11789 // Let normal code take care of it by not adding anything to Results.
11791 case ISD::ATOMIC_CMP_SWAP
:
11792 ReplaceCMP_SWAP_128Results(N
, Results
, DAG
, Subtarget
);
11797 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11798 if (Subtarget
->isTargetAndroid() || Subtarget
->isTargetFuchsia())
11799 return TargetLowering::useLoadStackGuardNode();
11803 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11804 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11805 // reciprocal if there are three or more FDIVs.
11809 TargetLoweringBase::LegalizeTypeAction
11810 AArch64TargetLowering::getPreferredVectorAction(MVT VT
) const {
11811 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11812 // v4i16, v2i32 instead of to promote.
11813 if (VT
== MVT::v1i8
|| VT
== MVT::v1i16
|| VT
== MVT::v1i32
||
11815 return TypeWidenVector
;
11817 return TargetLoweringBase::getPreferredVectorAction(VT
);
11820 // Loads and stores less than 128-bits are already atomic; ones above that
11821 // are doomed anyway, so defer to the default libcall and blame the OS when
11822 // things go wrong.
11823 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst
*SI
) const {
11824 unsigned Size
= SI
->getValueOperand()->getType()->getPrimitiveSizeInBits();
11825 return Size
== 128;
11828 // Loads and stores less than 128-bits are already atomic; ones above that
11829 // are doomed anyway, so defer to the default libcall and blame the OS when
11830 // things go wrong.
11831 TargetLowering::AtomicExpansionKind
11832 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst
*LI
) const {
11833 unsigned Size
= LI
->getType()->getPrimitiveSizeInBits();
11834 return Size
== 128 ? AtomicExpansionKind::LLSC
: AtomicExpansionKind::None
;
11837 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11838 TargetLowering::AtomicExpansionKind
11839 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst
*AI
) const {
11840 if (AI
->isFloatingPointOperation())
11841 return AtomicExpansionKind::CmpXChg
;
11843 unsigned Size
= AI
->getType()->getPrimitiveSizeInBits();
11844 if (Size
> 128) return AtomicExpansionKind::None
;
11845 // Nand not supported in LSE.
11846 if (AI
->getOperation() == AtomicRMWInst::Nand
) return AtomicExpansionKind::LLSC
;
11847 // Leave 128 bits to LLSC.
11848 return (Subtarget
->hasLSE() && Size
< 128) ? AtomicExpansionKind::None
: AtomicExpansionKind::LLSC
;
11851 TargetLowering::AtomicExpansionKind
11852 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11853 AtomicCmpXchgInst
*AI
) const {
11854 // If subtarget has LSE, leave cmpxchg intact for codegen.
11855 if (Subtarget
->hasLSE())
11856 return AtomicExpansionKind::None
;
11857 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11858 // implement cmpxchg without spilling. If the address being exchanged is also
11859 // on the stack and close enough to the spill slot, this can lead to a
11860 // situation where the monitor always gets cleared and the atomic operation
11861 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11862 if (getTargetMachine().getOptLevel() == 0)
11863 return AtomicExpansionKind::None
;
11864 return AtomicExpansionKind::LLSC
;
11867 Value
*AArch64TargetLowering::emitLoadLinked(IRBuilder
<> &Builder
, Value
*Addr
,
11868 AtomicOrdering Ord
) const {
11869 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11870 Type
*ValTy
= cast
<PointerType
>(Addr
->getType())->getElementType();
11871 bool IsAcquire
= isAcquireOrStronger(Ord
);
11873 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11874 // intrinsic must return {i64, i64} and we have to recombine them into a
11875 // single i128 here.
11876 if (ValTy
->getPrimitiveSizeInBits() == 128) {
11877 Intrinsic::ID Int
=
11878 IsAcquire
? Intrinsic::aarch64_ldaxp
: Intrinsic::aarch64_ldxp
;
11879 Function
*Ldxr
= Intrinsic::getDeclaration(M
, Int
);
11881 Addr
= Builder
.CreateBitCast(Addr
, Type::getInt8PtrTy(M
->getContext()));
11882 Value
*LoHi
= Builder
.CreateCall(Ldxr
, Addr
, "lohi");
11884 Value
*Lo
= Builder
.CreateExtractValue(LoHi
, 0, "lo");
11885 Value
*Hi
= Builder
.CreateExtractValue(LoHi
, 1, "hi");
11886 Lo
= Builder
.CreateZExt(Lo
, ValTy
, "lo64");
11887 Hi
= Builder
.CreateZExt(Hi
, ValTy
, "hi64");
11888 return Builder
.CreateOr(
11889 Lo
, Builder
.CreateShl(Hi
, ConstantInt::get(ValTy
, 64)), "val64");
11892 Type
*Tys
[] = { Addr
->getType() };
11893 Intrinsic::ID Int
=
11894 IsAcquire
? Intrinsic::aarch64_ldaxr
: Intrinsic::aarch64_ldxr
;
11895 Function
*Ldxr
= Intrinsic::getDeclaration(M
, Int
, Tys
);
11897 Type
*EltTy
= cast
<PointerType
>(Addr
->getType())->getElementType();
11899 const DataLayout
&DL
= M
->getDataLayout();
11900 IntegerType
*IntEltTy
= Builder
.getIntNTy(DL
.getTypeSizeInBits(EltTy
));
11901 Value
*Trunc
= Builder
.CreateTrunc(Builder
.CreateCall(Ldxr
, Addr
), IntEltTy
);
11903 return Builder
.CreateBitCast(Trunc
, EltTy
);
11906 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11907 IRBuilder
<> &Builder
) const {
11908 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11909 Builder
.CreateCall(Intrinsic::getDeclaration(M
, Intrinsic::aarch64_clrex
));
11912 Value
*AArch64TargetLowering::emitStoreConditional(IRBuilder
<> &Builder
,
11913 Value
*Val
, Value
*Addr
,
11914 AtomicOrdering Ord
) const {
11915 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11916 bool IsRelease
= isReleaseOrStronger(Ord
);
11918 // Since the intrinsics must have legal type, the i128 intrinsics take two
11919 // parameters: "i64, i64". We must marshal Val into the appropriate form
11920 // before the call.
11921 if (Val
->getType()->getPrimitiveSizeInBits() == 128) {
11922 Intrinsic::ID Int
=
11923 IsRelease
? Intrinsic::aarch64_stlxp
: Intrinsic::aarch64_stxp
;
11924 Function
*Stxr
= Intrinsic::getDeclaration(M
, Int
);
11925 Type
*Int64Ty
= Type::getInt64Ty(M
->getContext());
11927 Value
*Lo
= Builder
.CreateTrunc(Val
, Int64Ty
, "lo");
11928 Value
*Hi
= Builder
.CreateTrunc(Builder
.CreateLShr(Val
, 64), Int64Ty
, "hi");
11929 Addr
= Builder
.CreateBitCast(Addr
, Type::getInt8PtrTy(M
->getContext()));
11930 return Builder
.CreateCall(Stxr
, {Lo
, Hi
, Addr
});
11933 Intrinsic::ID Int
=
11934 IsRelease
? Intrinsic::aarch64_stlxr
: Intrinsic::aarch64_stxr
;
11935 Type
*Tys
[] = { Addr
->getType() };
11936 Function
*Stxr
= Intrinsic::getDeclaration(M
, Int
, Tys
);
11938 const DataLayout
&DL
= M
->getDataLayout();
11939 IntegerType
*IntValTy
= Builder
.getIntNTy(DL
.getTypeSizeInBits(Val
->getType()));
11940 Val
= Builder
.CreateBitCast(Val
, IntValTy
);
11942 return Builder
.CreateCall(Stxr
,
11943 {Builder
.CreateZExtOrBitCast(
11944 Val
, Stxr
->getFunctionType()->getParamType(0)),
11948 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11949 Type
*Ty
, CallingConv::ID CallConv
, bool isVarArg
) const {
11950 return Ty
->isArrayTy();
11953 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext
&,
11958 static Value
*UseTlsOffset(IRBuilder
<> &IRB
, unsigned Offset
) {
11959 Module
*M
= IRB
.GetInsertBlock()->getParent()->getParent();
11960 Function
*ThreadPointerFunc
=
11961 Intrinsic::getDeclaration(M
, Intrinsic::thread_pointer
);
11962 return IRB
.CreatePointerCast(
11963 IRB
.CreateConstGEP1_32(IRB
.getInt8Ty(), IRB
.CreateCall(ThreadPointerFunc
),
11965 IRB
.getInt8PtrTy()->getPointerTo(0));
11968 Value
*AArch64TargetLowering::getIRStackGuard(IRBuilder
<> &IRB
) const {
11969 // Android provides a fixed TLS slot for the stack cookie. See the definition
11970 // of TLS_SLOT_STACK_GUARD in
11971 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11972 if (Subtarget
->isTargetAndroid())
11973 return UseTlsOffset(IRB
, 0x28);
11975 // Fuchsia is similar.
11976 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
11977 if (Subtarget
->isTargetFuchsia())
11978 return UseTlsOffset(IRB
, -0x10);
11980 return TargetLowering::getIRStackGuard(IRB
);
11983 void AArch64TargetLowering::insertSSPDeclarations(Module
&M
) const {
11984 // MSVC CRT provides functionalities for stack protection.
11985 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment()) {
11986 // MSVC CRT has a global variable holding security cookie.
11987 M
.getOrInsertGlobal("__security_cookie",
11988 Type::getInt8PtrTy(M
.getContext()));
11990 // MSVC CRT has a function to validate security cookie.
11991 FunctionCallee SecurityCheckCookie
= M
.getOrInsertFunction(
11992 "__security_check_cookie", Type::getVoidTy(M
.getContext()),
11993 Type::getInt8PtrTy(M
.getContext()));
11994 if (Function
*F
= dyn_cast
<Function
>(SecurityCheckCookie
.getCallee())) {
11995 F
->setCallingConv(CallingConv::Win64
);
11996 F
->addAttribute(1, Attribute::AttrKind::InReg
);
12000 TargetLowering::insertSSPDeclarations(M
);
12003 Value
*AArch64TargetLowering::getSDagStackGuard(const Module
&M
) const {
12004 // MSVC CRT has a global variable holding security cookie.
12005 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment())
12006 return M
.getGlobalVariable("__security_cookie");
12007 return TargetLowering::getSDagStackGuard(M
);
12010 Function
*AArch64TargetLowering::getSSPStackGuardCheck(const Module
&M
) const {
12011 // MSVC CRT has a function to validate security cookie.
12012 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment())
12013 return M
.getFunction("__security_check_cookie");
12014 return TargetLowering::getSSPStackGuardCheck(M
);
12017 Value
*AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder
<> &IRB
) const {
12018 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12019 // definition of TLS_SLOT_SAFESTACK in
12020 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12021 if (Subtarget
->isTargetAndroid())
12022 return UseTlsOffset(IRB
, 0x48);
12024 // Fuchsia is similar.
12025 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
12026 if (Subtarget
->isTargetFuchsia())
12027 return UseTlsOffset(IRB
, -0x8);
12029 return TargetLowering::getSafeStackPointerLocation(IRB
);
12032 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12033 const Instruction
&AndI
) const {
12034 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12035 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12036 // may be beneficial to sink in other cases, but we would have to check that
12037 // the cmp would not get folded into the br to form a cbz for these to be
12039 ConstantInt
* Mask
= dyn_cast
<ConstantInt
>(AndI
.getOperand(1));
12042 return Mask
->getValue().isPowerOf2();
12045 bool AArch64TargetLowering::
12046 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12047 SDValue X
, ConstantSDNode
*XC
, ConstantSDNode
*CC
, SDValue Y
,
12048 unsigned OldShiftOpcode
, unsigned NewShiftOpcode
,
12049 SelectionDAG
&DAG
) const {
12050 // Does baseline recommend not to perform the fold by default?
12051 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12052 X
, XC
, CC
, Y
, OldShiftOpcode
, NewShiftOpcode
, DAG
))
12054 // Else, if this is a vector shift, prefer 'shl'.
12055 return X
.getValueType().isScalarInteger() || NewShiftOpcode
== ISD::SHL
;
12058 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock
*Entry
) const {
12059 // Update IsSplitCSR in AArch64unctionInfo.
12060 AArch64FunctionInfo
*AFI
= Entry
->getParent()->getInfo
<AArch64FunctionInfo
>();
12061 AFI
->setIsSplitCSR(true);
12064 void AArch64TargetLowering::insertCopiesSplitCSR(
12065 MachineBasicBlock
*Entry
,
12066 const SmallVectorImpl
<MachineBasicBlock
*> &Exits
) const {
12067 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
12068 const MCPhysReg
*IStart
= TRI
->getCalleeSavedRegsViaCopy(Entry
->getParent());
12072 const TargetInstrInfo
*TII
= Subtarget
->getInstrInfo();
12073 MachineRegisterInfo
*MRI
= &Entry
->getParent()->getRegInfo();
12074 MachineBasicBlock::iterator MBBI
= Entry
->begin();
12075 for (const MCPhysReg
*I
= IStart
; *I
; ++I
) {
12076 const TargetRegisterClass
*RC
= nullptr;
12077 if (AArch64::GPR64RegClass
.contains(*I
))
12078 RC
= &AArch64::GPR64RegClass
;
12079 else if (AArch64::FPR64RegClass
.contains(*I
))
12080 RC
= &AArch64::FPR64RegClass
;
12082 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12084 unsigned NewVR
= MRI
->createVirtualRegister(RC
);
12085 // Create copy from CSR to a virtual register.
12086 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12087 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12088 // nounwind. If we want to generalize this later, we may need to emit
12089 // CFI pseudo-instructions.
12090 assert(Entry
->getParent()->getFunction().hasFnAttribute(
12091 Attribute::NoUnwind
) &&
12092 "Function should be nounwind in insertCopiesSplitCSR!");
12093 Entry
->addLiveIn(*I
);
12094 BuildMI(*Entry
, MBBI
, DebugLoc(), TII
->get(TargetOpcode::COPY
), NewVR
)
12097 // Insert the copy-back instructions right before the terminator.
12098 for (auto *Exit
: Exits
)
12099 BuildMI(*Exit
, Exit
->getFirstTerminator(), DebugLoc(),
12100 TII
->get(TargetOpcode::COPY
), *I
)
12105 bool AArch64TargetLowering::isIntDivCheap(EVT VT
, AttributeList Attr
) const {
12106 // Integer division on AArch64 is expensive. However, when aggressively
12107 // optimizing for code size, we prefer to use a div instruction, as it is
12108 // usually smaller than the alternative sequence.
12109 // The exception to this is vector division. Since AArch64 doesn't have vector
12110 // integer division, leaving the division as-is is a loss even in terms of
12111 // size, because it will have to be scalarized, while the alternative code
12112 // sequence can be performed in vector form.
12114 Attr
.hasAttribute(AttributeList::FunctionIndex
, Attribute::MinSize
);
12115 return OptSize
&& !VT
.isVector();
12118 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT
) const {
12119 // We want inc-of-add for scalars and sub-of-not for vectors.
12120 return VT
.isScalarInteger();
12123 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT
) const {
12124 return Subtarget
->hasAggressiveFMA() && VT
.isFloatingPoint();
12128 AArch64TargetLowering::getVaListSizeInBits(const DataLayout
&DL
) const {
12129 if (Subtarget
->isTargetDarwin() || Subtarget
->isTargetWindows())
12130 return getPointerTy(DL
).getSizeInBits();
12132 return 3 * getPointerTy(DL
).getSizeInBits() + 2 * 32;
12135 void AArch64TargetLowering::finalizeLowering(MachineFunction
&MF
) const {
12136 MF
.getFrameInfo().computeMaxCallFrameSize(MF
);
12137 TargetLoweringBase::finalizeLowering(MF
);
12140 // Unlike X86, we let frame lowering assign offsets to all catch objects.
12141 bool AArch64TargetLowering::needsFixedCatchObjects() const {