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 "AArch64ISelLowering.h"
14 #include "AArch64CallingConvention.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64PerfectShuffle.h"
17 #include "AArch64RegisterInfo.h"
18 #include "AArch64Subtarget.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "Utils/AArch64BaseInfo.h"
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/CodeGen/CallingConvLower.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/RuntimeLibcalls.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/SelectionDAGNodes.h"
43 #include "llvm/CodeGen/TargetCallingConv.h"
44 #include "llvm/CodeGen/TargetInstrInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/IntrinsicInst.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/OperandTraits.h"
61 #include "llvm/IR/PatternMatch.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/Use.h"
64 #include "llvm/IR/Value.h"
65 #include "llvm/MC/MCRegisterInfo.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MachineValueType.h"
74 #include "llvm/Support/MathExtras.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include "llvm/Target/TargetMachine.h"
77 #include "llvm/Target/TargetOptions.h"
91 using namespace llvm::PatternMatch
;
93 #define DEBUG_TYPE "aarch64-lower"
95 STATISTIC(NumTailCalls
, "Number of tail calls");
96 STATISTIC(NumShiftInserts
, "Number of vector shift inserts");
97 STATISTIC(NumOptimizedImms
, "Number of times immediates were optimized");
100 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden
,
101 cl::desc("Allow AArch64 SLI/SRI formation"),
104 // FIXME: The necessary dtprel relocations don't seem to be supported
105 // well in the GNU bfd and gold linkers at the moment. Therefore, by
106 // default, for now, fall back to GeneralDynamic code generation.
107 cl::opt
<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
108 "aarch64-elf-ldtls-generation", cl::Hidden
,
109 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
113 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden
,
114 cl::desc("Enable AArch64 logical imm instruction "
118 /// Value type used for condition codes.
119 static const MVT MVT_CC
= MVT::i32
;
121 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine
&TM
,
122 const AArch64Subtarget
&STI
)
123 : TargetLowering(TM
), Subtarget(&STI
) {
124 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
125 // we have to make something up. Arbitrarily, choose ZeroOrOne.
126 setBooleanContents(ZeroOrOneBooleanContent
);
127 // When comparing vectors the result sets the different elements in the
128 // vector to all-one or all-zero.
129 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent
);
131 // Set up the register classes.
132 addRegisterClass(MVT::i32
, &AArch64::GPR32allRegClass
);
133 addRegisterClass(MVT::i64
, &AArch64::GPR64allRegClass
);
135 if (Subtarget
->hasFPARMv8()) {
136 addRegisterClass(MVT::f16
, &AArch64::FPR16RegClass
);
137 addRegisterClass(MVT::f32
, &AArch64::FPR32RegClass
);
138 addRegisterClass(MVT::f64
, &AArch64::FPR64RegClass
);
139 addRegisterClass(MVT::f128
, &AArch64::FPR128RegClass
);
142 if (Subtarget
->hasNEON()) {
143 addRegisterClass(MVT::v16i8
, &AArch64::FPR8RegClass
);
144 addRegisterClass(MVT::v8i16
, &AArch64::FPR16RegClass
);
145 // Someone set us up the NEON.
146 addDRTypeForNEON(MVT::v2f32
);
147 addDRTypeForNEON(MVT::v8i8
);
148 addDRTypeForNEON(MVT::v4i16
);
149 addDRTypeForNEON(MVT::v2i32
);
150 addDRTypeForNEON(MVT::v1i64
);
151 addDRTypeForNEON(MVT::v1f64
);
152 addDRTypeForNEON(MVT::v4f16
);
154 addQRTypeForNEON(MVT::v4f32
);
155 addQRTypeForNEON(MVT::v2f64
);
156 addQRTypeForNEON(MVT::v16i8
);
157 addQRTypeForNEON(MVT::v8i16
);
158 addQRTypeForNEON(MVT::v4i32
);
159 addQRTypeForNEON(MVT::v2i64
);
160 addQRTypeForNEON(MVT::v8f16
);
163 // Compute derived properties from the register classes
164 computeRegisterProperties(Subtarget
->getRegisterInfo());
166 // Provide all sorts of operation actions
167 setOperationAction(ISD::GlobalAddress
, MVT::i64
, Custom
);
168 setOperationAction(ISD::GlobalTLSAddress
, MVT::i64
, Custom
);
169 setOperationAction(ISD::SETCC
, MVT::i32
, Custom
);
170 setOperationAction(ISD::SETCC
, MVT::i64
, Custom
);
171 setOperationAction(ISD::SETCC
, MVT::f16
, Custom
);
172 setOperationAction(ISD::SETCC
, MVT::f32
, Custom
);
173 setOperationAction(ISD::SETCC
, MVT::f64
, Custom
);
174 setOperationAction(ISD::BITREVERSE
, MVT::i32
, Legal
);
175 setOperationAction(ISD::BITREVERSE
, MVT::i64
, Legal
);
176 setOperationAction(ISD::BRCOND
, MVT::Other
, Expand
);
177 setOperationAction(ISD::BR_CC
, MVT::i32
, Custom
);
178 setOperationAction(ISD::BR_CC
, MVT::i64
, Custom
);
179 setOperationAction(ISD::BR_CC
, MVT::f16
, Custom
);
180 setOperationAction(ISD::BR_CC
, MVT::f32
, Custom
);
181 setOperationAction(ISD::BR_CC
, MVT::f64
, Custom
);
182 setOperationAction(ISD::SELECT
, MVT::i32
, Custom
);
183 setOperationAction(ISD::SELECT
, MVT::i64
, Custom
);
184 setOperationAction(ISD::SELECT
, MVT::f16
, Custom
);
185 setOperationAction(ISD::SELECT
, MVT::f32
, Custom
);
186 setOperationAction(ISD::SELECT
, MVT::f64
, Custom
);
187 setOperationAction(ISD::SELECT_CC
, MVT::i32
, Custom
);
188 setOperationAction(ISD::SELECT_CC
, MVT::i64
, Custom
);
189 setOperationAction(ISD::SELECT_CC
, MVT::f16
, Custom
);
190 setOperationAction(ISD::SELECT_CC
, MVT::f32
, Custom
);
191 setOperationAction(ISD::SELECT_CC
, MVT::f64
, Custom
);
192 setOperationAction(ISD::BR_JT
, MVT::Other
, Custom
);
193 setOperationAction(ISD::JumpTable
, MVT::i64
, Custom
);
195 setOperationAction(ISD::SHL_PARTS
, MVT::i64
, Custom
);
196 setOperationAction(ISD::SRA_PARTS
, MVT::i64
, Custom
);
197 setOperationAction(ISD::SRL_PARTS
, MVT::i64
, Custom
);
199 setOperationAction(ISD::FREM
, MVT::f32
, Expand
);
200 setOperationAction(ISD::FREM
, MVT::f64
, Expand
);
201 setOperationAction(ISD::FREM
, MVT::f80
, Expand
);
203 setOperationAction(ISD::BUILD_PAIR
, MVT::i64
, Expand
);
205 // Custom lowering hooks are needed for XOR
206 // to fold it into CSINC/CSINV.
207 setOperationAction(ISD::XOR
, MVT::i32
, Custom
);
208 setOperationAction(ISD::XOR
, MVT::i64
, Custom
);
210 // Virtually no operation on f128 is legal, but LLVM can't expand them when
211 // there's a valid register class, so we need custom operations in most cases.
212 setOperationAction(ISD::FABS
, MVT::f128
, Expand
);
213 setOperationAction(ISD::FADD
, MVT::f128
, Custom
);
214 setOperationAction(ISD::FCOPYSIGN
, MVT::f128
, Expand
);
215 setOperationAction(ISD::FCOS
, MVT::f128
, Expand
);
216 setOperationAction(ISD::FDIV
, MVT::f128
, Custom
);
217 setOperationAction(ISD::FMA
, MVT::f128
, Expand
);
218 setOperationAction(ISD::FMUL
, MVT::f128
, Custom
);
219 setOperationAction(ISD::FNEG
, MVT::f128
, Expand
);
220 setOperationAction(ISD::FPOW
, MVT::f128
, Expand
);
221 setOperationAction(ISD::FREM
, MVT::f128
, Expand
);
222 setOperationAction(ISD::FRINT
, MVT::f128
, Expand
);
223 setOperationAction(ISD::FSIN
, MVT::f128
, Expand
);
224 setOperationAction(ISD::FSINCOS
, MVT::f128
, Expand
);
225 setOperationAction(ISD::FSQRT
, MVT::f128
, Expand
);
226 setOperationAction(ISD::FSUB
, MVT::f128
, Custom
);
227 setOperationAction(ISD::FTRUNC
, MVT::f128
, Expand
);
228 setOperationAction(ISD::SETCC
, MVT::f128
, Custom
);
229 setOperationAction(ISD::BR_CC
, MVT::f128
, Custom
);
230 setOperationAction(ISD::SELECT
, MVT::f128
, Custom
);
231 setOperationAction(ISD::SELECT_CC
, MVT::f128
, Custom
);
232 setOperationAction(ISD::FP_EXTEND
, MVT::f128
, Custom
);
234 // Lowering for many of the conversions is actually specified by the non-f128
235 // type. The LowerXXX function will be trivial when f128 isn't involved.
236 setOperationAction(ISD::FP_TO_SINT
, MVT::i32
, Custom
);
237 setOperationAction(ISD::FP_TO_SINT
, MVT::i64
, Custom
);
238 setOperationAction(ISD::FP_TO_SINT
, MVT::i128
, Custom
);
239 setOperationAction(ISD::FP_TO_UINT
, MVT::i32
, Custom
);
240 setOperationAction(ISD::FP_TO_UINT
, MVT::i64
, Custom
);
241 setOperationAction(ISD::FP_TO_UINT
, MVT::i128
, Custom
);
242 setOperationAction(ISD::SINT_TO_FP
, MVT::i32
, Custom
);
243 setOperationAction(ISD::SINT_TO_FP
, MVT::i64
, Custom
);
244 setOperationAction(ISD::SINT_TO_FP
, MVT::i128
, Custom
);
245 setOperationAction(ISD::UINT_TO_FP
, MVT::i32
, Custom
);
246 setOperationAction(ISD::UINT_TO_FP
, MVT::i64
, Custom
);
247 setOperationAction(ISD::UINT_TO_FP
, MVT::i128
, Custom
);
248 setOperationAction(ISD::FP_ROUND
, MVT::f32
, Custom
);
249 setOperationAction(ISD::FP_ROUND
, MVT::f64
, Custom
);
251 // Variable arguments.
252 setOperationAction(ISD::VASTART
, MVT::Other
, Custom
);
253 setOperationAction(ISD::VAARG
, MVT::Other
, Custom
);
254 setOperationAction(ISD::VACOPY
, MVT::Other
, Custom
);
255 setOperationAction(ISD::VAEND
, MVT::Other
, Expand
);
257 // Variable-sized objects.
258 setOperationAction(ISD::STACKSAVE
, MVT::Other
, Expand
);
259 setOperationAction(ISD::STACKRESTORE
, MVT::Other
, Expand
);
261 if (Subtarget
->isTargetWindows())
262 setOperationAction(ISD::DYNAMIC_STACKALLOC
, MVT::i64
, Custom
);
264 setOperationAction(ISD::DYNAMIC_STACKALLOC
, MVT::i64
, Expand
);
266 // Constant pool entries
267 setOperationAction(ISD::ConstantPool
, MVT::i64
, Custom
);
270 setOperationAction(ISD::BlockAddress
, MVT::i64
, Custom
);
272 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
273 setOperationAction(ISD::ADDC
, MVT::i32
, Custom
);
274 setOperationAction(ISD::ADDE
, MVT::i32
, Custom
);
275 setOperationAction(ISD::SUBC
, MVT::i32
, Custom
);
276 setOperationAction(ISD::SUBE
, MVT::i32
, Custom
);
277 setOperationAction(ISD::ADDC
, MVT::i64
, Custom
);
278 setOperationAction(ISD::ADDE
, MVT::i64
, Custom
);
279 setOperationAction(ISD::SUBC
, MVT::i64
, Custom
);
280 setOperationAction(ISD::SUBE
, MVT::i64
, Custom
);
282 // AArch64 lacks both left-rotate and popcount instructions.
283 setOperationAction(ISD::ROTL
, MVT::i32
, Expand
);
284 setOperationAction(ISD::ROTL
, MVT::i64
, Expand
);
285 for (MVT VT
: MVT::vector_valuetypes()) {
286 setOperationAction(ISD::ROTL
, VT
, Expand
);
287 setOperationAction(ISD::ROTR
, VT
, Expand
);
290 // AArch64 doesn't have {U|S}MUL_LOHI.
291 setOperationAction(ISD::UMUL_LOHI
, MVT::i64
, Expand
);
292 setOperationAction(ISD::SMUL_LOHI
, MVT::i64
, Expand
);
294 setOperationAction(ISD::CTPOP
, MVT::i32
, Custom
);
295 setOperationAction(ISD::CTPOP
, MVT::i64
, Custom
);
297 setOperationAction(ISD::SDIVREM
, MVT::i32
, Expand
);
298 setOperationAction(ISD::SDIVREM
, MVT::i64
, Expand
);
299 for (MVT VT
: MVT::vector_valuetypes()) {
300 setOperationAction(ISD::SDIVREM
, VT
, Expand
);
301 setOperationAction(ISD::UDIVREM
, VT
, Expand
);
303 setOperationAction(ISD::SREM
, MVT::i32
, Expand
);
304 setOperationAction(ISD::SREM
, MVT::i64
, Expand
);
305 setOperationAction(ISD::UDIVREM
, MVT::i32
, Expand
);
306 setOperationAction(ISD::UDIVREM
, MVT::i64
, Expand
);
307 setOperationAction(ISD::UREM
, MVT::i32
, Expand
);
308 setOperationAction(ISD::UREM
, MVT::i64
, Expand
);
310 // Custom lower Add/Sub/Mul with overflow.
311 setOperationAction(ISD::SADDO
, MVT::i32
, Custom
);
312 setOperationAction(ISD::SADDO
, MVT::i64
, Custom
);
313 setOperationAction(ISD::UADDO
, MVT::i32
, Custom
);
314 setOperationAction(ISD::UADDO
, MVT::i64
, Custom
);
315 setOperationAction(ISD::SSUBO
, MVT::i32
, Custom
);
316 setOperationAction(ISD::SSUBO
, MVT::i64
, Custom
);
317 setOperationAction(ISD::USUBO
, MVT::i32
, Custom
);
318 setOperationAction(ISD::USUBO
, MVT::i64
, Custom
);
319 setOperationAction(ISD::SMULO
, MVT::i32
, Custom
);
320 setOperationAction(ISD::SMULO
, MVT::i64
, Custom
);
321 setOperationAction(ISD::UMULO
, MVT::i32
, Custom
);
322 setOperationAction(ISD::UMULO
, MVT::i64
, Custom
);
324 setOperationAction(ISD::FSIN
, MVT::f32
, Expand
);
325 setOperationAction(ISD::FSIN
, MVT::f64
, Expand
);
326 setOperationAction(ISD::FCOS
, MVT::f32
, Expand
);
327 setOperationAction(ISD::FCOS
, MVT::f64
, Expand
);
328 setOperationAction(ISD::FPOW
, MVT::f32
, Expand
);
329 setOperationAction(ISD::FPOW
, MVT::f64
, Expand
);
330 setOperationAction(ISD::FCOPYSIGN
, MVT::f64
, Custom
);
331 setOperationAction(ISD::FCOPYSIGN
, MVT::f32
, Custom
);
332 if (Subtarget
->hasFullFP16())
333 setOperationAction(ISD::FCOPYSIGN
, MVT::f16
, Custom
);
335 setOperationAction(ISD::FCOPYSIGN
, MVT::f16
, Promote
);
337 setOperationAction(ISD::FREM
, MVT::f16
, Promote
);
338 setOperationAction(ISD::FREM
, MVT::v4f16
, Expand
);
339 setOperationAction(ISD::FREM
, MVT::v8f16
, Expand
);
340 setOperationAction(ISD::FPOW
, MVT::f16
, Promote
);
341 setOperationAction(ISD::FPOW
, MVT::v4f16
, Expand
);
342 setOperationAction(ISD::FPOW
, MVT::v8f16
, Expand
);
343 setOperationAction(ISD::FPOWI
, MVT::f16
, Promote
);
344 setOperationAction(ISD::FPOWI
, MVT::v4f16
, Expand
);
345 setOperationAction(ISD::FPOWI
, MVT::v8f16
, Expand
);
346 setOperationAction(ISD::FCOS
, MVT::f16
, Promote
);
347 setOperationAction(ISD::FCOS
, MVT::v4f16
, Expand
);
348 setOperationAction(ISD::FCOS
, MVT::v8f16
, Expand
);
349 setOperationAction(ISD::FSIN
, MVT::f16
, Promote
);
350 setOperationAction(ISD::FSIN
, MVT::v4f16
, Expand
);
351 setOperationAction(ISD::FSIN
, MVT::v8f16
, Expand
);
352 setOperationAction(ISD::FSINCOS
, MVT::f16
, Promote
);
353 setOperationAction(ISD::FSINCOS
, MVT::v4f16
, Expand
);
354 setOperationAction(ISD::FSINCOS
, MVT::v8f16
, Expand
);
355 setOperationAction(ISD::FEXP
, MVT::f16
, Promote
);
356 setOperationAction(ISD::FEXP
, MVT::v4f16
, Expand
);
357 setOperationAction(ISD::FEXP
, MVT::v8f16
, Expand
);
358 setOperationAction(ISD::FEXP2
, MVT::f16
, Promote
);
359 setOperationAction(ISD::FEXP2
, MVT::v4f16
, Expand
);
360 setOperationAction(ISD::FEXP2
, MVT::v8f16
, Expand
);
361 setOperationAction(ISD::FLOG
, MVT::f16
, Promote
);
362 setOperationAction(ISD::FLOG
, MVT::v4f16
, Expand
);
363 setOperationAction(ISD::FLOG
, MVT::v8f16
, Expand
);
364 setOperationAction(ISD::FLOG2
, MVT::f16
, Promote
);
365 setOperationAction(ISD::FLOG2
, MVT::v4f16
, Expand
);
366 setOperationAction(ISD::FLOG2
, MVT::v8f16
, Expand
);
367 setOperationAction(ISD::FLOG10
, MVT::f16
, Promote
);
368 setOperationAction(ISD::FLOG10
, MVT::v4f16
, Expand
);
369 setOperationAction(ISD::FLOG10
, MVT::v8f16
, Expand
);
371 if (!Subtarget
->hasFullFP16()) {
372 setOperationAction(ISD::SELECT
, MVT::f16
, Promote
);
373 setOperationAction(ISD::SELECT_CC
, MVT::f16
, Promote
);
374 setOperationAction(ISD::SETCC
, MVT::f16
, Promote
);
375 setOperationAction(ISD::BR_CC
, MVT::f16
, Promote
);
376 setOperationAction(ISD::FADD
, MVT::f16
, Promote
);
377 setOperationAction(ISD::FSUB
, MVT::f16
, Promote
);
378 setOperationAction(ISD::FMUL
, MVT::f16
, Promote
);
379 setOperationAction(ISD::FDIV
, MVT::f16
, Promote
);
380 setOperationAction(ISD::FMA
, MVT::f16
, Promote
);
381 setOperationAction(ISD::FNEG
, MVT::f16
, Promote
);
382 setOperationAction(ISD::FABS
, MVT::f16
, Promote
);
383 setOperationAction(ISD::FCEIL
, MVT::f16
, Promote
);
384 setOperationAction(ISD::FSQRT
, MVT::f16
, Promote
);
385 setOperationAction(ISD::FFLOOR
, MVT::f16
, Promote
);
386 setOperationAction(ISD::FNEARBYINT
, MVT::f16
, Promote
);
387 setOperationAction(ISD::FRINT
, MVT::f16
, Promote
);
388 setOperationAction(ISD::FROUND
, MVT::f16
, Promote
);
389 setOperationAction(ISD::FTRUNC
, MVT::f16
, Promote
);
390 setOperationAction(ISD::FMINNUM
, MVT::f16
, Promote
);
391 setOperationAction(ISD::FMAXNUM
, MVT::f16
, Promote
);
392 setOperationAction(ISD::FMINIMUM
, MVT::f16
, Promote
);
393 setOperationAction(ISD::FMAXIMUM
, MVT::f16
, Promote
);
395 // promote v4f16 to v4f32 when that is known to be safe.
396 setOperationAction(ISD::FADD
, MVT::v4f16
, Promote
);
397 setOperationAction(ISD::FSUB
, MVT::v4f16
, Promote
);
398 setOperationAction(ISD::FMUL
, MVT::v4f16
, Promote
);
399 setOperationAction(ISD::FDIV
, MVT::v4f16
, Promote
);
400 setOperationAction(ISD::FP_EXTEND
, MVT::v4f16
, Promote
);
401 setOperationAction(ISD::FP_ROUND
, MVT::v4f16
, Promote
);
402 AddPromotedToType(ISD::FADD
, MVT::v4f16
, MVT::v4f32
);
403 AddPromotedToType(ISD::FSUB
, MVT::v4f16
, MVT::v4f32
);
404 AddPromotedToType(ISD::FMUL
, MVT::v4f16
, MVT::v4f32
);
405 AddPromotedToType(ISD::FDIV
, MVT::v4f16
, MVT::v4f32
);
406 AddPromotedToType(ISD::FP_EXTEND
, MVT::v4f16
, MVT::v4f32
);
407 AddPromotedToType(ISD::FP_ROUND
, MVT::v4f16
, MVT::v4f32
);
409 setOperationAction(ISD::FABS
, MVT::v4f16
, Expand
);
410 setOperationAction(ISD::FNEG
, MVT::v4f16
, Expand
);
411 setOperationAction(ISD::FROUND
, MVT::v4f16
, Expand
);
412 setOperationAction(ISD::FMA
, MVT::v4f16
, Expand
);
413 setOperationAction(ISD::SETCC
, MVT::v4f16
, Expand
);
414 setOperationAction(ISD::BR_CC
, MVT::v4f16
, Expand
);
415 setOperationAction(ISD::SELECT
, MVT::v4f16
, Expand
);
416 setOperationAction(ISD::SELECT_CC
, MVT::v4f16
, Expand
);
417 setOperationAction(ISD::FTRUNC
, MVT::v4f16
, Expand
);
418 setOperationAction(ISD::FCOPYSIGN
, MVT::v4f16
, Expand
);
419 setOperationAction(ISD::FFLOOR
, MVT::v4f16
, Expand
);
420 setOperationAction(ISD::FCEIL
, MVT::v4f16
, Expand
);
421 setOperationAction(ISD::FRINT
, MVT::v4f16
, Expand
);
422 setOperationAction(ISD::FNEARBYINT
, MVT::v4f16
, Expand
);
423 setOperationAction(ISD::FSQRT
, MVT::v4f16
, Expand
);
425 setOperationAction(ISD::FABS
, MVT::v8f16
, Expand
);
426 setOperationAction(ISD::FADD
, MVT::v8f16
, Expand
);
427 setOperationAction(ISD::FCEIL
, MVT::v8f16
, Expand
);
428 setOperationAction(ISD::FCOPYSIGN
, MVT::v8f16
, Expand
);
429 setOperationAction(ISD::FDIV
, MVT::v8f16
, Expand
);
430 setOperationAction(ISD::FFLOOR
, MVT::v8f16
, Expand
);
431 setOperationAction(ISD::FMA
, MVT::v8f16
, Expand
);
432 setOperationAction(ISD::FMUL
, MVT::v8f16
, Expand
);
433 setOperationAction(ISD::FNEARBYINT
, MVT::v8f16
, Expand
);
434 setOperationAction(ISD::FNEG
, MVT::v8f16
, Expand
);
435 setOperationAction(ISD::FROUND
, MVT::v8f16
, Expand
);
436 setOperationAction(ISD::FRINT
, MVT::v8f16
, Expand
);
437 setOperationAction(ISD::FSQRT
, MVT::v8f16
, Expand
);
438 setOperationAction(ISD::FSUB
, MVT::v8f16
, Expand
);
439 setOperationAction(ISD::FTRUNC
, MVT::v8f16
, Expand
);
440 setOperationAction(ISD::SETCC
, MVT::v8f16
, Expand
);
441 setOperationAction(ISD::BR_CC
, MVT::v8f16
, Expand
);
442 setOperationAction(ISD::SELECT
, MVT::v8f16
, Expand
);
443 setOperationAction(ISD::SELECT_CC
, MVT::v8f16
, Expand
);
444 setOperationAction(ISD::FP_EXTEND
, MVT::v8f16
, Expand
);
447 // AArch64 has implementations of a lot of rounding-like FP operations.
448 for (MVT Ty
: {MVT::f32
, MVT::f64
}) {
449 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
450 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
451 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
452 setOperationAction(ISD::FRINT
, Ty
, Legal
);
453 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
454 setOperationAction(ISD::FROUND
, Ty
, Legal
);
455 setOperationAction(ISD::FMINNUM
, Ty
, Legal
);
456 setOperationAction(ISD::FMAXNUM
, Ty
, Legal
);
457 setOperationAction(ISD::FMINIMUM
, Ty
, Legal
);
458 setOperationAction(ISD::FMAXIMUM
, Ty
, Legal
);
461 if (Subtarget
->hasFullFP16()) {
462 setOperationAction(ISD::FNEARBYINT
, MVT::f16
, Legal
);
463 setOperationAction(ISD::FFLOOR
, MVT::f16
, Legal
);
464 setOperationAction(ISD::FCEIL
, MVT::f16
, Legal
);
465 setOperationAction(ISD::FRINT
, MVT::f16
, Legal
);
466 setOperationAction(ISD::FTRUNC
, MVT::f16
, Legal
);
467 setOperationAction(ISD::FROUND
, MVT::f16
, Legal
);
468 setOperationAction(ISD::FMINNUM
, MVT::f16
, Legal
);
469 setOperationAction(ISD::FMAXNUM
, MVT::f16
, Legal
);
470 setOperationAction(ISD::FMINIMUM
, MVT::f16
, Legal
);
471 setOperationAction(ISD::FMAXIMUM
, MVT::f16
, Legal
);
474 setOperationAction(ISD::PREFETCH
, MVT::Other
, Custom
);
476 setOperationAction(ISD::FLT_ROUNDS_
, MVT::i32
, Custom
);
478 setOperationAction(ISD::ATOMIC_CMP_SWAP
, MVT::i128
, Custom
);
479 setOperationAction(ISD::ATOMIC_LOAD_SUB
, MVT::i32
, Custom
);
480 setOperationAction(ISD::ATOMIC_LOAD_SUB
, MVT::i64
, Custom
);
481 setOperationAction(ISD::ATOMIC_LOAD_AND
, MVT::i32
, Custom
);
482 setOperationAction(ISD::ATOMIC_LOAD_AND
, MVT::i64
, Custom
);
484 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
485 // This requires the Performance Monitors extension.
486 if (Subtarget
->hasPerfMon())
487 setOperationAction(ISD::READCYCLECOUNTER
, MVT::i64
, Legal
);
489 if (getLibcallName(RTLIB::SINCOS_STRET_F32
) != nullptr &&
490 getLibcallName(RTLIB::SINCOS_STRET_F64
) != nullptr) {
491 // Issue __sincos_stret if available.
492 setOperationAction(ISD::FSINCOS
, MVT::f64
, Custom
);
493 setOperationAction(ISD::FSINCOS
, MVT::f32
, Custom
);
495 setOperationAction(ISD::FSINCOS
, MVT::f64
, Expand
);
496 setOperationAction(ISD::FSINCOS
, MVT::f32
, Expand
);
499 // Make floating-point constants legal for the large code model, so they don't
500 // become loads from the constant pool.
501 if (Subtarget
->isTargetMachO() && TM
.getCodeModel() == CodeModel::Large
) {
502 setOperationAction(ISD::ConstantFP
, MVT::f32
, Legal
);
503 setOperationAction(ISD::ConstantFP
, MVT::f64
, Legal
);
506 // AArch64 does not have floating-point extending loads, i1 sign-extending
507 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
508 for (MVT VT
: MVT::fp_valuetypes()) {
509 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f16
, Expand
);
510 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f32
, Expand
);
511 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f64
, Expand
);
512 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f80
, Expand
);
514 for (MVT VT
: MVT::integer_valuetypes())
515 setLoadExtAction(ISD::SEXTLOAD
, VT
, MVT::i1
, Expand
);
517 setTruncStoreAction(MVT::f32
, MVT::f16
, Expand
);
518 setTruncStoreAction(MVT::f64
, MVT::f32
, Expand
);
519 setTruncStoreAction(MVT::f64
, MVT::f16
, Expand
);
520 setTruncStoreAction(MVT::f128
, MVT::f80
, Expand
);
521 setTruncStoreAction(MVT::f128
, MVT::f64
, Expand
);
522 setTruncStoreAction(MVT::f128
, MVT::f32
, Expand
);
523 setTruncStoreAction(MVT::f128
, MVT::f16
, Expand
);
525 setOperationAction(ISD::BITCAST
, MVT::i16
, Custom
);
526 setOperationAction(ISD::BITCAST
, MVT::f16
, Custom
);
528 // Indexed loads and stores are supported.
529 for (unsigned im
= (unsigned)ISD::PRE_INC
;
530 im
!= (unsigned)ISD::LAST_INDEXED_MODE
; ++im
) {
531 setIndexedLoadAction(im
, MVT::i8
, Legal
);
532 setIndexedLoadAction(im
, MVT::i16
, Legal
);
533 setIndexedLoadAction(im
, MVT::i32
, Legal
);
534 setIndexedLoadAction(im
, MVT::i64
, Legal
);
535 setIndexedLoadAction(im
, MVT::f64
, Legal
);
536 setIndexedLoadAction(im
, MVT::f32
, Legal
);
537 setIndexedLoadAction(im
, MVT::f16
, Legal
);
538 setIndexedStoreAction(im
, MVT::i8
, Legal
);
539 setIndexedStoreAction(im
, MVT::i16
, Legal
);
540 setIndexedStoreAction(im
, MVT::i32
, Legal
);
541 setIndexedStoreAction(im
, MVT::i64
, Legal
);
542 setIndexedStoreAction(im
, MVT::f64
, Legal
);
543 setIndexedStoreAction(im
, MVT::f32
, Legal
);
544 setIndexedStoreAction(im
, MVT::f16
, Legal
);
548 setOperationAction(ISD::TRAP
, MVT::Other
, Legal
);
550 // We combine OR nodes for bitfield operations.
551 setTargetDAGCombine(ISD::OR
);
553 // Vector add and sub nodes may conceal a high-half opportunity.
554 // Also, try to fold ADD into CSINC/CSINV..
555 setTargetDAGCombine(ISD::ADD
);
556 setTargetDAGCombine(ISD::SUB
);
557 setTargetDAGCombine(ISD::SRL
);
558 setTargetDAGCombine(ISD::XOR
);
559 setTargetDAGCombine(ISD::SINT_TO_FP
);
560 setTargetDAGCombine(ISD::UINT_TO_FP
);
562 setTargetDAGCombine(ISD::FP_TO_SINT
);
563 setTargetDAGCombine(ISD::FP_TO_UINT
);
564 setTargetDAGCombine(ISD::FDIV
);
566 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN
);
568 setTargetDAGCombine(ISD::ANY_EXTEND
);
569 setTargetDAGCombine(ISD::ZERO_EXTEND
);
570 setTargetDAGCombine(ISD::SIGN_EXTEND
);
571 setTargetDAGCombine(ISD::BITCAST
);
572 setTargetDAGCombine(ISD::CONCAT_VECTORS
);
573 setTargetDAGCombine(ISD::STORE
);
574 if (Subtarget
->supportsAddressTopByteIgnored())
575 setTargetDAGCombine(ISD::LOAD
);
577 setTargetDAGCombine(ISD::MUL
);
579 setTargetDAGCombine(ISD::SELECT
);
580 setTargetDAGCombine(ISD::VSELECT
);
582 setTargetDAGCombine(ISD::INTRINSIC_VOID
);
583 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN
);
584 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT
);
586 setTargetDAGCombine(ISD::GlobalAddress
);
588 // In case of strict alignment, avoid an excessive number of byte wide stores.
589 MaxStoresPerMemsetOptSize
= 8;
590 MaxStoresPerMemset
= Subtarget
->requiresStrictAlign()
591 ? MaxStoresPerMemsetOptSize
: 32;
593 MaxGluedStoresPerMemcpy
= 4;
594 MaxStoresPerMemcpyOptSize
= 4;
595 MaxStoresPerMemcpy
= Subtarget
->requiresStrictAlign()
596 ? MaxStoresPerMemcpyOptSize
: 16;
598 MaxStoresPerMemmoveOptSize
= MaxStoresPerMemmove
= 4;
600 setStackPointerRegisterToSaveRestore(AArch64::SP
);
602 setSchedulingPreference(Sched::Hybrid
);
604 EnableExtLdPromotion
= true;
606 // Set required alignment.
607 setMinFunctionAlignment(2);
608 // Set preferred alignments.
609 setPrefFunctionAlignment(STI
.getPrefFunctionAlignment());
610 setPrefLoopAlignment(STI
.getPrefLoopAlignment());
612 // Only change the limit for entries in a jump table if specified by
613 // the subtarget, but not at the command line.
614 unsigned MaxJT
= STI
.getMaximumJumpTableSize();
615 if (MaxJT
&& getMaximumJumpTableSize() == 0)
616 setMaximumJumpTableSize(MaxJT
);
618 setHasExtractBitsInsn(true);
620 setOperationAction(ISD::INTRINSIC_WO_CHAIN
, MVT::Other
, Custom
);
622 if (Subtarget
->hasNEON()) {
623 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
624 // silliness like this:
625 setOperationAction(ISD::FABS
, MVT::v1f64
, Expand
);
626 setOperationAction(ISD::FADD
, MVT::v1f64
, Expand
);
627 setOperationAction(ISD::FCEIL
, MVT::v1f64
, Expand
);
628 setOperationAction(ISD::FCOPYSIGN
, MVT::v1f64
, Expand
);
629 setOperationAction(ISD::FCOS
, MVT::v1f64
, Expand
);
630 setOperationAction(ISD::FDIV
, MVT::v1f64
, Expand
);
631 setOperationAction(ISD::FFLOOR
, MVT::v1f64
, Expand
);
632 setOperationAction(ISD::FMA
, MVT::v1f64
, Expand
);
633 setOperationAction(ISD::FMUL
, MVT::v1f64
, Expand
);
634 setOperationAction(ISD::FNEARBYINT
, MVT::v1f64
, Expand
);
635 setOperationAction(ISD::FNEG
, MVT::v1f64
, Expand
);
636 setOperationAction(ISD::FPOW
, MVT::v1f64
, Expand
);
637 setOperationAction(ISD::FREM
, MVT::v1f64
, Expand
);
638 setOperationAction(ISD::FROUND
, MVT::v1f64
, Expand
);
639 setOperationAction(ISD::FRINT
, MVT::v1f64
, Expand
);
640 setOperationAction(ISD::FSIN
, MVT::v1f64
, Expand
);
641 setOperationAction(ISD::FSINCOS
, MVT::v1f64
, Expand
);
642 setOperationAction(ISD::FSQRT
, MVT::v1f64
, Expand
);
643 setOperationAction(ISD::FSUB
, MVT::v1f64
, Expand
);
644 setOperationAction(ISD::FTRUNC
, MVT::v1f64
, Expand
);
645 setOperationAction(ISD::SETCC
, MVT::v1f64
, Expand
);
646 setOperationAction(ISD::BR_CC
, MVT::v1f64
, Expand
);
647 setOperationAction(ISD::SELECT
, MVT::v1f64
, Expand
);
648 setOperationAction(ISD::SELECT_CC
, MVT::v1f64
, Expand
);
649 setOperationAction(ISD::FP_EXTEND
, MVT::v1f64
, Expand
);
651 setOperationAction(ISD::FP_TO_SINT
, MVT::v1i64
, Expand
);
652 setOperationAction(ISD::FP_TO_UINT
, MVT::v1i64
, Expand
);
653 setOperationAction(ISD::SINT_TO_FP
, MVT::v1i64
, Expand
);
654 setOperationAction(ISD::UINT_TO_FP
, MVT::v1i64
, Expand
);
655 setOperationAction(ISD::FP_ROUND
, MVT::v1f64
, Expand
);
657 setOperationAction(ISD::MUL
, MVT::v1i64
, Expand
);
659 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
660 // elements smaller than i32, so promote the input to i32 first.
661 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v4i8
, MVT::v4i32
);
662 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v4i8
, MVT::v4i32
);
663 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v4i16
, MVT::v4i32
);
664 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v4i16
, MVT::v4i32
);
665 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
666 // -> v8f16 conversions.
667 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v8i8
, MVT::v8i32
);
668 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v8i8
, MVT::v8i32
);
669 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v8i16
, MVT::v8i32
);
670 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v8i16
, MVT::v8i32
);
671 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
672 setOperationAction(ISD::SINT_TO_FP
, MVT::v2i32
, Custom
);
673 setOperationAction(ISD::UINT_TO_FP
, MVT::v2i32
, Custom
);
674 setOperationAction(ISD::SINT_TO_FP
, MVT::v2i64
, Custom
);
675 setOperationAction(ISD::UINT_TO_FP
, MVT::v2i64
, Custom
);
676 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
677 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
678 setOperationAction(ISD::SINT_TO_FP
, MVT::v4i32
, Custom
);
679 setOperationAction(ISD::UINT_TO_FP
, MVT::v4i32
, Custom
);
681 setOperationAction(ISD::CTLZ
, MVT::v1i64
, Expand
);
682 setOperationAction(ISD::CTLZ
, MVT::v2i64
, Expand
);
684 // AArch64 doesn't have MUL.2d:
685 setOperationAction(ISD::MUL
, MVT::v2i64
, Expand
);
686 // Custom handling for some quad-vector types to detect MULL.
687 setOperationAction(ISD::MUL
, MVT::v8i16
, Custom
);
688 setOperationAction(ISD::MUL
, MVT::v4i32
, Custom
);
689 setOperationAction(ISD::MUL
, MVT::v2i64
, Custom
);
692 for (MVT VT
: MVT::integer_valuetypes()) {
693 setOperationAction(ISD::VECREDUCE_ADD
, VT
, Custom
);
694 setOperationAction(ISD::VECREDUCE_SMAX
, VT
, Custom
);
695 setOperationAction(ISD::VECREDUCE_SMIN
, VT
, Custom
);
696 setOperationAction(ISD::VECREDUCE_UMAX
, VT
, Custom
);
697 setOperationAction(ISD::VECREDUCE_UMIN
, VT
, Custom
);
699 for (MVT VT
: MVT::fp_valuetypes()) {
700 setOperationAction(ISD::VECREDUCE_FMAX
, VT
, Custom
);
701 setOperationAction(ISD::VECREDUCE_FMIN
, VT
, Custom
);
704 setOperationAction(ISD::ANY_EXTEND
, MVT::v4i32
, Legal
);
705 setTruncStoreAction(MVT::v2i32
, MVT::v2i16
, Expand
);
706 // Likewise, narrowing and extending vector loads/stores aren't handled
708 for (MVT VT
: MVT::vector_valuetypes()) {
709 setOperationAction(ISD::SIGN_EXTEND_INREG
, VT
, Expand
);
711 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
) {
712 setOperationAction(ISD::MULHS
, VT
, Legal
);
713 setOperationAction(ISD::MULHU
, VT
, Legal
);
715 setOperationAction(ISD::MULHS
, VT
, Expand
);
716 setOperationAction(ISD::MULHU
, VT
, Expand
);
718 setOperationAction(ISD::SMUL_LOHI
, VT
, Expand
);
719 setOperationAction(ISD::UMUL_LOHI
, VT
, Expand
);
721 setOperationAction(ISD::BSWAP
, VT
, Expand
);
722 setOperationAction(ISD::CTTZ
, VT
, Expand
);
724 for (MVT InnerVT
: MVT::vector_valuetypes()) {
725 setTruncStoreAction(VT
, InnerVT
, Expand
);
726 setLoadExtAction(ISD::SEXTLOAD
, VT
, InnerVT
, Expand
);
727 setLoadExtAction(ISD::ZEXTLOAD
, VT
, InnerVT
, Expand
);
728 setLoadExtAction(ISD::EXTLOAD
, VT
, InnerVT
, Expand
);
732 // AArch64 has implementations of a lot of rounding-like FP operations.
733 for (MVT Ty
: {MVT::v2f32
, MVT::v4f32
, MVT::v2f64
}) {
734 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
735 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
736 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
737 setOperationAction(ISD::FRINT
, Ty
, Legal
);
738 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
739 setOperationAction(ISD::FROUND
, Ty
, Legal
);
742 setTruncStoreAction(MVT::v4i16
, MVT::v4i8
, Custom
);
745 PredictableSelectIsExpensive
= Subtarget
->predictableSelectIsExpensive();
748 void AArch64TargetLowering::addTypeForNEON(MVT VT
, MVT PromotedBitwiseVT
) {
749 assert(VT
.isVector() && "VT should be a vector type");
751 if (VT
.isFloatingPoint()) {
752 MVT PromoteTo
= EVT(VT
).changeVectorElementTypeToInteger().getSimpleVT();
753 setOperationPromotedToType(ISD::LOAD
, VT
, PromoteTo
);
754 setOperationPromotedToType(ISD::STORE
, VT
, PromoteTo
);
757 // Mark vector float intrinsics as expand.
758 if (VT
== MVT::v2f32
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
) {
759 setOperationAction(ISD::FSIN
, VT
, Expand
);
760 setOperationAction(ISD::FCOS
, VT
, Expand
);
761 setOperationAction(ISD::FPOW
, VT
, Expand
);
762 setOperationAction(ISD::FLOG
, VT
, Expand
);
763 setOperationAction(ISD::FLOG2
, VT
, Expand
);
764 setOperationAction(ISD::FLOG10
, VT
, Expand
);
765 setOperationAction(ISD::FEXP
, VT
, Expand
);
766 setOperationAction(ISD::FEXP2
, VT
, Expand
);
768 // But we do support custom-lowering for FCOPYSIGN.
769 setOperationAction(ISD::FCOPYSIGN
, VT
, Custom
);
772 setOperationAction(ISD::EXTRACT_VECTOR_ELT
, VT
, Custom
);
773 setOperationAction(ISD::INSERT_VECTOR_ELT
, VT
, Custom
);
774 setOperationAction(ISD::BUILD_VECTOR
, VT
, Custom
);
775 setOperationAction(ISD::VECTOR_SHUFFLE
, VT
, Custom
);
776 setOperationAction(ISD::EXTRACT_SUBVECTOR
, VT
, Custom
);
777 setOperationAction(ISD::SRA
, VT
, Custom
);
778 setOperationAction(ISD::SRL
, VT
, Custom
);
779 setOperationAction(ISD::SHL
, VT
, Custom
);
780 setOperationAction(ISD::AND
, VT
, Custom
);
781 setOperationAction(ISD::OR
, VT
, Custom
);
782 setOperationAction(ISD::SETCC
, VT
, Custom
);
783 setOperationAction(ISD::CONCAT_VECTORS
, VT
, Legal
);
785 setOperationAction(ISD::SELECT
, VT
, Expand
);
786 setOperationAction(ISD::SELECT_CC
, VT
, Expand
);
787 setOperationAction(ISD::VSELECT
, VT
, Expand
);
788 for (MVT InnerVT
: MVT::all_valuetypes())
789 setLoadExtAction(ISD::EXTLOAD
, InnerVT
, VT
, Expand
);
791 // CNT supports only B element sizes, then use UADDLP to widen.
792 if (VT
!= MVT::v8i8
&& VT
!= MVT::v16i8
)
793 setOperationAction(ISD::CTPOP
, VT
, Custom
);
795 setOperationAction(ISD::UDIV
, VT
, Expand
);
796 setOperationAction(ISD::SDIV
, VT
, Expand
);
797 setOperationAction(ISD::UREM
, VT
, Expand
);
798 setOperationAction(ISD::SREM
, VT
, Expand
);
799 setOperationAction(ISD::FREM
, VT
, Expand
);
801 setOperationAction(ISD::FP_TO_SINT
, VT
, Custom
);
802 setOperationAction(ISD::FP_TO_UINT
, VT
, Custom
);
804 if (!VT
.isFloatingPoint())
805 setOperationAction(ISD::ABS
, VT
, Legal
);
807 // [SU][MIN|MAX] are available for all NEON types apart from i64.
808 if (!VT
.isFloatingPoint() && VT
!= MVT::v2i64
&& VT
!= MVT::v1i64
)
809 for (unsigned Opcode
: {ISD::SMIN
, ISD::SMAX
, ISD::UMIN
, ISD::UMAX
})
810 setOperationAction(Opcode
, VT
, Legal
);
812 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
813 if (VT
.isFloatingPoint() &&
814 (VT
.getVectorElementType() != MVT::f16
|| Subtarget
->hasFullFP16()))
815 for (unsigned Opcode
:
816 {ISD::FMINIMUM
, ISD::FMAXIMUM
, ISD::FMINNUM
, ISD::FMAXNUM
})
817 setOperationAction(Opcode
, VT
, Legal
);
819 if (Subtarget
->isLittleEndian()) {
820 for (unsigned im
= (unsigned)ISD::PRE_INC
;
821 im
!= (unsigned)ISD::LAST_INDEXED_MODE
; ++im
) {
822 setIndexedLoadAction(im
, VT
, Legal
);
823 setIndexedStoreAction(im
, VT
, Legal
);
828 void AArch64TargetLowering::addDRTypeForNEON(MVT VT
) {
829 addRegisterClass(VT
, &AArch64::FPR64RegClass
);
830 addTypeForNEON(VT
, MVT::v2i32
);
833 void AArch64TargetLowering::addQRTypeForNEON(MVT VT
) {
834 addRegisterClass(VT
, &AArch64::FPR128RegClass
);
835 addTypeForNEON(VT
, MVT::v4i32
);
838 EVT
AArch64TargetLowering::getSetCCResultType(const DataLayout
&, LLVMContext
&,
842 return VT
.changeVectorElementTypeToInteger();
845 static bool optimizeLogicalImm(SDValue Op
, unsigned Size
, uint64_t Imm
,
846 const APInt
&Demanded
,
847 TargetLowering::TargetLoweringOpt
&TLO
,
849 uint64_t OldImm
= Imm
, NewImm
, Enc
;
850 uint64_t Mask
= ((uint64_t)(-1LL) >> (64 - Size
)), OrigMask
= Mask
;
852 // Return if the immediate is already all zeros, all ones, a bimm32 or a
854 if (Imm
== 0 || Imm
== Mask
||
855 AArch64_AM::isLogicalImmediate(Imm
& Mask
, Size
))
858 unsigned EltSize
= Size
;
859 uint64_t DemandedBits
= Demanded
.getZExtValue();
861 // Clear bits that are not demanded.
865 // The goal here is to set the non-demanded bits in a way that minimizes
866 // the number of switching between 0 and 1. In order to achieve this goal,
867 // we set the non-demanded bits to the value of the preceding demanded bits.
868 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
869 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
870 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
871 // The final result is 0b11000011.
872 uint64_t NonDemandedBits
= ~DemandedBits
;
873 uint64_t InvertedImm
= ~Imm
& DemandedBits
;
874 uint64_t RotatedImm
=
875 ((InvertedImm
<< 1) | (InvertedImm
>> (EltSize
- 1) & 1)) &
877 uint64_t Sum
= RotatedImm
+ NonDemandedBits
;
878 bool Carry
= NonDemandedBits
& ~Sum
& (1ULL << (EltSize
- 1));
879 uint64_t Ones
= (Sum
+ Carry
) & NonDemandedBits
;
880 NewImm
= (Imm
| Ones
) & Mask
;
882 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
883 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
884 // we halve the element size and continue the search.
885 if (isShiftedMask_64(NewImm
) || isShiftedMask_64(~(NewImm
| ~Mask
)))
888 // We cannot shrink the element size any further if it is 2-bits.
894 uint64_t Hi
= Imm
>> EltSize
, DemandedBitsHi
= DemandedBits
>> EltSize
;
896 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
897 if (((Imm
^ Hi
) & (DemandedBits
& DemandedBitsHi
) & Mask
) != 0)
900 // Merge the upper and lower halves of Imm and DemandedBits.
902 DemandedBits
|= DemandedBitsHi
;
907 // Replicate the element across the register width.
908 while (EltSize
< Size
) {
909 NewImm
|= NewImm
<< EltSize
;
914 assert(((OldImm
^ NewImm
) & Demanded
.getZExtValue()) == 0 &&
915 "demanded bits should never be altered");
916 assert(OldImm
!= NewImm
&& "the new imm shouldn't be equal to the old imm");
918 // Create the new constant immediate node.
919 EVT VT
= Op
.getValueType();
923 // If the new constant immediate is all-zeros or all-ones, let the target
924 // independent DAG combine optimize this node.
925 if (NewImm
== 0 || NewImm
== OrigMask
) {
926 New
= TLO
.DAG
.getNode(Op
.getOpcode(), DL
, VT
, Op
.getOperand(0),
927 TLO
.DAG
.getConstant(NewImm
, DL
, VT
));
928 // Otherwise, create a machine node so that target independent DAG combine
929 // doesn't undo this optimization.
931 Enc
= AArch64_AM::encodeLogicalImmediate(NewImm
, Size
);
932 SDValue EncConst
= TLO
.DAG
.getTargetConstant(Enc
, DL
, VT
);
934 TLO
.DAG
.getMachineNode(NewOpc
, DL
, VT
, Op
.getOperand(0), EncConst
), 0);
937 return TLO
.CombineTo(Op
, New
);
940 bool AArch64TargetLowering::targetShrinkDemandedConstant(
941 SDValue Op
, const APInt
&Demanded
, TargetLoweringOpt
&TLO
) const {
942 // Delay this optimization to as late as possible.
946 if (!EnableOptimizeLogicalImm
)
949 EVT VT
= Op
.getValueType();
953 unsigned Size
= VT
.getSizeInBits();
954 assert((Size
== 32 || Size
== 64) &&
955 "i32 or i64 is expected after legalization.");
957 // Exit early if we demand all bits.
958 if (Demanded
.countPopulation() == Size
)
962 switch (Op
.getOpcode()) {
966 NewOpc
= Size
== 32 ? AArch64::ANDWri
: AArch64::ANDXri
;
969 NewOpc
= Size
== 32 ? AArch64::ORRWri
: AArch64::ORRXri
;
972 NewOpc
= Size
== 32 ? AArch64::EORWri
: AArch64::EORXri
;
975 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
978 uint64_t Imm
= C
->getZExtValue();
979 return optimizeLogicalImm(Op
, Size
, Imm
, Demanded
, TLO
, NewOpc
);
982 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
983 /// Mask are known to be either zero or one and return them Known.
984 void AArch64TargetLowering::computeKnownBitsForTargetNode(
985 const SDValue Op
, KnownBits
&Known
,
986 const APInt
&DemandedElts
, const SelectionDAG
&DAG
, unsigned Depth
) const {
987 switch (Op
.getOpcode()) {
990 case AArch64ISD::CSEL
: {
992 Known
= DAG
.computeKnownBits(Op
->getOperand(0), Depth
+ 1);
993 Known2
= DAG
.computeKnownBits(Op
->getOperand(1), Depth
+ 1);
994 Known
.Zero
&= Known2
.Zero
;
995 Known
.One
&= Known2
.One
;
998 case ISD::INTRINSIC_W_CHAIN
: {
999 ConstantSDNode
*CN
= cast
<ConstantSDNode
>(Op
->getOperand(1));
1000 Intrinsic::ID IntID
= static_cast<Intrinsic::ID
>(CN
->getZExtValue());
1003 case Intrinsic::aarch64_ldaxr
:
1004 case Intrinsic::aarch64_ldxr
: {
1005 unsigned BitWidth
= Known
.getBitWidth();
1006 EVT VT
= cast
<MemIntrinsicSDNode
>(Op
)->getMemoryVT();
1007 unsigned MemBits
= VT
.getScalarSizeInBits();
1008 Known
.Zero
|= APInt::getHighBitsSet(BitWidth
, BitWidth
- MemBits
);
1014 case ISD::INTRINSIC_WO_CHAIN
:
1015 case ISD::INTRINSIC_VOID
: {
1016 unsigned IntNo
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
1020 case Intrinsic::aarch64_neon_umaxv
:
1021 case Intrinsic::aarch64_neon_uminv
: {
1022 // Figure out the datatype of the vector operand. The UMINV instruction
1023 // will zero extend the result, so we can mark as known zero all the
1024 // bits larger than the element datatype. 32-bit or larget doesn't need
1025 // this as those are legal types and will be handled by isel directly.
1026 MVT VT
= Op
.getOperand(1).getValueType().getSimpleVT();
1027 unsigned BitWidth
= Known
.getBitWidth();
1028 if (VT
== MVT::v8i8
|| VT
== MVT::v16i8
) {
1029 assert(BitWidth
>= 8 && "Unexpected width!");
1030 APInt Mask
= APInt::getHighBitsSet(BitWidth
, BitWidth
- 8);
1032 } else if (VT
== MVT::v4i16
|| VT
== MVT::v8i16
) {
1033 assert(BitWidth
>= 16 && "Unexpected width!");
1034 APInt Mask
= APInt::getHighBitsSet(BitWidth
, BitWidth
- 16);
1044 MVT
AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout
&DL
,
1049 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT
,
1053 if (Subtarget
->requiresStrictAlign())
1057 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1058 *Fast
= !Subtarget
->isMisaligned128StoreSlow() || VT
.getStoreSize() != 16 ||
1059 // See comments in performSTORECombine() for more details about
1060 // these conditions.
1062 // Code that uses clang vector extensions can mark that it
1063 // wants unaligned accesses to be treated as fast by
1064 // underspecifying alignment to be 1 or 2.
1067 // Disregard v2i64. Memcpy lowering produces those and splitting
1068 // them regresses performance on micro-benchmarks and olden/bh.
1075 AArch64TargetLowering::createFastISel(FunctionLoweringInfo
&funcInfo
,
1076 const TargetLibraryInfo
*libInfo
) const {
1077 return AArch64::createFastISel(funcInfo
, libInfo
);
1080 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode
) const {
1081 switch ((AArch64ISD::NodeType
)Opcode
) {
1082 case AArch64ISD::FIRST_NUMBER
: break;
1083 case AArch64ISD::CALL
: return "AArch64ISD::CALL";
1084 case AArch64ISD::ADRP
: return "AArch64ISD::ADRP";
1085 case AArch64ISD::ADR
: return "AArch64ISD::ADR";
1086 case AArch64ISD::ADDlow
: return "AArch64ISD::ADDlow";
1087 case AArch64ISD::LOADgot
: return "AArch64ISD::LOADgot";
1088 case AArch64ISD::RET_FLAG
: return "AArch64ISD::RET_FLAG";
1089 case AArch64ISD::BRCOND
: return "AArch64ISD::BRCOND";
1090 case AArch64ISD::CSEL
: return "AArch64ISD::CSEL";
1091 case AArch64ISD::FCSEL
: return "AArch64ISD::FCSEL";
1092 case AArch64ISD::CSINV
: return "AArch64ISD::CSINV";
1093 case AArch64ISD::CSNEG
: return "AArch64ISD::CSNEG";
1094 case AArch64ISD::CSINC
: return "AArch64ISD::CSINC";
1095 case AArch64ISD::THREAD_POINTER
: return "AArch64ISD::THREAD_POINTER";
1096 case AArch64ISD::TLSDESC_CALLSEQ
: return "AArch64ISD::TLSDESC_CALLSEQ";
1097 case AArch64ISD::ADC
: return "AArch64ISD::ADC";
1098 case AArch64ISD::SBC
: return "AArch64ISD::SBC";
1099 case AArch64ISD::ADDS
: return "AArch64ISD::ADDS";
1100 case AArch64ISD::SUBS
: return "AArch64ISD::SUBS";
1101 case AArch64ISD::ADCS
: return "AArch64ISD::ADCS";
1102 case AArch64ISD::SBCS
: return "AArch64ISD::SBCS";
1103 case AArch64ISD::ANDS
: return "AArch64ISD::ANDS";
1104 case AArch64ISD::CCMP
: return "AArch64ISD::CCMP";
1105 case AArch64ISD::CCMN
: return "AArch64ISD::CCMN";
1106 case AArch64ISD::FCCMP
: return "AArch64ISD::FCCMP";
1107 case AArch64ISD::FCMP
: return "AArch64ISD::FCMP";
1108 case AArch64ISD::DUP
: return "AArch64ISD::DUP";
1109 case AArch64ISD::DUPLANE8
: return "AArch64ISD::DUPLANE8";
1110 case AArch64ISD::DUPLANE16
: return "AArch64ISD::DUPLANE16";
1111 case AArch64ISD::DUPLANE32
: return "AArch64ISD::DUPLANE32";
1112 case AArch64ISD::DUPLANE64
: return "AArch64ISD::DUPLANE64";
1113 case AArch64ISD::MOVI
: return "AArch64ISD::MOVI";
1114 case AArch64ISD::MOVIshift
: return "AArch64ISD::MOVIshift";
1115 case AArch64ISD::MOVIedit
: return "AArch64ISD::MOVIedit";
1116 case AArch64ISD::MOVImsl
: return "AArch64ISD::MOVImsl";
1117 case AArch64ISD::FMOV
: return "AArch64ISD::FMOV";
1118 case AArch64ISD::MVNIshift
: return "AArch64ISD::MVNIshift";
1119 case AArch64ISD::MVNImsl
: return "AArch64ISD::MVNImsl";
1120 case AArch64ISD::BICi
: return "AArch64ISD::BICi";
1121 case AArch64ISD::ORRi
: return "AArch64ISD::ORRi";
1122 case AArch64ISD::BSL
: return "AArch64ISD::BSL";
1123 case AArch64ISD::NEG
: return "AArch64ISD::NEG";
1124 case AArch64ISD::EXTR
: return "AArch64ISD::EXTR";
1125 case AArch64ISD::ZIP1
: return "AArch64ISD::ZIP1";
1126 case AArch64ISD::ZIP2
: return "AArch64ISD::ZIP2";
1127 case AArch64ISD::UZP1
: return "AArch64ISD::UZP1";
1128 case AArch64ISD::UZP2
: return "AArch64ISD::UZP2";
1129 case AArch64ISD::TRN1
: return "AArch64ISD::TRN1";
1130 case AArch64ISD::TRN2
: return "AArch64ISD::TRN2";
1131 case AArch64ISD::REV16
: return "AArch64ISD::REV16";
1132 case AArch64ISD::REV32
: return "AArch64ISD::REV32";
1133 case AArch64ISD::REV64
: return "AArch64ISD::REV64";
1134 case AArch64ISD::EXT
: return "AArch64ISD::EXT";
1135 case AArch64ISD::VSHL
: return "AArch64ISD::VSHL";
1136 case AArch64ISD::VLSHR
: return "AArch64ISD::VLSHR";
1137 case AArch64ISD::VASHR
: return "AArch64ISD::VASHR";
1138 case AArch64ISD::CMEQ
: return "AArch64ISD::CMEQ";
1139 case AArch64ISD::CMGE
: return "AArch64ISD::CMGE";
1140 case AArch64ISD::CMGT
: return "AArch64ISD::CMGT";
1141 case AArch64ISD::CMHI
: return "AArch64ISD::CMHI";
1142 case AArch64ISD::CMHS
: return "AArch64ISD::CMHS";
1143 case AArch64ISD::FCMEQ
: return "AArch64ISD::FCMEQ";
1144 case AArch64ISD::FCMGE
: return "AArch64ISD::FCMGE";
1145 case AArch64ISD::FCMGT
: return "AArch64ISD::FCMGT";
1146 case AArch64ISD::CMEQz
: return "AArch64ISD::CMEQz";
1147 case AArch64ISD::CMGEz
: return "AArch64ISD::CMGEz";
1148 case AArch64ISD::CMGTz
: return "AArch64ISD::CMGTz";
1149 case AArch64ISD::CMLEz
: return "AArch64ISD::CMLEz";
1150 case AArch64ISD::CMLTz
: return "AArch64ISD::CMLTz";
1151 case AArch64ISD::FCMEQz
: return "AArch64ISD::FCMEQz";
1152 case AArch64ISD::FCMGEz
: return "AArch64ISD::FCMGEz";
1153 case AArch64ISD::FCMGTz
: return "AArch64ISD::FCMGTz";
1154 case AArch64ISD::FCMLEz
: return "AArch64ISD::FCMLEz";
1155 case AArch64ISD::FCMLTz
: return "AArch64ISD::FCMLTz";
1156 case AArch64ISD::SADDV
: return "AArch64ISD::SADDV";
1157 case AArch64ISD::UADDV
: return "AArch64ISD::UADDV";
1158 case AArch64ISD::SMINV
: return "AArch64ISD::SMINV";
1159 case AArch64ISD::UMINV
: return "AArch64ISD::UMINV";
1160 case AArch64ISD::SMAXV
: return "AArch64ISD::SMAXV";
1161 case AArch64ISD::UMAXV
: return "AArch64ISD::UMAXV";
1162 case AArch64ISD::NOT
: return "AArch64ISD::NOT";
1163 case AArch64ISD::BIT
: return "AArch64ISD::BIT";
1164 case AArch64ISD::CBZ
: return "AArch64ISD::CBZ";
1165 case AArch64ISD::CBNZ
: return "AArch64ISD::CBNZ";
1166 case AArch64ISD::TBZ
: return "AArch64ISD::TBZ";
1167 case AArch64ISD::TBNZ
: return "AArch64ISD::TBNZ";
1168 case AArch64ISD::TC_RETURN
: return "AArch64ISD::TC_RETURN";
1169 case AArch64ISD::PREFETCH
: return "AArch64ISD::PREFETCH";
1170 case AArch64ISD::SITOF
: return "AArch64ISD::SITOF";
1171 case AArch64ISD::UITOF
: return "AArch64ISD::UITOF";
1172 case AArch64ISD::NVCAST
: return "AArch64ISD::NVCAST";
1173 case AArch64ISD::SQSHL_I
: return "AArch64ISD::SQSHL_I";
1174 case AArch64ISD::UQSHL_I
: return "AArch64ISD::UQSHL_I";
1175 case AArch64ISD::SRSHR_I
: return "AArch64ISD::SRSHR_I";
1176 case AArch64ISD::URSHR_I
: return "AArch64ISD::URSHR_I";
1177 case AArch64ISD::SQSHLU_I
: return "AArch64ISD::SQSHLU_I";
1178 case AArch64ISD::WrapperLarge
: return "AArch64ISD::WrapperLarge";
1179 case AArch64ISD::LD2post
: return "AArch64ISD::LD2post";
1180 case AArch64ISD::LD3post
: return "AArch64ISD::LD3post";
1181 case AArch64ISD::LD4post
: return "AArch64ISD::LD4post";
1182 case AArch64ISD::ST2post
: return "AArch64ISD::ST2post";
1183 case AArch64ISD::ST3post
: return "AArch64ISD::ST3post";
1184 case AArch64ISD::ST4post
: return "AArch64ISD::ST4post";
1185 case AArch64ISD::LD1x2post
: return "AArch64ISD::LD1x2post";
1186 case AArch64ISD::LD1x3post
: return "AArch64ISD::LD1x3post";
1187 case AArch64ISD::LD1x4post
: return "AArch64ISD::LD1x4post";
1188 case AArch64ISD::ST1x2post
: return "AArch64ISD::ST1x2post";
1189 case AArch64ISD::ST1x3post
: return "AArch64ISD::ST1x3post";
1190 case AArch64ISD::ST1x4post
: return "AArch64ISD::ST1x4post";
1191 case AArch64ISD::LD1DUPpost
: return "AArch64ISD::LD1DUPpost";
1192 case AArch64ISD::LD2DUPpost
: return "AArch64ISD::LD2DUPpost";
1193 case AArch64ISD::LD3DUPpost
: return "AArch64ISD::LD3DUPpost";
1194 case AArch64ISD::LD4DUPpost
: return "AArch64ISD::LD4DUPpost";
1195 case AArch64ISD::LD1LANEpost
: return "AArch64ISD::LD1LANEpost";
1196 case AArch64ISD::LD2LANEpost
: return "AArch64ISD::LD2LANEpost";
1197 case AArch64ISD::LD3LANEpost
: return "AArch64ISD::LD3LANEpost";
1198 case AArch64ISD::LD4LANEpost
: return "AArch64ISD::LD4LANEpost";
1199 case AArch64ISD::ST2LANEpost
: return "AArch64ISD::ST2LANEpost";
1200 case AArch64ISD::ST3LANEpost
: return "AArch64ISD::ST3LANEpost";
1201 case AArch64ISD::ST4LANEpost
: return "AArch64ISD::ST4LANEpost";
1202 case AArch64ISD::SMULL
: return "AArch64ISD::SMULL";
1203 case AArch64ISD::UMULL
: return "AArch64ISD::UMULL";
1204 case AArch64ISD::FRECPE
: return "AArch64ISD::FRECPE";
1205 case AArch64ISD::FRECPS
: return "AArch64ISD::FRECPS";
1206 case AArch64ISD::FRSQRTE
: return "AArch64ISD::FRSQRTE";
1207 case AArch64ISD::FRSQRTS
: return "AArch64ISD::FRSQRTS";
1213 AArch64TargetLowering::EmitF128CSEL(MachineInstr
&MI
,
1214 MachineBasicBlock
*MBB
) const {
1215 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1219 // [... previous instrs leading to comparison ...]
1225 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1227 MachineFunction
*MF
= MBB
->getParent();
1228 const TargetInstrInfo
*TII
= Subtarget
->getInstrInfo();
1229 const BasicBlock
*LLVM_BB
= MBB
->getBasicBlock();
1230 DebugLoc DL
= MI
.getDebugLoc();
1231 MachineFunction::iterator It
= ++MBB
->getIterator();
1233 unsigned DestReg
= MI
.getOperand(0).getReg();
1234 unsigned IfTrueReg
= MI
.getOperand(1).getReg();
1235 unsigned IfFalseReg
= MI
.getOperand(2).getReg();
1236 unsigned CondCode
= MI
.getOperand(3).getImm();
1237 bool NZCVKilled
= MI
.getOperand(4).isKill();
1239 MachineBasicBlock
*TrueBB
= MF
->CreateMachineBasicBlock(LLVM_BB
);
1240 MachineBasicBlock
*EndBB
= MF
->CreateMachineBasicBlock(LLVM_BB
);
1241 MF
->insert(It
, TrueBB
);
1242 MF
->insert(It
, EndBB
);
1244 // Transfer rest of current basic-block to EndBB
1245 EndBB
->splice(EndBB
->begin(), MBB
, std::next(MachineBasicBlock::iterator(MI
)),
1247 EndBB
->transferSuccessorsAndUpdatePHIs(MBB
);
1249 BuildMI(MBB
, DL
, TII
->get(AArch64::Bcc
)).addImm(CondCode
).addMBB(TrueBB
);
1250 BuildMI(MBB
, DL
, TII
->get(AArch64::B
)).addMBB(EndBB
);
1251 MBB
->addSuccessor(TrueBB
);
1252 MBB
->addSuccessor(EndBB
);
1254 // TrueBB falls through to the end.
1255 TrueBB
->addSuccessor(EndBB
);
1258 TrueBB
->addLiveIn(AArch64::NZCV
);
1259 EndBB
->addLiveIn(AArch64::NZCV
);
1262 BuildMI(*EndBB
, EndBB
->begin(), DL
, TII
->get(AArch64::PHI
), DestReg
)
1268 MI
.eraseFromParent();
1272 MachineBasicBlock
*AArch64TargetLowering::EmitLoweredCatchRet(
1273 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1274 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1275 BB
->getParent()->getFunction().getPersonalityFn())) &&
1276 "SEH does not use catchret!");
1280 MachineBasicBlock
*AArch64TargetLowering::EmitLoweredCatchPad(
1281 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1282 MI
.eraseFromParent();
1286 MachineBasicBlock
*AArch64TargetLowering::EmitInstrWithCustomInserter(
1287 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1288 switch (MI
.getOpcode()) {
1293 llvm_unreachable("Unexpected instruction for custom inserter!");
1295 case AArch64::F128CSEL
:
1296 return EmitF128CSEL(MI
, BB
);
1298 case TargetOpcode::STACKMAP
:
1299 case TargetOpcode::PATCHPOINT
:
1300 return emitPatchPoint(MI
, BB
);
1302 case AArch64::CATCHRET
:
1303 return EmitLoweredCatchRet(MI
, BB
);
1304 case AArch64::CATCHPAD
:
1305 return EmitLoweredCatchPad(MI
, BB
);
1309 //===----------------------------------------------------------------------===//
1310 // AArch64 Lowering private implementation.
1311 //===----------------------------------------------------------------------===//
1313 //===----------------------------------------------------------------------===//
1315 //===----------------------------------------------------------------------===//
1317 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1319 static AArch64CC::CondCode
changeIntCCToAArch64CC(ISD::CondCode CC
) {
1322 llvm_unreachable("Unknown condition code!");
1324 return AArch64CC::NE
;
1326 return AArch64CC::EQ
;
1328 return AArch64CC::GT
;
1330 return AArch64CC::GE
;
1332 return AArch64CC::LT
;
1334 return AArch64CC::LE
;
1336 return AArch64CC::HI
;
1338 return AArch64CC::HS
;
1340 return AArch64CC::LO
;
1342 return AArch64CC::LS
;
1346 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1347 static void changeFPCCToAArch64CC(ISD::CondCode CC
,
1348 AArch64CC::CondCode
&CondCode
,
1349 AArch64CC::CondCode
&CondCode2
) {
1350 CondCode2
= AArch64CC::AL
;
1353 llvm_unreachable("Unknown FP condition!");
1356 CondCode
= AArch64CC::EQ
;
1360 CondCode
= AArch64CC::GT
;
1364 CondCode
= AArch64CC::GE
;
1367 CondCode
= AArch64CC::MI
;
1370 CondCode
= AArch64CC::LS
;
1373 CondCode
= AArch64CC::MI
;
1374 CondCode2
= AArch64CC::GT
;
1377 CondCode
= AArch64CC::VC
;
1380 CondCode
= AArch64CC::VS
;
1383 CondCode
= AArch64CC::EQ
;
1384 CondCode2
= AArch64CC::VS
;
1387 CondCode
= AArch64CC::HI
;
1390 CondCode
= AArch64CC::PL
;
1394 CondCode
= AArch64CC::LT
;
1398 CondCode
= AArch64CC::LE
;
1402 CondCode
= AArch64CC::NE
;
1407 /// Convert a DAG fp condition code to an AArch64 CC.
1408 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1409 /// should be AND'ed instead of OR'ed.
1410 static void changeFPCCToANDAArch64CC(ISD::CondCode CC
,
1411 AArch64CC::CondCode
&CondCode
,
1412 AArch64CC::CondCode
&CondCode2
) {
1413 CondCode2
= AArch64CC::AL
;
1416 changeFPCCToAArch64CC(CC
, CondCode
, CondCode2
);
1417 assert(CondCode2
== AArch64CC::AL
);
1421 // == ((a olt b) || (a ogt b))
1422 // == ((a ord b) && (a une b))
1423 CondCode
= AArch64CC::VC
;
1424 CondCode2
= AArch64CC::NE
;
1428 // == ((a uno b) || (a oeq b))
1429 // == ((a ule b) && (a uge b))
1430 CondCode
= AArch64CC::PL
;
1431 CondCode2
= AArch64CC::LE
;
1436 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1437 /// CC usable with the vector instructions. Fewer operations are available
1438 /// without a real NZCV register, so we have to use less efficient combinations
1439 /// to get the same effect.
1440 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC
,
1441 AArch64CC::CondCode
&CondCode
,
1442 AArch64CC::CondCode
&CondCode2
,
1447 // Mostly the scalar mappings work fine.
1448 changeFPCCToAArch64CC(CC
, CondCode
, CondCode2
);
1454 CondCode
= AArch64CC::MI
;
1455 CondCode2
= AArch64CC::GE
;
1462 // All of the compare-mask comparisons are ordered, but we can switch
1463 // between the two by a double inversion. E.g. ULE == !OGT.
1465 changeFPCCToAArch64CC(getSetCCInverse(CC
, false), CondCode
, CondCode2
);
1470 static bool isLegalArithImmed(uint64_t C
) {
1471 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1472 bool IsLegal
= (C
>> 12 == 0) || ((C
& 0xFFFULL
) == 0 && C
>> 24 == 0);
1473 LLVM_DEBUG(dbgs() << "Is imm " << C
1474 << " legal: " << (IsLegal
? "yes\n" : "no\n"));
1478 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1479 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1480 // can be set differently by this operation. It comes down to whether
1481 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1482 // everything is fine. If not then the optimization is wrong. Thus general
1483 // comparisons are only valid if op2 != 0.
1485 // So, finally, the only LLVM-native comparisons that don't mention C and V
1486 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1487 // the absence of information about op2.
1488 static bool isCMN(SDValue Op
, ISD::CondCode CC
) {
1489 return Op
.getOpcode() == ISD::SUB
&& isNullConstant(Op
.getOperand(0)) &&
1490 (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
);
1493 static SDValue
emitComparison(SDValue LHS
, SDValue RHS
, ISD::CondCode CC
,
1494 const SDLoc
&dl
, SelectionDAG
&DAG
) {
1495 EVT VT
= LHS
.getValueType();
1496 const bool FullFP16
=
1497 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
1499 if (VT
.isFloatingPoint()) {
1500 assert(VT
!= MVT::f128
);
1501 if (VT
== MVT::f16
&& !FullFP16
) {
1502 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, LHS
);
1503 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, RHS
);
1506 return DAG
.getNode(AArch64ISD::FCMP
, dl
, VT
, LHS
, RHS
);
1509 // The CMP instruction is just an alias for SUBS, and representing it as
1510 // SUBS means that it's possible to get CSE with subtract operations.
1511 // A later phase can perform the optimization of setting the destination
1512 // register to WZR/XZR if it ends up being unused.
1513 unsigned Opcode
= AArch64ISD::SUBS
;
1515 if (isCMN(RHS
, CC
)) {
1516 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1517 Opcode
= AArch64ISD::ADDS
;
1518 RHS
= RHS
.getOperand(1);
1519 } else if (isCMN(LHS
, CC
)) {
1520 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1521 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1522 Opcode
= AArch64ISD::ADDS
;
1523 LHS
= LHS
.getOperand(1);
1524 } else if (LHS
.getOpcode() == ISD::AND
&& isNullConstant(RHS
) &&
1525 !isUnsignedIntSetCC(CC
)) {
1526 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1527 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1528 // of the signed comparisons.
1529 Opcode
= AArch64ISD::ANDS
;
1530 RHS
= LHS
.getOperand(1);
1531 LHS
= LHS
.getOperand(0);
1534 return DAG
.getNode(Opcode
, dl
, DAG
.getVTList(VT
, MVT_CC
), LHS
, RHS
)
1538 /// \defgroup AArch64CCMP CMP;CCMP matching
1540 /// These functions deal with the formation of CMP;CCMP;... sequences.
1541 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1542 /// a comparison. They set the NZCV flags to a predefined value if their
1543 /// predicate is false. This allows to express arbitrary conjunctions, for
1544 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1547 /// ccmp B, inv(CB), CA
1548 /// check for CB flags
1550 /// This naturally lets us implement chains of AND operations with SETCC
1551 /// operands. And we can even implement some other situations by transforming
1553 /// - We can implement (NEG SETCC) i.e. negating a single comparison by
1554 /// negating the flags used in a CCMP/FCCMP operations.
1555 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1556 /// by negating the flags we test for afterwards. i.e.
1557 /// NEG (CMP CCMP CCCMP ...) can be implemented.
1558 /// - Note that we can only ever negate all previously processed results.
1559 /// What we can not implement by flipping the flags to test is a negation
1560 /// of two sub-trees (because the negation affects all sub-trees emitted so
1561 /// far, so the 2nd sub-tree we emit would also affect the first).
1562 /// With those tools we can implement some OR operations:
1563 /// - (OR (SETCC A) (SETCC B)) can be implemented via:
1564 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1565 /// - After transforming OR to NEG/AND combinations we may be able to use NEG
1566 /// elimination rules from earlier to implement the whole thing as a
1567 /// CCMP/FCCMP chain.
1569 /// As complete example:
1570 /// or (or (setCA (cmp A)) (setCB (cmp B)))
1571 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1572 /// can be reassociated to:
1573 /// or (and (setCC (cmp C)) setCD (cmp D))
1574 // (or (setCA (cmp A)) (setCB (cmp B)))
1575 /// can be transformed to:
1576 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1577 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1578 /// which can be implemented as:
1580 /// ccmp D, inv(CD), CC
1581 /// ccmp A, CA, inv(CD)
1582 /// ccmp B, CB, inv(CA)
1583 /// check for CB flags
1585 /// A counterexample is "or (and A B) (and C D)" which translates to
1586 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1587 /// can only implement 1 of the inner (not) operations, but not both!
1590 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1591 static SDValue
emitConditionalComparison(SDValue LHS
, SDValue RHS
,
1592 ISD::CondCode CC
, SDValue CCOp
,
1593 AArch64CC::CondCode Predicate
,
1594 AArch64CC::CondCode OutCC
,
1595 const SDLoc
&DL
, SelectionDAG
&DAG
) {
1596 unsigned Opcode
= 0;
1597 const bool FullFP16
=
1598 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
1600 if (LHS
.getValueType().isFloatingPoint()) {
1601 assert(LHS
.getValueType() != MVT::f128
);
1602 if (LHS
.getValueType() == MVT::f16
&& !FullFP16
) {
1603 LHS
= DAG
.getNode(ISD::FP_EXTEND
, DL
, MVT::f32
, LHS
);
1604 RHS
= DAG
.getNode(ISD::FP_EXTEND
, DL
, MVT::f32
, RHS
);
1606 Opcode
= AArch64ISD::FCCMP
;
1607 } else if (RHS
.getOpcode() == ISD::SUB
) {
1608 SDValue SubOp0
= RHS
.getOperand(0);
1609 if (isNullConstant(SubOp0
) && (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
1610 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1611 Opcode
= AArch64ISD::CCMN
;
1612 RHS
= RHS
.getOperand(1);
1616 Opcode
= AArch64ISD::CCMP
;
1618 SDValue Condition
= DAG
.getConstant(Predicate
, DL
, MVT_CC
);
1619 AArch64CC::CondCode InvOutCC
= AArch64CC::getInvertedCondCode(OutCC
);
1620 unsigned NZCV
= AArch64CC::getNZCVToSatisfyCondCode(InvOutCC
);
1621 SDValue NZCVOp
= DAG
.getConstant(NZCV
, DL
, MVT::i32
);
1622 return DAG
.getNode(Opcode
, DL
, MVT_CC
, LHS
, RHS
, NZCVOp
, Condition
, CCOp
);
1625 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1626 /// expressed as a conjunction. See \ref AArch64CCMP.
1627 /// \param CanNegate Set to true if we can negate the whole sub-tree just by
1628 /// changing the conditions on the SETCC tests.
1629 /// (this means we can call emitConjunctionRec() with
1630 /// Negate==true on this sub-tree)
1631 /// \param MustBeFirst Set to true if this subtree needs to be negated and we
1632 /// cannot do the negation naturally. We are required to
1633 /// emit the subtree first in this case.
1634 /// \param WillNegate Is true if are called when the result of this
1635 /// subexpression must be negated. This happens when the
1636 /// outer expression is an OR. We can use this fact to know
1637 /// that we have a double negation (or (or ...) ...) that
1638 /// can be implemented for free.
1639 static bool canEmitConjunction(const SDValue Val
, bool &CanNegate
,
1640 bool &MustBeFirst
, bool WillNegate
,
1641 unsigned Depth
= 0) {
1642 if (!Val
.hasOneUse())
1644 unsigned Opcode
= Val
->getOpcode();
1645 if (Opcode
== ISD::SETCC
) {
1646 if (Val
->getOperand(0).getValueType() == MVT::f128
)
1649 MustBeFirst
= false;
1652 // Protect against exponential runtime and stack overflow.
1655 if (Opcode
== ISD::AND
|| Opcode
== ISD::OR
) {
1656 bool IsOR
= Opcode
== ISD::OR
;
1657 SDValue O0
= Val
->getOperand(0);
1658 SDValue O1
= Val
->getOperand(1);
1661 if (!canEmitConjunction(O0
, CanNegateL
, MustBeFirstL
, IsOR
, Depth
+1))
1665 if (!canEmitConjunction(O1
, CanNegateR
, MustBeFirstR
, IsOR
, Depth
+1))
1668 if (MustBeFirstL
&& MustBeFirstR
)
1672 // For an OR expression we need to be able to naturally negate at least
1673 // one side or we cannot do the transformation at all.
1674 if (!CanNegateL
&& !CanNegateR
)
1676 // If we the result of the OR will be negated and we can naturally negate
1677 // the leafs, then this sub-tree as a whole negates naturally.
1678 CanNegate
= WillNegate
&& CanNegateL
&& CanNegateR
;
1679 // If we cannot naturally negate the whole sub-tree, then this must be
1681 MustBeFirst
= !CanNegate
;
1683 assert(Opcode
== ISD::AND
&& "Must be OR or AND");
1684 // We cannot naturally negate an AND operation.
1686 MustBeFirst
= MustBeFirstL
|| MustBeFirstR
;
1693 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1694 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1695 /// Tries to transform the given i1 producing node @p Val to a series compare
1696 /// and conditional compare operations. @returns an NZCV flags producing node
1697 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1698 /// transformation was not possible.
1699 /// \p Negate is true if we want this sub-tree being negated just by changing
1700 /// SETCC conditions.
1701 static SDValue
emitConjunctionRec(SelectionDAG
&DAG
, SDValue Val
,
1702 AArch64CC::CondCode
&OutCC
, bool Negate
, SDValue CCOp
,
1703 AArch64CC::CondCode Predicate
) {
1704 // We're at a tree leaf, produce a conditional comparison operation.
1705 unsigned Opcode
= Val
->getOpcode();
1706 if (Opcode
== ISD::SETCC
) {
1707 SDValue LHS
= Val
->getOperand(0);
1708 SDValue RHS
= Val
->getOperand(1);
1709 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Val
->getOperand(2))->get();
1710 bool isInteger
= LHS
.getValueType().isInteger();
1712 CC
= getSetCCInverse(CC
, isInteger
);
1714 // Determine OutCC and handle FP special case.
1716 OutCC
= changeIntCCToAArch64CC(CC
);
1718 assert(LHS
.getValueType().isFloatingPoint());
1719 AArch64CC::CondCode ExtraCC
;
1720 changeFPCCToANDAArch64CC(CC
, OutCC
, ExtraCC
);
1721 // Some floating point conditions can't be tested with a single condition
1722 // code. Construct an additional comparison in this case.
1723 if (ExtraCC
!= AArch64CC::AL
) {
1725 if (!CCOp
.getNode())
1726 ExtraCmp
= emitComparison(LHS
, RHS
, CC
, DL
, DAG
);
1728 ExtraCmp
= emitConditionalComparison(LHS
, RHS
, CC
, CCOp
, Predicate
,
1731 Predicate
= ExtraCC
;
1735 // Produce a normal comparison if we are first in the chain
1737 return emitComparison(LHS
, RHS
, CC
, DL
, DAG
);
1738 // Otherwise produce a ccmp.
1739 return emitConditionalComparison(LHS
, RHS
, CC
, CCOp
, Predicate
, OutCC
, DL
,
1742 assert(Val
->hasOneUse() && "Valid conjunction/disjunction tree");
1744 bool IsOR
= Opcode
== ISD::OR
;
1746 SDValue LHS
= Val
->getOperand(0);
1749 bool ValidL
= canEmitConjunction(LHS
, CanNegateL
, MustBeFirstL
, IsOR
);
1750 assert(ValidL
&& "Valid conjunction/disjunction tree");
1753 SDValue RHS
= Val
->getOperand(1);
1756 bool ValidR
= canEmitConjunction(RHS
, CanNegateR
, MustBeFirstR
, IsOR
);
1757 assert(ValidR
&& "Valid conjunction/disjunction tree");
1760 // Swap sub-tree that must come first to the right side.
1762 assert(!MustBeFirstR
&& "Valid conjunction/disjunction tree");
1763 std::swap(LHS
, RHS
);
1764 std::swap(CanNegateL
, CanNegateR
);
1765 std::swap(MustBeFirstL
, MustBeFirstR
);
1771 bool NegateAfterAll
;
1772 if (Opcode
== ISD::OR
) {
1773 // Swap the sub-tree that we can negate naturally to the left.
1775 assert(CanNegateR
&& "at least one side must be negatable");
1776 assert(!MustBeFirstR
&& "invalid conjunction/disjunction tree");
1778 std::swap(LHS
, RHS
);
1780 NegateAfterR
= true;
1782 // Negate the left sub-tree if possible, otherwise negate the result.
1783 NegateR
= CanNegateR
;
1784 NegateAfterR
= !CanNegateR
;
1787 NegateAfterAll
= !Negate
;
1789 assert(Opcode
== ISD::AND
&& "Valid conjunction/disjunction tree");
1790 assert(!Negate
&& "Valid conjunction/disjunction tree");
1794 NegateAfterR
= false;
1795 NegateAfterAll
= false;
1799 AArch64CC::CondCode RHSCC
;
1800 SDValue CmpR
= emitConjunctionRec(DAG
, RHS
, RHSCC
, NegateR
, CCOp
, Predicate
);
1802 RHSCC
= AArch64CC::getInvertedCondCode(RHSCC
);
1803 SDValue CmpL
= emitConjunctionRec(DAG
, LHS
, OutCC
, NegateL
, CmpR
, RHSCC
);
1805 OutCC
= AArch64CC::getInvertedCondCode(OutCC
);
1809 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1810 /// In some cases this is even possible with OR operations in the expression.
1811 /// See \ref AArch64CCMP.
1812 /// \see emitConjunctionRec().
1813 static SDValue
emitConjunction(SelectionDAG
&DAG
, SDValue Val
,
1814 AArch64CC::CondCode
&OutCC
) {
1815 bool DummyCanNegate
;
1816 bool DummyMustBeFirst
;
1817 if (!canEmitConjunction(Val
, DummyCanNegate
, DummyMustBeFirst
, false))
1820 return emitConjunctionRec(DAG
, Val
, OutCC
, false, SDValue(), AArch64CC::AL
);
1825 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1826 /// extension operations.
1827 static unsigned getCmpOperandFoldingProfit(SDValue Op
) {
1828 auto isSupportedExtend
= [&](SDValue V
) {
1829 if (V
.getOpcode() == ISD::SIGN_EXTEND_INREG
)
1832 if (V
.getOpcode() == ISD::AND
)
1833 if (ConstantSDNode
*MaskCst
= dyn_cast
<ConstantSDNode
>(V
.getOperand(1))) {
1834 uint64_t Mask
= MaskCst
->getZExtValue();
1835 return (Mask
== 0xFF || Mask
== 0xFFFF || Mask
== 0xFFFFFFFF);
1841 if (!Op
.hasOneUse())
1844 if (isSupportedExtend(Op
))
1847 unsigned Opc
= Op
.getOpcode();
1848 if (Opc
== ISD::SHL
|| Opc
== ISD::SRL
|| Opc
== ISD::SRA
)
1849 if (ConstantSDNode
*ShiftCst
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))) {
1850 uint64_t Shift
= ShiftCst
->getZExtValue();
1851 if (isSupportedExtend(Op
.getOperand(0)))
1852 return (Shift
<= 4) ? 2 : 1;
1853 EVT VT
= Op
.getValueType();
1854 if ((VT
== MVT::i32
&& Shift
<= 31) || (VT
== MVT::i64
&& Shift
<= 63))
1861 static SDValue
getAArch64Cmp(SDValue LHS
, SDValue RHS
, ISD::CondCode CC
,
1862 SDValue
&AArch64cc
, SelectionDAG
&DAG
,
1864 if (ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(RHS
.getNode())) {
1865 EVT VT
= RHS
.getValueType();
1866 uint64_t C
= RHSC
->getZExtValue();
1867 if (!isLegalArithImmed(C
)) {
1868 // Constant does not fit, try adjusting it by one?
1874 if ((VT
== MVT::i32
&& C
!= 0x80000000 &&
1875 isLegalArithImmed((uint32_t)(C
- 1))) ||
1876 (VT
== MVT::i64
&& C
!= 0x80000000ULL
&&
1877 isLegalArithImmed(C
- 1ULL))) {
1878 CC
= (CC
== ISD::SETLT
) ? ISD::SETLE
: ISD::SETGT
;
1879 C
= (VT
== MVT::i32
) ? (uint32_t)(C
- 1) : C
- 1;
1880 RHS
= DAG
.getConstant(C
, dl
, VT
);
1885 if ((VT
== MVT::i32
&& C
!= 0 &&
1886 isLegalArithImmed((uint32_t)(C
- 1))) ||
1887 (VT
== MVT::i64
&& C
!= 0ULL && isLegalArithImmed(C
- 1ULL))) {
1888 CC
= (CC
== ISD::SETULT
) ? ISD::SETULE
: ISD::SETUGT
;
1889 C
= (VT
== MVT::i32
) ? (uint32_t)(C
- 1) : C
- 1;
1890 RHS
= DAG
.getConstant(C
, dl
, VT
);
1895 if ((VT
== MVT::i32
&& C
!= INT32_MAX
&&
1896 isLegalArithImmed((uint32_t)(C
+ 1))) ||
1897 (VT
== MVT::i64
&& C
!= INT64_MAX
&&
1898 isLegalArithImmed(C
+ 1ULL))) {
1899 CC
= (CC
== ISD::SETLE
) ? ISD::SETLT
: ISD::SETGE
;
1900 C
= (VT
== MVT::i32
) ? (uint32_t)(C
+ 1) : C
+ 1;
1901 RHS
= DAG
.getConstant(C
, dl
, VT
);
1906 if ((VT
== MVT::i32
&& C
!= UINT32_MAX
&&
1907 isLegalArithImmed((uint32_t)(C
+ 1))) ||
1908 (VT
== MVT::i64
&& C
!= UINT64_MAX
&&
1909 isLegalArithImmed(C
+ 1ULL))) {
1910 CC
= (CC
== ISD::SETULE
) ? ISD::SETULT
: ISD::SETUGE
;
1911 C
= (VT
== MVT::i32
) ? (uint32_t)(C
+ 1) : C
+ 1;
1912 RHS
= DAG
.getConstant(C
, dl
, VT
);
1919 // Comparisons are canonicalized so that the RHS operand is simpler than the
1920 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1921 // can fold some shift+extend operations on the RHS operand, so swap the
1922 // operands if that can be done.
1927 // can be turned into:
1928 // cmp w12, w11, lsl #1
1929 if (!isa
<ConstantSDNode
>(RHS
) ||
1930 !isLegalArithImmed(cast
<ConstantSDNode
>(RHS
)->getZExtValue())) {
1931 SDValue TheLHS
= isCMN(LHS
, CC
) ? LHS
.getOperand(1) : LHS
;
1933 if (getCmpOperandFoldingProfit(TheLHS
) > getCmpOperandFoldingProfit(RHS
)) {
1934 std::swap(LHS
, RHS
);
1935 CC
= ISD::getSetCCSwappedOperands(CC
);
1940 AArch64CC::CondCode AArch64CC
;
1941 if ((CC
== ISD::SETEQ
|| CC
== ISD::SETNE
) && isa
<ConstantSDNode
>(RHS
)) {
1942 const ConstantSDNode
*RHSC
= cast
<ConstantSDNode
>(RHS
);
1944 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1945 // For the i8 operand, the largest immediate is 255, so this can be easily
1946 // encoded in the compare instruction. For the i16 operand, however, the
1947 // largest immediate cannot be encoded in the compare.
1948 // Therefore, use a sign extending load and cmn to avoid materializing the
1949 // -1 constant. For example,
1951 // ldrh w0, [x0, #0]
1954 // ldrsh w0, [x0, #0]
1956 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1957 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1958 // ensure both the LHS and RHS are truly zero extended and to make sure the
1959 // transformation is profitable.
1960 if ((RHSC
->getZExtValue() >> 16 == 0) && isa
<LoadSDNode
>(LHS
) &&
1961 cast
<LoadSDNode
>(LHS
)->getExtensionType() == ISD::ZEXTLOAD
&&
1962 cast
<LoadSDNode
>(LHS
)->getMemoryVT() == MVT::i16
&&
1963 LHS
.getNode()->hasNUsesOfValue(1, 0)) {
1964 int16_t ValueofRHS
= cast
<ConstantSDNode
>(RHS
)->getZExtValue();
1965 if (ValueofRHS
< 0 && isLegalArithImmed(-ValueofRHS
)) {
1967 DAG
.getNode(ISD::SIGN_EXTEND_INREG
, dl
, LHS
.getValueType(), LHS
,
1968 DAG
.getValueType(MVT::i16
));
1969 Cmp
= emitComparison(SExt
, DAG
.getConstant(ValueofRHS
, dl
,
1970 RHS
.getValueType()),
1972 AArch64CC
= changeIntCCToAArch64CC(CC
);
1976 if (!Cmp
&& (RHSC
->isNullValue() || RHSC
->isOne())) {
1977 if ((Cmp
= emitConjunction(DAG
, LHS
, AArch64CC
))) {
1978 if ((CC
== ISD::SETNE
) ^ RHSC
->isNullValue())
1979 AArch64CC
= AArch64CC::getInvertedCondCode(AArch64CC
);
1985 Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
1986 AArch64CC
= changeIntCCToAArch64CC(CC
);
1988 AArch64cc
= DAG
.getConstant(AArch64CC
, dl
, MVT_CC
);
1992 static std::pair
<SDValue
, SDValue
>
1993 getAArch64XALUOOp(AArch64CC::CondCode
&CC
, SDValue Op
, SelectionDAG
&DAG
) {
1994 assert((Op
.getValueType() == MVT::i32
|| Op
.getValueType() == MVT::i64
) &&
1995 "Unsupported value type");
1996 SDValue Value
, Overflow
;
1998 SDValue LHS
= Op
.getOperand(0);
1999 SDValue RHS
= Op
.getOperand(1);
2001 switch (Op
.getOpcode()) {
2003 llvm_unreachable("Unknown overflow instruction!");
2005 Opc
= AArch64ISD::ADDS
;
2009 Opc
= AArch64ISD::ADDS
;
2013 Opc
= AArch64ISD::SUBS
;
2017 Opc
= AArch64ISD::SUBS
;
2020 // Multiply needs a little bit extra work.
2024 bool IsSigned
= Op
.getOpcode() == ISD::SMULO
;
2025 if (Op
.getValueType() == MVT::i32
) {
2026 unsigned ExtendOpc
= IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
2027 // For a 32 bit multiply with overflow check we want the instruction
2028 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2029 // need to generate the following pattern:
2030 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2031 LHS
= DAG
.getNode(ExtendOpc
, DL
, MVT::i64
, LHS
);
2032 RHS
= DAG
.getNode(ExtendOpc
, DL
, MVT::i64
, RHS
);
2033 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, MVT::i64
, LHS
, RHS
);
2034 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, Mul
,
2035 DAG
.getConstant(0, DL
, MVT::i64
));
2036 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2037 // operation. We need to clear out the upper 32 bits, because we used a
2038 // widening multiply that wrote all 64 bits. In the end this should be a
2040 Value
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i32
, Add
);
2042 // The signed overflow check requires more than just a simple check for
2043 // any bit set in the upper 32 bits of the result. These bits could be
2044 // just the sign bits of a negative number. To perform the overflow
2045 // check we have to arithmetic shift right the 32nd bit of the result by
2046 // 31 bits. Then we compare the result to the upper 32 bits.
2047 SDValue UpperBits
= DAG
.getNode(ISD::SRL
, DL
, MVT::i64
, Add
,
2048 DAG
.getConstant(32, DL
, MVT::i64
));
2049 UpperBits
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i32
, UpperBits
);
2050 SDValue LowerBits
= DAG
.getNode(ISD::SRA
, DL
, MVT::i32
, Value
,
2051 DAG
.getConstant(31, DL
, MVT::i64
));
2052 // It is important that LowerBits is last, otherwise the arithmetic
2053 // shift will not be folded into the compare (SUBS).
2054 SDVTList VTs
= DAG
.getVTList(MVT::i32
, MVT::i32
);
2055 Overflow
= DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
, UpperBits
, LowerBits
)
2058 // The overflow check for unsigned multiply is easy. We only need to
2059 // check if any of the upper 32 bits are set. This can be done with a
2060 // CMP (shifted register). For that we need to generate the following
2062 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2063 SDValue UpperBits
= DAG
.getNode(ISD::SRL
, DL
, MVT::i64
, Mul
,
2064 DAG
.getConstant(32, DL
, MVT::i64
));
2065 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2067 DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
,
2068 DAG
.getConstant(0, DL
, MVT::i64
),
2069 UpperBits
).getValue(1);
2073 assert(Op
.getValueType() == MVT::i64
&& "Expected an i64 value type");
2074 // For the 64 bit multiply
2075 Value
= DAG
.getNode(ISD::MUL
, DL
, MVT::i64
, LHS
, RHS
);
2077 SDValue UpperBits
= DAG
.getNode(ISD::MULHS
, DL
, MVT::i64
, LHS
, RHS
);
2078 SDValue LowerBits
= DAG
.getNode(ISD::SRA
, DL
, MVT::i64
, Value
,
2079 DAG
.getConstant(63, DL
, MVT::i64
));
2080 // It is important that LowerBits is last, otherwise the arithmetic
2081 // shift will not be folded into the compare (SUBS).
2082 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2083 Overflow
= DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
, UpperBits
, LowerBits
)
2086 SDValue UpperBits
= DAG
.getNode(ISD::MULHU
, DL
, MVT::i64
, LHS
, RHS
);
2087 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2089 DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
,
2090 DAG
.getConstant(0, DL
, MVT::i64
),
2091 UpperBits
).getValue(1);
2098 SDVTList VTs
= DAG
.getVTList(Op
->getValueType(0), MVT::i32
);
2100 // Emit the AArch64 operation with overflow check.
2101 Value
= DAG
.getNode(Opc
, DL
, VTs
, LHS
, RHS
);
2102 Overflow
= Value
.getValue(1);
2104 return std::make_pair(Value
, Overflow
);
2107 SDValue
AArch64TargetLowering::LowerF128Call(SDValue Op
, SelectionDAG
&DAG
,
2108 RTLIB::Libcall Call
) const {
2109 SmallVector
<SDValue
, 2> Ops(Op
->op_begin(), Op
->op_end());
2110 return makeLibCall(DAG
, Call
, MVT::f128
, Ops
, false, SDLoc(Op
)).first
;
2113 // Returns true if the given Op is the overflow flag result of an overflow
2114 // intrinsic operation.
2115 static bool isOverflowIntrOpRes(SDValue Op
) {
2116 unsigned Opc
= Op
.getOpcode();
2117 return (Op
.getResNo() == 1 &&
2118 (Opc
== ISD::SADDO
|| Opc
== ISD::UADDO
|| Opc
== ISD::SSUBO
||
2119 Opc
== ISD::USUBO
|| Opc
== ISD::SMULO
|| Opc
== ISD::UMULO
));
2122 static SDValue
LowerXOR(SDValue Op
, SelectionDAG
&DAG
) {
2123 SDValue Sel
= Op
.getOperand(0);
2124 SDValue Other
= Op
.getOperand(1);
2127 // If the operand is an overflow checking operation, invert the condition
2128 // code and kill the Not operation. I.e., transform:
2129 // (xor (overflow_op_bool, 1))
2131 // (csel 1, 0, invert(cc), overflow_op_bool)
2132 // ... which later gets transformed to just a cset instruction with an
2133 // inverted condition code, rather than a cset + eor sequence.
2134 if (isOneConstant(Other
) && isOverflowIntrOpRes(Sel
)) {
2135 // Only lower legal XALUO ops.
2136 if (!DAG
.getTargetLoweringInfo().isTypeLegal(Sel
->getValueType(0)))
2139 SDValue TVal
= DAG
.getConstant(1, dl
, MVT::i32
);
2140 SDValue FVal
= DAG
.getConstant(0, dl
, MVT::i32
);
2141 AArch64CC::CondCode CC
;
2142 SDValue Value
, Overflow
;
2143 std::tie(Value
, Overflow
) = getAArch64XALUOOp(CC
, Sel
.getValue(0), DAG
);
2144 SDValue CCVal
= DAG
.getConstant(getInvertedCondCode(CC
), dl
, MVT::i32
);
2145 return DAG
.getNode(AArch64ISD::CSEL
, dl
, Op
.getValueType(), TVal
, FVal
,
2148 // If neither operand is a SELECT_CC, give up.
2149 if (Sel
.getOpcode() != ISD::SELECT_CC
)
2150 std::swap(Sel
, Other
);
2151 if (Sel
.getOpcode() != ISD::SELECT_CC
)
2154 // The folding we want to perform is:
2155 // (xor x, (select_cc a, b, cc, 0, -1) )
2157 // (csel x, (xor x, -1), cc ...)
2159 // The latter will get matched to a CSINV instruction.
2161 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Sel
.getOperand(4))->get();
2162 SDValue LHS
= Sel
.getOperand(0);
2163 SDValue RHS
= Sel
.getOperand(1);
2164 SDValue TVal
= Sel
.getOperand(2);
2165 SDValue FVal
= Sel
.getOperand(3);
2167 // FIXME: This could be generalized to non-integer comparisons.
2168 if (LHS
.getValueType() != MVT::i32
&& LHS
.getValueType() != MVT::i64
)
2171 ConstantSDNode
*CFVal
= dyn_cast
<ConstantSDNode
>(FVal
);
2172 ConstantSDNode
*CTVal
= dyn_cast
<ConstantSDNode
>(TVal
);
2174 // The values aren't constants, this isn't the pattern we're looking for.
2175 if (!CFVal
|| !CTVal
)
2178 // We can commute the SELECT_CC by inverting the condition. This
2179 // might be needed to make this fit into a CSINV pattern.
2180 if (CTVal
->isAllOnesValue() && CFVal
->isNullValue()) {
2181 std::swap(TVal
, FVal
);
2182 std::swap(CTVal
, CFVal
);
2183 CC
= ISD::getSetCCInverse(CC
, true);
2186 // If the constants line up, perform the transform!
2187 if (CTVal
->isNullValue() && CFVal
->isAllOnesValue()) {
2189 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
2192 TVal
= DAG
.getNode(ISD::XOR
, dl
, Other
.getValueType(), Other
,
2193 DAG
.getConstant(-1ULL, dl
, Other
.getValueType()));
2195 return DAG
.getNode(AArch64ISD::CSEL
, dl
, Sel
.getValueType(), FVal
, TVal
,
2202 static SDValue
LowerADDC_ADDE_SUBC_SUBE(SDValue Op
, SelectionDAG
&DAG
) {
2203 EVT VT
= Op
.getValueType();
2205 // Let legalize expand this if it isn't a legal type yet.
2206 if (!DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
2209 SDVTList VTs
= DAG
.getVTList(VT
, MVT::i32
);
2212 bool ExtraOp
= false;
2213 switch (Op
.getOpcode()) {
2215 llvm_unreachable("Invalid code");
2217 Opc
= AArch64ISD::ADDS
;
2220 Opc
= AArch64ISD::SUBS
;
2223 Opc
= AArch64ISD::ADCS
;
2227 Opc
= AArch64ISD::SBCS
;
2233 return DAG
.getNode(Opc
, SDLoc(Op
), VTs
, Op
.getOperand(0), Op
.getOperand(1));
2234 return DAG
.getNode(Opc
, SDLoc(Op
), VTs
, Op
.getOperand(0), Op
.getOperand(1),
2238 static SDValue
LowerXALUO(SDValue Op
, SelectionDAG
&DAG
) {
2239 // Let legalize expand this if it isn't a legal type yet.
2240 if (!DAG
.getTargetLoweringInfo().isTypeLegal(Op
.getValueType()))
2244 AArch64CC::CondCode CC
;
2245 // The actual operation that sets the overflow or carry flag.
2246 SDValue Value
, Overflow
;
2247 std::tie(Value
, Overflow
) = getAArch64XALUOOp(CC
, Op
, DAG
);
2249 // We use 0 and 1 as false and true values.
2250 SDValue TVal
= DAG
.getConstant(1, dl
, MVT::i32
);
2251 SDValue FVal
= DAG
.getConstant(0, dl
, MVT::i32
);
2253 // We use an inverted condition, because the conditional select is inverted
2254 // too. This will allow it to be selected to a single instruction:
2255 // CSINC Wd, WZR, WZR, invert(cond).
2256 SDValue CCVal
= DAG
.getConstant(getInvertedCondCode(CC
), dl
, MVT::i32
);
2257 Overflow
= DAG
.getNode(AArch64ISD::CSEL
, dl
, MVT::i32
, FVal
, TVal
,
2260 SDVTList VTs
= DAG
.getVTList(Op
.getValueType(), MVT::i32
);
2261 return DAG
.getNode(ISD::MERGE_VALUES
, dl
, VTs
, Value
, Overflow
);
2264 // Prefetch operands are:
2265 // 1: Address to prefetch
2267 // 3: int locality (0 = no locality ... 3 = extreme locality)
2268 // 4: bool isDataCache
2269 static SDValue
LowerPREFETCH(SDValue Op
, SelectionDAG
&DAG
) {
2271 unsigned IsWrite
= cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue();
2272 unsigned Locality
= cast
<ConstantSDNode
>(Op
.getOperand(3))->getZExtValue();
2273 unsigned IsData
= cast
<ConstantSDNode
>(Op
.getOperand(4))->getZExtValue();
2275 bool IsStream
= !Locality
;
2276 // When the locality number is set
2278 // The front-end should have filtered out the out-of-range values
2279 assert(Locality
<= 3 && "Prefetch locality out-of-range");
2280 // The locality degree is the opposite of the cache speed.
2281 // Put the number the other way around.
2282 // The encoding starts at 0 for level 1
2283 Locality
= 3 - Locality
;
2286 // built the mask value encoding the expected behavior.
2287 unsigned PrfOp
= (IsWrite
<< 4) | // Load/Store bit
2288 (!IsData
<< 3) | // IsDataCache bit
2289 (Locality
<< 1) | // Cache level bits
2290 (unsigned)IsStream
; // Stream bit
2291 return DAG
.getNode(AArch64ISD::PREFETCH
, DL
, MVT::Other
, Op
.getOperand(0),
2292 DAG
.getConstant(PrfOp
, DL
, MVT::i32
), Op
.getOperand(1));
2295 SDValue
AArch64TargetLowering::LowerFP_EXTEND(SDValue Op
,
2296 SelectionDAG
&DAG
) const {
2297 assert(Op
.getValueType() == MVT::f128
&& "Unexpected lowering");
2300 LC
= RTLIB::getFPEXT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2302 return LowerF128Call(Op
, DAG
, LC
);
2305 SDValue
AArch64TargetLowering::LowerFP_ROUND(SDValue Op
,
2306 SelectionDAG
&DAG
) const {
2307 if (Op
.getOperand(0).getValueType() != MVT::f128
) {
2308 // It's legal except when f128 is involved
2313 LC
= RTLIB::getFPROUND(Op
.getOperand(0).getValueType(), Op
.getValueType());
2315 // FP_ROUND node has a second operand indicating whether it is known to be
2316 // precise. That doesn't take part in the LibCall so we can't directly use
2318 SDValue SrcVal
= Op
.getOperand(0);
2319 return makeLibCall(DAG
, LC
, Op
.getValueType(), SrcVal
, /*isSigned*/ false,
2323 static SDValue
LowerVectorFP_TO_INT(SDValue Op
, SelectionDAG
&DAG
) {
2324 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2325 // Any additional optimization in this function should be recorded
2326 // in the cost tables.
2327 EVT InVT
= Op
.getOperand(0).getValueType();
2328 EVT VT
= Op
.getValueType();
2329 unsigned NumElts
= InVT
.getVectorNumElements();
2331 // f16 vectors are promoted to f32 before a conversion.
2332 if (InVT
.getVectorElementType() == MVT::f16
) {
2333 MVT NewVT
= MVT::getVectorVT(MVT::f32
, NumElts
);
2336 Op
.getOpcode(), dl
, Op
.getValueType(),
2337 DAG
.getNode(ISD::FP_EXTEND
, dl
, NewVT
, Op
.getOperand(0)));
2340 if (VT
.getSizeInBits() < InVT
.getSizeInBits()) {
2343 DAG
.getNode(Op
.getOpcode(), dl
, InVT
.changeVectorElementTypeToInteger(),
2345 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Cv
);
2348 if (VT
.getSizeInBits() > InVT
.getSizeInBits()) {
2351 MVT::getVectorVT(MVT::getFloatingPointVT(VT
.getScalarSizeInBits()),
2352 VT
.getVectorNumElements());
2353 SDValue Ext
= DAG
.getNode(ISD::FP_EXTEND
, dl
, ExtVT
, Op
.getOperand(0));
2354 return DAG
.getNode(Op
.getOpcode(), dl
, VT
, Ext
);
2357 // Type changing conversions are illegal.
2361 SDValue
AArch64TargetLowering::LowerFP_TO_INT(SDValue Op
,
2362 SelectionDAG
&DAG
) const {
2363 if (Op
.getOperand(0).getValueType().isVector())
2364 return LowerVectorFP_TO_INT(Op
, DAG
);
2366 // f16 conversions are promoted to f32 when full fp16 is not supported.
2367 if (Op
.getOperand(0).getValueType() == MVT::f16
&&
2368 !Subtarget
->hasFullFP16()) {
2371 Op
.getOpcode(), dl
, Op
.getValueType(),
2372 DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, Op
.getOperand(0)));
2375 if (Op
.getOperand(0).getValueType() != MVT::f128
) {
2376 // It's legal except when f128 is involved
2381 if (Op
.getOpcode() == ISD::FP_TO_SINT
)
2382 LC
= RTLIB::getFPTOSINT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2384 LC
= RTLIB::getFPTOUINT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2386 SmallVector
<SDValue
, 2> Ops(Op
->op_begin(), Op
->op_end());
2387 return makeLibCall(DAG
, LC
, Op
.getValueType(), Ops
, false, SDLoc(Op
)).first
;
2390 static SDValue
LowerVectorINT_TO_FP(SDValue Op
, SelectionDAG
&DAG
) {
2391 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2392 // Any additional optimization in this function should be recorded
2393 // in the cost tables.
2394 EVT VT
= Op
.getValueType();
2396 SDValue In
= Op
.getOperand(0);
2397 EVT InVT
= In
.getValueType();
2399 if (VT
.getSizeInBits() < InVT
.getSizeInBits()) {
2401 MVT::getVectorVT(MVT::getFloatingPointVT(InVT
.getScalarSizeInBits()),
2402 InVT
.getVectorNumElements());
2403 In
= DAG
.getNode(Op
.getOpcode(), dl
, CastVT
, In
);
2404 return DAG
.getNode(ISD::FP_ROUND
, dl
, VT
, In
, DAG
.getIntPtrConstant(0, dl
));
2407 if (VT
.getSizeInBits() > InVT
.getSizeInBits()) {
2409 Op
.getOpcode() == ISD::SINT_TO_FP
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
2410 EVT CastVT
= VT
.changeVectorElementTypeToInteger();
2411 In
= DAG
.getNode(CastOpc
, dl
, CastVT
, In
);
2412 return DAG
.getNode(Op
.getOpcode(), dl
, VT
, In
);
2418 SDValue
AArch64TargetLowering::LowerINT_TO_FP(SDValue Op
,
2419 SelectionDAG
&DAG
) const {
2420 if (Op
.getValueType().isVector())
2421 return LowerVectorINT_TO_FP(Op
, DAG
);
2423 // f16 conversions are promoted to f32 when full fp16 is not supported.
2424 if (Op
.getValueType() == MVT::f16
&&
2425 !Subtarget
->hasFullFP16()) {
2428 ISD::FP_ROUND
, dl
, MVT::f16
,
2429 DAG
.getNode(Op
.getOpcode(), dl
, MVT::f32
, Op
.getOperand(0)),
2430 DAG
.getIntPtrConstant(0, dl
));
2433 // i128 conversions are libcalls.
2434 if (Op
.getOperand(0).getValueType() == MVT::i128
)
2437 // Other conversions are legal, unless it's to the completely software-based
2439 if (Op
.getValueType() != MVT::f128
)
2443 if (Op
.getOpcode() == ISD::SINT_TO_FP
)
2444 LC
= RTLIB::getSINTTOFP(Op
.getOperand(0).getValueType(), Op
.getValueType());
2446 LC
= RTLIB::getUINTTOFP(Op
.getOperand(0).getValueType(), Op
.getValueType());
2448 return LowerF128Call(Op
, DAG
, LC
);
2451 SDValue
AArch64TargetLowering::LowerFSINCOS(SDValue Op
,
2452 SelectionDAG
&DAG
) const {
2453 // For iOS, we want to call an alternative entry point: __sincos_stret,
2454 // which returns the values in two S / D registers.
2456 SDValue Arg
= Op
.getOperand(0);
2457 EVT ArgVT
= Arg
.getValueType();
2458 Type
*ArgTy
= ArgVT
.getTypeForEVT(*DAG
.getContext());
2465 Entry
.IsSExt
= false;
2466 Entry
.IsZExt
= false;
2467 Args
.push_back(Entry
);
2469 RTLIB::Libcall LC
= ArgVT
== MVT::f64
? RTLIB::SINCOS_STRET_F64
2470 : RTLIB::SINCOS_STRET_F32
;
2471 const char *LibcallName
= getLibcallName(LC
);
2473 DAG
.getExternalSymbol(LibcallName
, getPointerTy(DAG
.getDataLayout()));
2475 StructType
*RetTy
= StructType::get(ArgTy
, ArgTy
);
2476 TargetLowering::CallLoweringInfo
CLI(DAG
);
2478 .setChain(DAG
.getEntryNode())
2479 .setLibCallee(CallingConv::Fast
, RetTy
, Callee
, std::move(Args
));
2481 std::pair
<SDValue
, SDValue
> CallResult
= LowerCallTo(CLI
);
2482 return CallResult
.first
;
2485 static SDValue
LowerBITCAST(SDValue Op
, SelectionDAG
&DAG
) {
2486 if (Op
.getValueType() != MVT::f16
)
2489 assert(Op
.getOperand(0).getValueType() == MVT::i16
);
2492 Op
= DAG
.getNode(ISD::ANY_EXTEND
, DL
, MVT::i32
, Op
.getOperand(0));
2493 Op
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::f32
, Op
);
2495 DAG
.getMachineNode(TargetOpcode::EXTRACT_SUBREG
, DL
, MVT::f16
, Op
,
2496 DAG
.getTargetConstant(AArch64::hsub
, DL
, MVT::i32
)),
2500 static EVT
getExtensionTo64Bits(const EVT
&OrigVT
) {
2501 if (OrigVT
.getSizeInBits() >= 64)
2504 assert(OrigVT
.isSimple() && "Expecting a simple value type");
2506 MVT::SimpleValueType OrigSimpleTy
= OrigVT
.getSimpleVT().SimpleTy
;
2507 switch (OrigSimpleTy
) {
2508 default: llvm_unreachable("Unexpected Vector Type");
2517 static SDValue
addRequiredExtensionForVectorMULL(SDValue N
, SelectionDAG
&DAG
,
2520 unsigned ExtOpcode
) {
2521 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2522 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2523 // 64-bits we need to insert a new extension so that it will be 64-bits.
2524 assert(ExtTy
.is128BitVector() && "Unexpected extension size");
2525 if (OrigTy
.getSizeInBits() >= 64)
2528 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2529 EVT NewVT
= getExtensionTo64Bits(OrigTy
);
2531 return DAG
.getNode(ExtOpcode
, SDLoc(N
), NewVT
, N
);
2534 static bool isExtendedBUILD_VECTOR(SDNode
*N
, SelectionDAG
&DAG
,
2536 EVT VT
= N
->getValueType(0);
2538 if (N
->getOpcode() != ISD::BUILD_VECTOR
)
2541 for (const SDValue
&Elt
: N
->op_values()) {
2542 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Elt
)) {
2543 unsigned EltSize
= VT
.getScalarSizeInBits();
2544 unsigned HalfSize
= EltSize
/ 2;
2546 if (!isIntN(HalfSize
, C
->getSExtValue()))
2549 if (!isUIntN(HalfSize
, C
->getZExtValue()))
2560 static SDValue
skipExtensionForVectorMULL(SDNode
*N
, SelectionDAG
&DAG
) {
2561 if (N
->getOpcode() == ISD::SIGN_EXTEND
|| N
->getOpcode() == ISD::ZERO_EXTEND
)
2562 return addRequiredExtensionForVectorMULL(N
->getOperand(0), DAG
,
2563 N
->getOperand(0)->getValueType(0),
2567 assert(N
->getOpcode() == ISD::BUILD_VECTOR
&& "expected BUILD_VECTOR");
2568 EVT VT
= N
->getValueType(0);
2570 unsigned EltSize
= VT
.getScalarSizeInBits() / 2;
2571 unsigned NumElts
= VT
.getVectorNumElements();
2572 MVT TruncVT
= MVT::getIntegerVT(EltSize
);
2573 SmallVector
<SDValue
, 8> Ops
;
2574 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2575 ConstantSDNode
*C
= cast
<ConstantSDNode
>(N
->getOperand(i
));
2576 const APInt
&CInt
= C
->getAPIntValue();
2577 // Element types smaller than 32 bits are not legal, so use i32 elements.
2578 // The values are implicitly truncated so sext vs. zext doesn't matter.
2579 Ops
.push_back(DAG
.getConstant(CInt
.zextOrTrunc(32), dl
, MVT::i32
));
2581 return DAG
.getBuildVector(MVT::getVectorVT(TruncVT
, NumElts
), dl
, Ops
);
2584 static bool isSignExtended(SDNode
*N
, SelectionDAG
&DAG
) {
2585 return N
->getOpcode() == ISD::SIGN_EXTEND
||
2586 isExtendedBUILD_VECTOR(N
, DAG
, true);
2589 static bool isZeroExtended(SDNode
*N
, SelectionDAG
&DAG
) {
2590 return N
->getOpcode() == ISD::ZERO_EXTEND
||
2591 isExtendedBUILD_VECTOR(N
, DAG
, false);
2594 static bool isAddSubSExt(SDNode
*N
, SelectionDAG
&DAG
) {
2595 unsigned Opcode
= N
->getOpcode();
2596 if (Opcode
== ISD::ADD
|| Opcode
== ISD::SUB
) {
2597 SDNode
*N0
= N
->getOperand(0).getNode();
2598 SDNode
*N1
= N
->getOperand(1).getNode();
2599 return N0
->hasOneUse() && N1
->hasOneUse() &&
2600 isSignExtended(N0
, DAG
) && isSignExtended(N1
, DAG
);
2605 static bool isAddSubZExt(SDNode
*N
, SelectionDAG
&DAG
) {
2606 unsigned Opcode
= N
->getOpcode();
2607 if (Opcode
== ISD::ADD
|| Opcode
== ISD::SUB
) {
2608 SDNode
*N0
= N
->getOperand(0).getNode();
2609 SDNode
*N1
= N
->getOperand(1).getNode();
2610 return N0
->hasOneUse() && N1
->hasOneUse() &&
2611 isZeroExtended(N0
, DAG
) && isZeroExtended(N1
, DAG
);
2616 SDValue
AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op
,
2617 SelectionDAG
&DAG
) const {
2618 // The rounding mode is in bits 23:22 of the FPSCR.
2619 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2620 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2621 // so that the shift + and get folded into a bitfield extract.
2624 SDValue FPCR_64
= DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, dl
, MVT::i64
,
2625 DAG
.getConstant(Intrinsic::aarch64_get_fpcr
, dl
,
2627 SDValue FPCR_32
= DAG
.getNode(ISD::TRUNCATE
, dl
, MVT::i32
, FPCR_64
);
2628 SDValue FltRounds
= DAG
.getNode(ISD::ADD
, dl
, MVT::i32
, FPCR_32
,
2629 DAG
.getConstant(1U << 22, dl
, MVT::i32
));
2630 SDValue RMODE
= DAG
.getNode(ISD::SRL
, dl
, MVT::i32
, FltRounds
,
2631 DAG
.getConstant(22, dl
, MVT::i32
));
2632 return DAG
.getNode(ISD::AND
, dl
, MVT::i32
, RMODE
,
2633 DAG
.getConstant(3, dl
, MVT::i32
));
2636 static SDValue
LowerMUL(SDValue Op
, SelectionDAG
&DAG
) {
2637 // Multiplications are only custom-lowered for 128-bit vectors so that
2638 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2639 EVT VT
= Op
.getValueType();
2640 assert(VT
.is128BitVector() && VT
.isInteger() &&
2641 "unexpected type for custom-lowering ISD::MUL");
2642 SDNode
*N0
= Op
.getOperand(0).getNode();
2643 SDNode
*N1
= Op
.getOperand(1).getNode();
2644 unsigned NewOpc
= 0;
2646 bool isN0SExt
= isSignExtended(N0
, DAG
);
2647 bool isN1SExt
= isSignExtended(N1
, DAG
);
2648 if (isN0SExt
&& isN1SExt
)
2649 NewOpc
= AArch64ISD::SMULL
;
2651 bool isN0ZExt
= isZeroExtended(N0
, DAG
);
2652 bool isN1ZExt
= isZeroExtended(N1
, DAG
);
2653 if (isN0ZExt
&& isN1ZExt
)
2654 NewOpc
= AArch64ISD::UMULL
;
2655 else if (isN1SExt
|| isN1ZExt
) {
2656 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2657 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2658 if (isN1SExt
&& isAddSubSExt(N0
, DAG
)) {
2659 NewOpc
= AArch64ISD::SMULL
;
2661 } else if (isN1ZExt
&& isAddSubZExt(N0
, DAG
)) {
2662 NewOpc
= AArch64ISD::UMULL
;
2664 } else if (isN0ZExt
&& isAddSubZExt(N1
, DAG
)) {
2666 NewOpc
= AArch64ISD::UMULL
;
2672 if (VT
== MVT::v2i64
)
2673 // Fall through to expand this. It is not legal.
2676 // Other vector multiplications are legal.
2681 // Legalize to a S/UMULL instruction
2684 SDValue Op1
= skipExtensionForVectorMULL(N1
, DAG
);
2686 Op0
= skipExtensionForVectorMULL(N0
, DAG
);
2687 assert(Op0
.getValueType().is64BitVector() &&
2688 Op1
.getValueType().is64BitVector() &&
2689 "unexpected types for extended operands to VMULL");
2690 return DAG
.getNode(NewOpc
, DL
, VT
, Op0
, Op1
);
2692 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2693 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2694 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2695 SDValue N00
= skipExtensionForVectorMULL(N0
->getOperand(0).getNode(), DAG
);
2696 SDValue N01
= skipExtensionForVectorMULL(N0
->getOperand(1).getNode(), DAG
);
2697 EVT Op1VT
= Op1
.getValueType();
2698 return DAG
.getNode(N0
->getOpcode(), DL
, VT
,
2699 DAG
.getNode(NewOpc
, DL
, VT
,
2700 DAG
.getNode(ISD::BITCAST
, DL
, Op1VT
, N00
), Op1
),
2701 DAG
.getNode(NewOpc
, DL
, VT
,
2702 DAG
.getNode(ISD::BITCAST
, DL
, Op1VT
, N01
), Op1
));
2705 SDValue
AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op
,
2706 SelectionDAG
&DAG
) const {
2707 unsigned IntNo
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
2710 default: return SDValue(); // Don't custom lower most intrinsics.
2711 case Intrinsic::thread_pointer
: {
2712 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
2713 return DAG
.getNode(AArch64ISD::THREAD_POINTER
, dl
, PtrVT
);
2715 case Intrinsic::aarch64_neon_abs
: {
2716 EVT Ty
= Op
.getValueType();
2717 if (Ty
== MVT::i64
) {
2718 SDValue Result
= DAG
.getNode(ISD::BITCAST
, dl
, MVT::v1i64
,
2720 Result
= DAG
.getNode(ISD::ABS
, dl
, MVT::v1i64
, Result
);
2721 return DAG
.getNode(ISD::BITCAST
, dl
, MVT::i64
, Result
);
2722 } else if (Ty
.isVector() && Ty
.isInteger() && isTypeLegal(Ty
)) {
2723 return DAG
.getNode(ISD::ABS
, dl
, Ty
, Op
.getOperand(1));
2725 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2728 case Intrinsic::aarch64_neon_smax
:
2729 return DAG
.getNode(ISD::SMAX
, dl
, Op
.getValueType(),
2730 Op
.getOperand(1), Op
.getOperand(2));
2731 case Intrinsic::aarch64_neon_umax
:
2732 return DAG
.getNode(ISD::UMAX
, dl
, Op
.getValueType(),
2733 Op
.getOperand(1), Op
.getOperand(2));
2734 case Intrinsic::aarch64_neon_smin
:
2735 return DAG
.getNode(ISD::SMIN
, dl
, Op
.getValueType(),
2736 Op
.getOperand(1), Op
.getOperand(2));
2737 case Intrinsic::aarch64_neon_umin
:
2738 return DAG
.getNode(ISD::UMIN
, dl
, Op
.getValueType(),
2739 Op
.getOperand(1), Op
.getOperand(2));
2741 case Intrinsic::localaddress
: {
2742 const auto &MF
= DAG
.getMachineFunction();
2743 const auto *RegInfo
= Subtarget
->getRegisterInfo();
2744 unsigned Reg
= RegInfo
->getLocalAddressRegister(MF
);
2745 return DAG
.getCopyFromReg(DAG
.getEntryNode(), dl
, Reg
,
2746 Op
.getSimpleValueType());
2749 case Intrinsic::eh_recoverfp
: {
2750 // FIXME: This needs to be implemented to correctly handle highly aligned
2751 // stack objects. For now we simply return the incoming FP. Refer D53541
2752 // for more details.
2753 SDValue FnOp
= Op
.getOperand(1);
2754 SDValue IncomingFPOp
= Op
.getOperand(2);
2755 GlobalAddressSDNode
*GSD
= dyn_cast
<GlobalAddressSDNode
>(FnOp
);
2756 auto *Fn
= dyn_cast_or_null
<Function
>(GSD
? GSD
->getGlobal() : nullptr);
2759 "llvm.eh.recoverfp must take a function as the first argument");
2760 return IncomingFPOp
;
2765 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2766 static SDValue
LowerTruncateVectorStore(SDLoc DL
, StoreSDNode
*ST
,
2768 SelectionDAG
&DAG
) {
2769 assert(VT
.isVector() && "VT should be a vector type");
2770 assert(MemVT
== MVT::v4i8
&& VT
== MVT::v4i16
);
2772 SDValue Value
= ST
->getValue();
2774 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2775 // the word lane which represent the v4i8 subvector. It optimizes the store
2781 SDValue Undef
= DAG
.getUNDEF(MVT::i16
);
2782 SDValue UndefVec
= DAG
.getBuildVector(MVT::v4i16
, DL
,
2783 {Undef
, Undef
, Undef
, Undef
});
2785 SDValue TruncExt
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v8i16
,
2787 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::v8i8
, TruncExt
);
2789 Trunc
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2i32
, Trunc
);
2790 SDValue ExtractTrunc
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, MVT::i32
,
2791 Trunc
, DAG
.getConstant(0, DL
, MVT::i64
));
2793 return DAG
.getStore(ST
->getChain(), DL
, ExtractTrunc
,
2794 ST
->getBasePtr(), ST
->getMemOperand());
2797 // Custom lowering for any store, vector or scalar and/or default or with
2798 // a truncate operations. Currently only custom lower truncate operation
2799 // from vector v4i16 to v4i8.
2800 SDValue
AArch64TargetLowering::LowerSTORE(SDValue Op
,
2801 SelectionDAG
&DAG
) const {
2803 StoreSDNode
*StoreNode
= cast
<StoreSDNode
>(Op
);
2804 assert (StoreNode
&& "Can only custom lower store nodes");
2806 SDValue Value
= StoreNode
->getValue();
2808 EVT VT
= Value
.getValueType();
2809 EVT MemVT
= StoreNode
->getMemoryVT();
2811 assert (VT
.isVector() && "Can only custom lower vector store types");
2813 unsigned AS
= StoreNode
->getAddressSpace();
2814 unsigned Align
= StoreNode
->getAlignment();
2815 if (Align
< MemVT
.getStoreSize() &&
2816 !allowsMisalignedMemoryAccesses(MemVT
, AS
, Align
, nullptr)) {
2817 return scalarizeVectorStore(StoreNode
, DAG
);
2820 if (StoreNode
->isTruncatingStore()) {
2821 return LowerTruncateVectorStore(Dl
, StoreNode
, VT
, MemVT
, DAG
);
2827 SDValue
AArch64TargetLowering::LowerOperation(SDValue Op
,
2828 SelectionDAG
&DAG
) const {
2829 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2830 LLVM_DEBUG(Op
.dump());
2832 switch (Op
.getOpcode()) {
2834 llvm_unreachable("unimplemented operand");
2837 return LowerBITCAST(Op
, DAG
);
2838 case ISD::GlobalAddress
:
2839 return LowerGlobalAddress(Op
, DAG
);
2840 case ISD::GlobalTLSAddress
:
2841 return LowerGlobalTLSAddress(Op
, DAG
);
2843 return LowerSETCC(Op
, DAG
);
2845 return LowerBR_CC(Op
, DAG
);
2847 return LowerSELECT(Op
, DAG
);
2848 case ISD::SELECT_CC
:
2849 return LowerSELECT_CC(Op
, DAG
);
2850 case ISD::JumpTable
:
2851 return LowerJumpTable(Op
, DAG
);
2853 return LowerBR_JT(Op
, DAG
);
2854 case ISD::ConstantPool
:
2855 return LowerConstantPool(Op
, DAG
);
2856 case ISD::BlockAddress
:
2857 return LowerBlockAddress(Op
, DAG
);
2859 return LowerVASTART(Op
, DAG
);
2861 return LowerVACOPY(Op
, DAG
);
2863 return LowerVAARG(Op
, DAG
);
2868 return LowerADDC_ADDE_SUBC_SUBE(Op
, DAG
);
2875 return LowerXALUO(Op
, DAG
);
2877 return LowerF128Call(Op
, DAG
, RTLIB::ADD_F128
);
2879 return LowerF128Call(Op
, DAG
, RTLIB::SUB_F128
);
2881 return LowerF128Call(Op
, DAG
, RTLIB::MUL_F128
);
2883 return LowerF128Call(Op
, DAG
, RTLIB::DIV_F128
);
2885 return LowerFP_ROUND(Op
, DAG
);
2886 case ISD::FP_EXTEND
:
2887 return LowerFP_EXTEND(Op
, DAG
);
2888 case ISD::FRAMEADDR
:
2889 return LowerFRAMEADDR(Op
, DAG
);
2890 case ISD::SPONENTRY
:
2891 return LowerSPONENTRY(Op
, DAG
);
2892 case ISD::RETURNADDR
:
2893 return LowerRETURNADDR(Op
, DAG
);
2894 case ISD::ADDROFRETURNADDR
:
2895 return LowerADDROFRETURNADDR(Op
, DAG
);
2896 case ISD::INSERT_VECTOR_ELT
:
2897 return LowerINSERT_VECTOR_ELT(Op
, DAG
);
2898 case ISD::EXTRACT_VECTOR_ELT
:
2899 return LowerEXTRACT_VECTOR_ELT(Op
, DAG
);
2900 case ISD::BUILD_VECTOR
:
2901 return LowerBUILD_VECTOR(Op
, DAG
);
2902 case ISD::VECTOR_SHUFFLE
:
2903 return LowerVECTOR_SHUFFLE(Op
, DAG
);
2904 case ISD::EXTRACT_SUBVECTOR
:
2905 return LowerEXTRACT_SUBVECTOR(Op
, DAG
);
2909 return LowerVectorSRA_SRL_SHL(Op
, DAG
);
2910 case ISD::SHL_PARTS
:
2911 return LowerShiftLeftParts(Op
, DAG
);
2912 case ISD::SRL_PARTS
:
2913 case ISD::SRA_PARTS
:
2914 return LowerShiftRightParts(Op
, DAG
);
2916 return LowerCTPOP(Op
, DAG
);
2917 case ISD::FCOPYSIGN
:
2918 return LowerFCOPYSIGN(Op
, DAG
);
2920 return LowerVectorAND(Op
, DAG
);
2922 return LowerVectorOR(Op
, DAG
);
2924 return LowerXOR(Op
, DAG
);
2926 return LowerPREFETCH(Op
, DAG
);
2927 case ISD::SINT_TO_FP
:
2928 case ISD::UINT_TO_FP
:
2929 return LowerINT_TO_FP(Op
, DAG
);
2930 case ISD::FP_TO_SINT
:
2931 case ISD::FP_TO_UINT
:
2932 return LowerFP_TO_INT(Op
, DAG
);
2934 return LowerFSINCOS(Op
, DAG
);
2935 case ISD::FLT_ROUNDS_
:
2936 return LowerFLT_ROUNDS_(Op
, DAG
);
2938 return LowerMUL(Op
, DAG
);
2939 case ISD::INTRINSIC_WO_CHAIN
:
2940 return LowerINTRINSIC_WO_CHAIN(Op
, DAG
);
2942 return LowerSTORE(Op
, DAG
);
2943 case ISD::VECREDUCE_ADD
:
2944 case ISD::VECREDUCE_SMAX
:
2945 case ISD::VECREDUCE_SMIN
:
2946 case ISD::VECREDUCE_UMAX
:
2947 case ISD::VECREDUCE_UMIN
:
2948 case ISD::VECREDUCE_FMAX
:
2949 case ISD::VECREDUCE_FMIN
:
2950 return LowerVECREDUCE(Op
, DAG
);
2951 case ISD::ATOMIC_LOAD_SUB
:
2952 return LowerATOMIC_LOAD_SUB(Op
, DAG
);
2953 case ISD::ATOMIC_LOAD_AND
:
2954 return LowerATOMIC_LOAD_AND(Op
, DAG
);
2955 case ISD::DYNAMIC_STACKALLOC
:
2956 return LowerDYNAMIC_STACKALLOC(Op
, DAG
);
2960 //===----------------------------------------------------------------------===//
2961 // Calling Convention Implementation
2962 //===----------------------------------------------------------------------===//
2964 /// Selects the correct CCAssignFn for a given CallingConvention value.
2965 CCAssignFn
*AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC
,
2966 bool IsVarArg
) const {
2969 report_fatal_error("Unsupported calling convention.");
2970 case CallingConv::WebKit_JS
:
2971 return CC_AArch64_WebKit_JS
;
2972 case CallingConv::GHC
:
2973 return CC_AArch64_GHC
;
2974 case CallingConv::C
:
2975 case CallingConv::Fast
:
2976 case CallingConv::PreserveMost
:
2977 case CallingConv::CXX_FAST_TLS
:
2978 case CallingConv::Swift
:
2979 if (Subtarget
->isTargetWindows() && IsVarArg
)
2980 return CC_AArch64_Win64_VarArg
;
2981 if (!Subtarget
->isTargetDarwin())
2982 return CC_AArch64_AAPCS
;
2983 return IsVarArg
? CC_AArch64_DarwinPCS_VarArg
: CC_AArch64_DarwinPCS
;
2984 case CallingConv::Win64
:
2985 return IsVarArg
? CC_AArch64_Win64_VarArg
: CC_AArch64_AAPCS
;
2986 case CallingConv::AArch64_VectorCall
:
2987 return CC_AArch64_AAPCS
;
2992 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC
) const {
2993 return CC
== CallingConv::WebKit_JS
? RetCC_AArch64_WebKit_JS
2994 : RetCC_AArch64_AAPCS
;
2997 SDValue
AArch64TargetLowering::LowerFormalArguments(
2998 SDValue Chain
, CallingConv::ID CallConv
, bool isVarArg
,
2999 const SmallVectorImpl
<ISD::InputArg
> &Ins
, const SDLoc
&DL
,
3000 SelectionDAG
&DAG
, SmallVectorImpl
<SDValue
> &InVals
) const {
3001 MachineFunction
&MF
= DAG
.getMachineFunction();
3002 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3003 bool IsWin64
= Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv());
3005 // Assign locations to all of the incoming arguments.
3006 SmallVector
<CCValAssign
, 16> ArgLocs
;
3007 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), ArgLocs
,
3010 // At this point, Ins[].VT may already be promoted to i32. To correctly
3011 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3012 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3013 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3014 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3016 unsigned NumArgs
= Ins
.size();
3017 Function::const_arg_iterator CurOrigArg
= MF
.getFunction().arg_begin();
3018 unsigned CurArgIdx
= 0;
3019 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3020 MVT ValVT
= Ins
[i
].VT
;
3021 if (Ins
[i
].isOrigArg()) {
3022 std::advance(CurOrigArg
, Ins
[i
].getOrigArgIndex() - CurArgIdx
);
3023 CurArgIdx
= Ins
[i
].getOrigArgIndex();
3025 // Get type of the original argument.
3026 EVT ActualVT
= getValueType(DAG
.getDataLayout(), CurOrigArg
->getType(),
3027 /*AllowUnknown*/ true);
3028 MVT ActualMVT
= ActualVT
.isSimple() ? ActualVT
.getSimpleVT() : MVT::Other
;
3029 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3030 if (ActualMVT
== MVT::i1
|| ActualMVT
== MVT::i8
)
3032 else if (ActualMVT
== MVT::i16
)
3035 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
, /*IsVarArg=*/false);
3037 AssignFn(i
, ValVT
, ValVT
, CCValAssign::Full
, Ins
[i
].Flags
, CCInfo
);
3038 assert(!Res
&& "Call operand has unhandled type");
3041 assert(ArgLocs
.size() == Ins
.size());
3042 SmallVector
<SDValue
, 16> ArgValues
;
3043 for (unsigned i
= 0, e
= ArgLocs
.size(); i
!= e
; ++i
) {
3044 CCValAssign
&VA
= ArgLocs
[i
];
3046 if (Ins
[i
].Flags
.isByVal()) {
3047 // Byval is used for HFAs in the PCS, but the system should work in a
3048 // non-compliant manner for larger structs.
3049 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
3050 int Size
= Ins
[i
].Flags
.getByValSize();
3051 unsigned NumRegs
= (Size
+ 7) / 8;
3053 // FIXME: This works on big-endian for composite byvals, which are the common
3054 // case. It should also work for fundamental types too.
3056 MFI
.CreateFixedObject(8 * NumRegs
, VA
.getLocMemOffset(), false);
3057 SDValue FrameIdxN
= DAG
.getFrameIndex(FrameIdx
, PtrVT
);
3058 InVals
.push_back(FrameIdxN
);
3063 if (VA
.isRegLoc()) {
3064 // Arguments stored in registers.
3065 EVT RegVT
= VA
.getLocVT();
3068 const TargetRegisterClass
*RC
;
3070 if (RegVT
== MVT::i32
)
3071 RC
= &AArch64::GPR32RegClass
;
3072 else if (RegVT
== MVT::i64
)
3073 RC
= &AArch64::GPR64RegClass
;
3074 else if (RegVT
== MVT::f16
)
3075 RC
= &AArch64::FPR16RegClass
;
3076 else if (RegVT
== MVT::f32
)
3077 RC
= &AArch64::FPR32RegClass
;
3078 else if (RegVT
== MVT::f64
|| RegVT
.is64BitVector())
3079 RC
= &AArch64::FPR64RegClass
;
3080 else if (RegVT
== MVT::f128
|| RegVT
.is128BitVector())
3081 RC
= &AArch64::FPR128RegClass
;
3083 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3085 // Transform the arguments in physical registers into virtual ones.
3086 unsigned Reg
= MF
.addLiveIn(VA
.getLocReg(), RC
);
3087 ArgValue
= DAG
.getCopyFromReg(Chain
, DL
, Reg
, RegVT
);
3089 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3090 // to 64 bits. Insert an assert[sz]ext to capture this, then
3091 // truncate to the right size.
3092 switch (VA
.getLocInfo()) {
3094 llvm_unreachable("Unknown loc info!");
3095 case CCValAssign::Full
:
3097 case CCValAssign::BCvt
:
3098 ArgValue
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getValVT(), ArgValue
);
3100 case CCValAssign::AExt
:
3101 case CCValAssign::SExt
:
3102 case CCValAssign::ZExt
:
3103 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3104 // nodes after our lowering.
3105 assert(RegVT
== Ins
[i
].VT
&& "incorrect register location selected");
3109 InVals
.push_back(ArgValue
);
3111 } else { // VA.isRegLoc()
3112 assert(VA
.isMemLoc() && "CCValAssign is neither reg nor mem");
3113 unsigned ArgOffset
= VA
.getLocMemOffset();
3114 unsigned ArgSize
= VA
.getValVT().getSizeInBits() / 8;
3116 uint32_t BEAlign
= 0;
3117 if (!Subtarget
->isLittleEndian() && ArgSize
< 8 &&
3118 !Ins
[i
].Flags
.isInConsecutiveRegs())
3119 BEAlign
= 8 - ArgSize
;
3121 int FI
= MFI
.CreateFixedObject(ArgSize
, ArgOffset
+ BEAlign
, true);
3123 // Create load nodes to retrieve arguments from the stack.
3124 SDValue FIN
= DAG
.getFrameIndex(FI
, getPointerTy(DAG
.getDataLayout()));
3127 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3128 ISD::LoadExtType ExtType
= ISD::NON_EXTLOAD
;
3129 MVT MemVT
= VA
.getValVT();
3131 switch (VA
.getLocInfo()) {
3134 case CCValAssign::BCvt
:
3135 MemVT
= VA
.getLocVT();
3137 case CCValAssign::SExt
:
3138 ExtType
= ISD::SEXTLOAD
;
3140 case CCValAssign::ZExt
:
3141 ExtType
= ISD::ZEXTLOAD
;
3143 case CCValAssign::AExt
:
3144 ExtType
= ISD::EXTLOAD
;
3148 ArgValue
= DAG
.getExtLoad(
3149 ExtType
, DL
, VA
.getLocVT(), Chain
, FIN
,
3150 MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(), FI
),
3153 InVals
.push_back(ArgValue
);
3158 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3160 if (!Subtarget
->isTargetDarwin() || IsWin64
) {
3161 // The AAPCS variadic function ABI is identical to the non-variadic
3162 // one. As a result there may be more arguments in registers and we should
3163 // save them for future reference.
3164 // Win64 variadic functions also pass arguments in registers, but all float
3165 // arguments are passed in integer registers.
3166 saveVarArgRegisters(CCInfo
, DAG
, DL
, Chain
);
3169 // This will point to the next argument passed via stack.
3170 unsigned StackOffset
= CCInfo
.getNextStackOffset();
3171 // We currently pass all varargs at 8-byte alignment.
3172 StackOffset
= ((StackOffset
+ 7) & ~7);
3173 FuncInfo
->setVarArgsStackIndex(MFI
.CreateFixedObject(4, StackOffset
, true));
3175 if (MFI
.hasMustTailInVarArgFunc()) {
3176 SmallVector
<MVT
, 2> RegParmTypes
;
3177 RegParmTypes
.push_back(MVT::i64
);
3178 RegParmTypes
.push_back(MVT::f128
);
3179 // Compute the set of forwarded registers. The rest are scratch.
3180 SmallVectorImpl
<ForwardedRegister
> &Forwards
=
3181 FuncInfo
->getForwardedMustTailRegParms();
3182 CCInfo
.analyzeMustTailForwardedRegisters(Forwards
, RegParmTypes
,
3187 unsigned StackArgSize
= CCInfo
.getNextStackOffset();
3188 bool TailCallOpt
= MF
.getTarget().Options
.GuaranteedTailCallOpt
;
3189 if (DoesCalleeRestoreStack(CallConv
, TailCallOpt
)) {
3190 // This is a non-standard ABI so by fiat I say we're allowed to make full
3191 // use of the stack area to be popped, which must be aligned to 16 bytes in
3193 StackArgSize
= alignTo(StackArgSize
, 16);
3195 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3196 // a multiple of 16.
3197 FuncInfo
->setArgumentStackToRestore(StackArgSize
);
3199 // This realignment carries over to the available bytes below. Our own
3200 // callers will guarantee the space is free by giving an aligned value to
3203 // Even if we're not expected to free up the space, it's useful to know how
3204 // much is there while considering tail calls (because we can reuse it).
3205 FuncInfo
->setBytesInStackArgArea(StackArgSize
);
3207 if (Subtarget
->hasCustomCallingConv())
3208 Subtarget
->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF
);
3213 void AArch64TargetLowering::saveVarArgRegisters(CCState
&CCInfo
,
3216 SDValue
&Chain
) const {
3217 MachineFunction
&MF
= DAG
.getMachineFunction();
3218 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3219 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3220 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
3221 bool IsWin64
= Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv());
3223 SmallVector
<SDValue
, 8> MemOps
;
3225 static const MCPhysReg GPRArgRegs
[] = { AArch64::X0
, AArch64::X1
, AArch64::X2
,
3226 AArch64::X3
, AArch64::X4
, AArch64::X5
,
3227 AArch64::X6
, AArch64::X7
};
3228 static const unsigned NumGPRArgRegs
= array_lengthof(GPRArgRegs
);
3229 unsigned FirstVariadicGPR
= CCInfo
.getFirstUnallocated(GPRArgRegs
);
3231 unsigned GPRSaveSize
= 8 * (NumGPRArgRegs
- FirstVariadicGPR
);
3233 if (GPRSaveSize
!= 0) {
3235 GPRIdx
= MFI
.CreateFixedObject(GPRSaveSize
, -(int)GPRSaveSize
, false);
3236 if (GPRSaveSize
& 15)
3237 // The extra size here, if triggered, will always be 8.
3238 MFI
.CreateFixedObject(16 - (GPRSaveSize
& 15), -(int)alignTo(GPRSaveSize
, 16), false);
3240 GPRIdx
= MFI
.CreateStackObject(GPRSaveSize
, 8, false);
3242 SDValue FIN
= DAG
.getFrameIndex(GPRIdx
, PtrVT
);
3244 for (unsigned i
= FirstVariadicGPR
; i
< NumGPRArgRegs
; ++i
) {
3245 unsigned VReg
= MF
.addLiveIn(GPRArgRegs
[i
], &AArch64::GPR64RegClass
);
3246 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, VReg
, MVT::i64
);
3247 SDValue Store
= DAG
.getStore(
3248 Val
.getValue(1), DL
, Val
, FIN
,
3250 ? MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(),
3252 (i
- FirstVariadicGPR
) * 8)
3253 : MachinePointerInfo::getStack(DAG
.getMachineFunction(), i
* 8));
3254 MemOps
.push_back(Store
);
3256 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, FIN
, DAG
.getConstant(8, DL
, PtrVT
));
3259 FuncInfo
->setVarArgsGPRIndex(GPRIdx
);
3260 FuncInfo
->setVarArgsGPRSize(GPRSaveSize
);
3262 if (Subtarget
->hasFPARMv8() && !IsWin64
) {
3263 static const MCPhysReg FPRArgRegs
[] = {
3264 AArch64::Q0
, AArch64::Q1
, AArch64::Q2
, AArch64::Q3
,
3265 AArch64::Q4
, AArch64::Q5
, AArch64::Q6
, AArch64::Q7
};
3266 static const unsigned NumFPRArgRegs
= array_lengthof(FPRArgRegs
);
3267 unsigned FirstVariadicFPR
= CCInfo
.getFirstUnallocated(FPRArgRegs
);
3269 unsigned FPRSaveSize
= 16 * (NumFPRArgRegs
- FirstVariadicFPR
);
3271 if (FPRSaveSize
!= 0) {
3272 FPRIdx
= MFI
.CreateStackObject(FPRSaveSize
, 16, false);
3274 SDValue FIN
= DAG
.getFrameIndex(FPRIdx
, PtrVT
);
3276 for (unsigned i
= FirstVariadicFPR
; i
< NumFPRArgRegs
; ++i
) {
3277 unsigned VReg
= MF
.addLiveIn(FPRArgRegs
[i
], &AArch64::FPR128RegClass
);
3278 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, VReg
, MVT::f128
);
3280 SDValue Store
= DAG
.getStore(
3281 Val
.getValue(1), DL
, Val
, FIN
,
3282 MachinePointerInfo::getStack(DAG
.getMachineFunction(), i
* 16));
3283 MemOps
.push_back(Store
);
3284 FIN
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, FIN
,
3285 DAG
.getConstant(16, DL
, PtrVT
));
3288 FuncInfo
->setVarArgsFPRIndex(FPRIdx
);
3289 FuncInfo
->setVarArgsFPRSize(FPRSaveSize
);
3292 if (!MemOps
.empty()) {
3293 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOps
);
3297 /// LowerCallResult - Lower the result values of a call into the
3298 /// appropriate copies out of appropriate physical registers.
3299 SDValue
AArch64TargetLowering::LowerCallResult(
3300 SDValue Chain
, SDValue InFlag
, CallingConv::ID CallConv
, bool isVarArg
,
3301 const SmallVectorImpl
<ISD::InputArg
> &Ins
, const SDLoc
&DL
,
3302 SelectionDAG
&DAG
, SmallVectorImpl
<SDValue
> &InVals
, bool isThisReturn
,
3303 SDValue ThisVal
) const {
3304 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
3305 ? RetCC_AArch64_WebKit_JS
3306 : RetCC_AArch64_AAPCS
;
3307 // Assign locations to each value returned by this call.
3308 SmallVector
<CCValAssign
, 16> RVLocs
;
3309 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), RVLocs
,
3311 CCInfo
.AnalyzeCallResult(Ins
, RetCC
);
3313 // Copy all of the result registers out of their specified physreg.
3314 for (unsigned i
= 0; i
!= RVLocs
.size(); ++i
) {
3315 CCValAssign VA
= RVLocs
[i
];
3317 // Pass 'this' value directly from the argument to return value, to avoid
3318 // reg unit interference
3319 if (i
== 0 && isThisReturn
) {
3320 assert(!VA
.needsCustom() && VA
.getLocVT() == MVT::i64
&&
3321 "unexpected return calling convention register assignment");
3322 InVals
.push_back(ThisVal
);
3327 DAG
.getCopyFromReg(Chain
, DL
, VA
.getLocReg(), VA
.getLocVT(), InFlag
);
3328 Chain
= Val
.getValue(1);
3329 InFlag
= Val
.getValue(2);
3331 switch (VA
.getLocInfo()) {
3333 llvm_unreachable("Unknown loc info!");
3334 case CCValAssign::Full
:
3336 case CCValAssign::BCvt
:
3337 Val
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getValVT(), Val
);
3341 InVals
.push_back(Val
);
3347 /// Return true if the calling convention is one that we can guarantee TCO for.
3348 static bool canGuaranteeTCO(CallingConv::ID CC
) {
3349 return CC
== CallingConv::Fast
;
3352 /// Return true if we might ever do TCO for calls with this calling convention.
3353 static bool mayTailCallThisCC(CallingConv::ID CC
) {
3355 case CallingConv::C
:
3356 case CallingConv::PreserveMost
:
3357 case CallingConv::Swift
:
3360 return canGuaranteeTCO(CC
);
3364 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3365 SDValue Callee
, CallingConv::ID CalleeCC
, bool isVarArg
,
3366 const SmallVectorImpl
<ISD::OutputArg
> &Outs
,
3367 const SmallVectorImpl
<SDValue
> &OutVals
,
3368 const SmallVectorImpl
<ISD::InputArg
> &Ins
, SelectionDAG
&DAG
) const {
3369 if (!mayTailCallThisCC(CalleeCC
))
3372 MachineFunction
&MF
= DAG
.getMachineFunction();
3373 const Function
&CallerF
= MF
.getFunction();
3374 CallingConv::ID CallerCC
= CallerF
.getCallingConv();
3375 bool CCMatch
= CallerCC
== CalleeCC
;
3377 // Byval parameters hand the function a pointer directly into the stack area
3378 // we want to reuse during a tail call. Working around this *is* possible (see
3379 // X86) but less efficient and uglier in LowerCall.
3380 for (Function::const_arg_iterator i
= CallerF
.arg_begin(),
3381 e
= CallerF
.arg_end();
3383 if (i
->hasByValAttr())
3386 if (getTargetMachine().Options
.GuaranteedTailCallOpt
)
3387 return canGuaranteeTCO(CalleeCC
) && CCMatch
;
3389 // Externally-defined functions with weak linkage should not be
3390 // tail-called on AArch64 when the OS does not support dynamic
3391 // pre-emption of symbols, as the AAELF spec requires normal calls
3392 // to undefined weak functions to be replaced with a NOP or jump to the
3393 // next instruction. The behaviour of branch instructions in this
3394 // situation (as used for tail calls) is implementation-defined, so we
3395 // cannot rely on the linker replacing the tail call with a return.
3396 if (GlobalAddressSDNode
*G
= dyn_cast
<GlobalAddressSDNode
>(Callee
)) {
3397 const GlobalValue
*GV
= G
->getGlobal();
3398 const Triple
&TT
= getTargetMachine().getTargetTriple();
3399 if (GV
->hasExternalWeakLinkage() &&
3400 (!TT
.isOSWindows() || TT
.isOSBinFormatELF() || TT
.isOSBinFormatMachO()))
3404 // Now we search for cases where we can use a tail call without changing the
3405 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3408 // I want anyone implementing a new calling convention to think long and hard
3409 // about this assert.
3410 assert((!isVarArg
|| CalleeCC
== CallingConv::C
) &&
3411 "Unexpected variadic calling convention");
3413 LLVMContext
&C
= *DAG
.getContext();
3414 if (isVarArg
&& !Outs
.empty()) {
3415 // At least two cases here: if caller is fastcc then we can't have any
3416 // memory arguments (we'd be expected to clean up the stack afterwards). If
3417 // caller is C then we could potentially use its argument area.
3419 // FIXME: for now we take the most conservative of these in both cases:
3420 // disallow all variadic memory operands.
3421 SmallVector
<CCValAssign
, 16> ArgLocs
;
3422 CCState
CCInfo(CalleeCC
, isVarArg
, MF
, ArgLocs
, C
);
3424 CCInfo
.AnalyzeCallOperands(Outs
, CCAssignFnForCall(CalleeCC
, true));
3425 for (const CCValAssign
&ArgLoc
: ArgLocs
)
3426 if (!ArgLoc
.isRegLoc())
3430 // Check that the call results are passed in the same way.
3431 if (!CCState::resultsCompatible(CalleeCC
, CallerCC
, MF
, C
, Ins
,
3432 CCAssignFnForCall(CalleeCC
, isVarArg
),
3433 CCAssignFnForCall(CallerCC
, isVarArg
)))
3435 // The callee has to preserve all registers the caller needs to preserve.
3436 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
3437 const uint32_t *CallerPreserved
= TRI
->getCallPreservedMask(MF
, CallerCC
);
3439 const uint32_t *CalleePreserved
= TRI
->getCallPreservedMask(MF
, CalleeCC
);
3440 if (Subtarget
->hasCustomCallingConv()) {
3441 TRI
->UpdateCustomCallPreservedMask(MF
, &CallerPreserved
);
3442 TRI
->UpdateCustomCallPreservedMask(MF
, &CalleePreserved
);
3444 if (!TRI
->regmaskSubsetEqual(CallerPreserved
, CalleePreserved
))
3448 // Nothing more to check if the callee is taking no arguments
3452 SmallVector
<CCValAssign
, 16> ArgLocs
;
3453 CCState
CCInfo(CalleeCC
, isVarArg
, MF
, ArgLocs
, C
);
3455 CCInfo
.AnalyzeCallOperands(Outs
, CCAssignFnForCall(CalleeCC
, isVarArg
));
3457 const AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3459 // If the stack arguments for this call do not fit into our own save area then
3460 // the call cannot be made tail.
3461 if (CCInfo
.getNextStackOffset() > FuncInfo
->getBytesInStackArgArea())
3464 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
3465 if (!parametersInCSRMatch(MRI
, CallerPreserved
, ArgLocs
, OutVals
))
3471 SDValue
AArch64TargetLowering::addTokenForArgument(SDValue Chain
,
3473 MachineFrameInfo
&MFI
,
3474 int ClobberedFI
) const {
3475 SmallVector
<SDValue
, 8> ArgChains
;
3476 int64_t FirstByte
= MFI
.getObjectOffset(ClobberedFI
);
3477 int64_t LastByte
= FirstByte
+ MFI
.getObjectSize(ClobberedFI
) - 1;
3479 // Include the original chain at the beginning of the list. When this is
3480 // used by target LowerCall hooks, this helps legalize find the
3481 // CALLSEQ_BEGIN node.
3482 ArgChains
.push_back(Chain
);
3484 // Add a chain value for each stack argument corresponding
3485 for (SDNode::use_iterator U
= DAG
.getEntryNode().getNode()->use_begin(),
3486 UE
= DAG
.getEntryNode().getNode()->use_end();
3488 if (LoadSDNode
*L
= dyn_cast
<LoadSDNode
>(*U
))
3489 if (FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(L
->getBasePtr()))
3490 if (FI
->getIndex() < 0) {
3491 int64_t InFirstByte
= MFI
.getObjectOffset(FI
->getIndex());
3492 int64_t InLastByte
= InFirstByte
;
3493 InLastByte
+= MFI
.getObjectSize(FI
->getIndex()) - 1;
3495 if ((InFirstByte
<= FirstByte
&& FirstByte
<= InLastByte
) ||
3496 (FirstByte
<= InFirstByte
&& InFirstByte
<= LastByte
))
3497 ArgChains
.push_back(SDValue(L
, 1));
3500 // Build a tokenfactor for all the chains.
3501 return DAG
.getNode(ISD::TokenFactor
, SDLoc(Chain
), MVT::Other
, ArgChains
);
3504 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC
,
3505 bool TailCallOpt
) const {
3506 return CallCC
== CallingConv::Fast
&& TailCallOpt
;
3509 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3510 /// and add input and output parameter nodes.
3512 AArch64TargetLowering::LowerCall(CallLoweringInfo
&CLI
,
3513 SmallVectorImpl
<SDValue
> &InVals
) const {
3514 SelectionDAG
&DAG
= CLI
.DAG
;
3516 SmallVector
<ISD::OutputArg
, 32> &Outs
= CLI
.Outs
;
3517 SmallVector
<SDValue
, 32> &OutVals
= CLI
.OutVals
;
3518 SmallVector
<ISD::InputArg
, 32> &Ins
= CLI
.Ins
;
3519 SDValue Chain
= CLI
.Chain
;
3520 SDValue Callee
= CLI
.Callee
;
3521 bool &IsTailCall
= CLI
.IsTailCall
;
3522 CallingConv::ID CallConv
= CLI
.CallConv
;
3523 bool IsVarArg
= CLI
.IsVarArg
;
3525 MachineFunction
&MF
= DAG
.getMachineFunction();
3526 bool IsThisReturn
= false;
3528 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3529 bool TailCallOpt
= MF
.getTarget().Options
.GuaranteedTailCallOpt
;
3530 bool IsSibCall
= false;
3533 // Check if it's really possible to do a tail call.
3534 IsTailCall
= isEligibleForTailCallOptimization(
3535 Callee
, CallConv
, IsVarArg
, Outs
, OutVals
, Ins
, DAG
);
3536 if (!IsTailCall
&& CLI
.CS
&& CLI
.CS
.isMustTailCall())
3537 report_fatal_error("failed to perform tail call elimination on a call "
3538 "site marked musttail");
3540 // A sibling call is one where we're under the usual C ABI and not planning
3541 // to change that but can still do a tail call:
3542 if (!TailCallOpt
&& IsTailCall
)
3549 // Analyze operands of the call, assigning locations to each operand.
3550 SmallVector
<CCValAssign
, 16> ArgLocs
;
3551 CCState
CCInfo(CallConv
, IsVarArg
, DAG
.getMachineFunction(), ArgLocs
,
3555 // Handle fixed and variable vector arguments differently.
3556 // Variable vector arguments always go into memory.
3557 unsigned NumArgs
= Outs
.size();
3559 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3560 MVT ArgVT
= Outs
[i
].VT
;
3561 ISD::ArgFlagsTy ArgFlags
= Outs
[i
].Flags
;
3562 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
,
3563 /*IsVarArg=*/ !Outs
[i
].IsFixed
);
3564 bool Res
= AssignFn(i
, ArgVT
, ArgVT
, CCValAssign::Full
, ArgFlags
, CCInfo
);
3565 assert(!Res
&& "Call operand has unhandled type");
3569 // At this point, Outs[].VT may already be promoted to i32. To correctly
3570 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3571 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3572 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3573 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3575 unsigned NumArgs
= Outs
.size();
3576 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3577 MVT ValVT
= Outs
[i
].VT
;
3578 // Get type of the original argument.
3579 EVT ActualVT
= getValueType(DAG
.getDataLayout(),
3580 CLI
.getArgs()[Outs
[i
].OrigArgIndex
].Ty
,
3581 /*AllowUnknown*/ true);
3582 MVT ActualMVT
= ActualVT
.isSimple() ? ActualVT
.getSimpleVT() : ValVT
;
3583 ISD::ArgFlagsTy ArgFlags
= Outs
[i
].Flags
;
3584 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3585 if (ActualMVT
== MVT::i1
|| ActualMVT
== MVT::i8
)
3587 else if (ActualMVT
== MVT::i16
)
3590 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
, /*IsVarArg=*/false);
3591 bool Res
= AssignFn(i
, ValVT
, ValVT
, CCValAssign::Full
, ArgFlags
, CCInfo
);
3592 assert(!Res
&& "Call operand has unhandled type");
3597 // Get a count of how many bytes are to be pushed on the stack.
3598 unsigned NumBytes
= CCInfo
.getNextStackOffset();
3601 // Since we're not changing the ABI to make this a tail call, the memory
3602 // operands are already available in the caller's incoming argument space.
3606 // FPDiff is the byte offset of the call's argument area from the callee's.
3607 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3608 // by this amount for a tail call. In a sibling call it must be 0 because the
3609 // caller will deallocate the entire stack and the callee still expects its
3610 // arguments to begin at SP+0. Completely unused for non-tail calls.
3613 if (IsTailCall
&& !IsSibCall
) {
3614 unsigned NumReusableBytes
= FuncInfo
->getBytesInStackArgArea();
3616 // Since callee will pop argument stack as a tail call, we must keep the
3617 // popped size 16-byte aligned.
3618 NumBytes
= alignTo(NumBytes
, 16);
3620 // FPDiff will be negative if this tail call requires more space than we
3621 // would automatically have in our incoming argument space. Positive if we
3622 // can actually shrink the stack.
3623 FPDiff
= NumReusableBytes
- NumBytes
;
3625 // The stack pointer must be 16-byte aligned at all times it's used for a
3626 // memory operation, which in practice means at *all* times and in
3627 // particular across call boundaries. Therefore our own arguments started at
3628 // a 16-byte aligned SP and the delta applied for the tail call should
3629 // satisfy the same constraint.
3630 assert(FPDiff
% 16 == 0 && "unaligned stack on tail call");
3633 // Adjust the stack pointer for the new arguments...
3634 // These operations are automatically eliminated by the prolog/epilog pass
3636 Chain
= DAG
.getCALLSEQ_START(Chain
, NumBytes
, 0, DL
);
3638 SDValue StackPtr
= DAG
.getCopyFromReg(Chain
, DL
, AArch64::SP
,
3639 getPointerTy(DAG
.getDataLayout()));
3641 SmallVector
<std::pair
<unsigned, SDValue
>, 8> RegsToPass
;
3642 SmallVector
<SDValue
, 8> MemOpChains
;
3643 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
3645 if (IsVarArg
&& CLI
.CS
&& CLI
.CS
.isMustTailCall()) {
3646 const auto &Forwards
= FuncInfo
->getForwardedMustTailRegParms();
3647 for (const auto &F
: Forwards
) {
3648 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, F
.VReg
, F
.VT
);
3649 RegsToPass
.push_back(std::make_pair(unsigned(F
.PReg
), Val
));
3653 // Walk the register/memloc assignments, inserting copies/loads.
3654 for (unsigned i
= 0, realArgIdx
= 0, e
= ArgLocs
.size(); i
!= e
;
3655 ++i
, ++realArgIdx
) {
3656 CCValAssign
&VA
= ArgLocs
[i
];
3657 SDValue Arg
= OutVals
[realArgIdx
];
3658 ISD::ArgFlagsTy Flags
= Outs
[realArgIdx
].Flags
;
3660 // Promote the value if needed.
3661 switch (VA
.getLocInfo()) {
3663 llvm_unreachable("Unknown loc info!");
3664 case CCValAssign::Full
:
3666 case CCValAssign::SExt
:
3667 Arg
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3669 case CCValAssign::ZExt
:
3670 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3672 case CCValAssign::AExt
:
3673 if (Outs
[realArgIdx
].ArgVT
== MVT::i1
) {
3674 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3675 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i1
, Arg
);
3676 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i8
, Arg
);
3678 Arg
= DAG
.getNode(ISD::ANY_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3680 case CCValAssign::BCvt
:
3681 Arg
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getLocVT(), Arg
);
3683 case CCValAssign::FPExt
:
3684 Arg
= DAG
.getNode(ISD::FP_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3688 if (VA
.isRegLoc()) {
3689 if (realArgIdx
== 0 && Flags
.isReturned() && !Flags
.isSwiftSelf() &&
3690 Outs
[0].VT
== MVT::i64
) {
3691 assert(VA
.getLocVT() == MVT::i64
&&
3692 "unexpected calling convention register assignment");
3693 assert(!Ins
.empty() && Ins
[0].VT
== MVT::i64
&&
3694 "unexpected use of 'returned'");
3695 IsThisReturn
= true;
3697 RegsToPass
.push_back(std::make_pair(VA
.getLocReg(), Arg
));
3699 assert(VA
.isMemLoc());
3702 MachinePointerInfo DstInfo
;
3704 // FIXME: This works on big-endian for composite byvals, which are the
3705 // common case. It should also work for fundamental types too.
3706 uint32_t BEAlign
= 0;
3707 unsigned OpSize
= Flags
.isByVal() ? Flags
.getByValSize() * 8
3708 : VA
.getValVT().getSizeInBits();
3709 OpSize
= (OpSize
+ 7) / 8;
3710 if (!Subtarget
->isLittleEndian() && !Flags
.isByVal() &&
3711 !Flags
.isInConsecutiveRegs()) {
3713 BEAlign
= 8 - OpSize
;
3715 unsigned LocMemOffset
= VA
.getLocMemOffset();
3716 int32_t Offset
= LocMemOffset
+ BEAlign
;
3717 SDValue PtrOff
= DAG
.getIntPtrConstant(Offset
, DL
);
3718 PtrOff
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, StackPtr
, PtrOff
);
3721 Offset
= Offset
+ FPDiff
;
3722 int FI
= MF
.getFrameInfo().CreateFixedObject(OpSize
, Offset
, true);
3724 DstAddr
= DAG
.getFrameIndex(FI
, PtrVT
);
3726 MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(), FI
);
3728 // Make sure any stack arguments overlapping with where we're storing
3729 // are loaded before this eventual operation. Otherwise they'll be
3731 Chain
= addTokenForArgument(Chain
, DAG
, MF
.getFrameInfo(), FI
);
3733 SDValue PtrOff
= DAG
.getIntPtrConstant(Offset
, DL
);
3735 DstAddr
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, StackPtr
, PtrOff
);
3736 DstInfo
= MachinePointerInfo::getStack(DAG
.getMachineFunction(),
3740 if (Outs
[i
].Flags
.isByVal()) {
3742 DAG
.getConstant(Outs
[i
].Flags
.getByValSize(), DL
, MVT::i64
);
3743 SDValue Cpy
= DAG
.getMemcpy(
3744 Chain
, DL
, DstAddr
, Arg
, SizeNode
, Outs
[i
].Flags
.getByValAlign(),
3745 /*isVol = */ false, /*AlwaysInline = */ false,
3746 /*isTailCall = */ false,
3747 DstInfo
, MachinePointerInfo());
3749 MemOpChains
.push_back(Cpy
);
3751 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3752 // promoted to a legal register type i32, we should truncate Arg back to
3754 if (VA
.getValVT() == MVT::i1
|| VA
.getValVT() == MVT::i8
||
3755 VA
.getValVT() == MVT::i16
)
3756 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, VA
.getValVT(), Arg
);
3758 SDValue Store
= DAG
.getStore(Chain
, DL
, Arg
, DstAddr
, DstInfo
);
3759 MemOpChains
.push_back(Store
);
3764 if (!MemOpChains
.empty())
3765 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOpChains
);
3767 // Build a sequence of copy-to-reg nodes chained together with token chain
3768 // and flag operands which copy the outgoing args into the appropriate regs.
3770 for (auto &RegToPass
: RegsToPass
) {
3771 Chain
= DAG
.getCopyToReg(Chain
, DL
, RegToPass
.first
,
3772 RegToPass
.second
, InFlag
);
3773 InFlag
= Chain
.getValue(1);
3776 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3777 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3778 // node so that legalize doesn't hack it.
3779 if (auto *G
= dyn_cast
<GlobalAddressSDNode
>(Callee
)) {
3780 auto GV
= G
->getGlobal();
3781 if (Subtarget
->classifyGlobalFunctionReference(GV
, getTargetMachine()) ==
3782 AArch64II::MO_GOT
) {
3783 Callee
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_GOT
);
3784 Callee
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, Callee
);
3785 } else if (Subtarget
->isTargetCOFF() && GV
->hasDLLImportStorageClass()) {
3786 assert(Subtarget
->isTargetWindows() &&
3787 "Windows is the only supported COFF target");
3788 Callee
= getGOT(G
, DAG
, AArch64II::MO_DLLIMPORT
);
3790 const GlobalValue
*GV
= G
->getGlobal();
3791 Callee
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, 0);
3793 } else if (auto *S
= dyn_cast
<ExternalSymbolSDNode
>(Callee
)) {
3794 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
3795 Subtarget
->isTargetMachO()) {
3796 const char *Sym
= S
->getSymbol();
3797 Callee
= DAG
.getTargetExternalSymbol(Sym
, PtrVT
, AArch64II::MO_GOT
);
3798 Callee
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, Callee
);
3800 const char *Sym
= S
->getSymbol();
3801 Callee
= DAG
.getTargetExternalSymbol(Sym
, PtrVT
, 0);
3805 // We don't usually want to end the call-sequence here because we would tidy
3806 // the frame up *after* the call, however in the ABI-changing tail-call case
3807 // we've carefully laid out the parameters so that when sp is reset they'll be
3808 // in the correct location.
3809 if (IsTailCall
&& !IsSibCall
) {
3810 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(NumBytes
, DL
, true),
3811 DAG
.getIntPtrConstant(0, DL
, true), InFlag
, DL
);
3812 InFlag
= Chain
.getValue(1);
3815 std::vector
<SDValue
> Ops
;
3816 Ops
.push_back(Chain
);
3817 Ops
.push_back(Callee
);
3820 // Each tail call may have to adjust the stack by a different amount, so
3821 // this information must travel along with the operation for eventual
3822 // consumption by emitEpilogue.
3823 Ops
.push_back(DAG
.getTargetConstant(FPDiff
, DL
, MVT::i32
));
3826 // Add argument registers to the end of the list so that they are known live
3828 for (auto &RegToPass
: RegsToPass
)
3829 Ops
.push_back(DAG
.getRegister(RegToPass
.first
,
3830 RegToPass
.second
.getValueType()));
3832 // Add a register mask operand representing the call-preserved registers.
3833 const uint32_t *Mask
;
3834 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
3836 // For 'this' returns, use the X0-preserving mask if applicable
3837 Mask
= TRI
->getThisReturnPreservedMask(MF
, CallConv
);
3839 IsThisReturn
= false;
3840 Mask
= TRI
->getCallPreservedMask(MF
, CallConv
);
3843 Mask
= TRI
->getCallPreservedMask(MF
, CallConv
);
3845 if (Subtarget
->hasCustomCallingConv())
3846 TRI
->UpdateCustomCallPreservedMask(MF
, &Mask
);
3848 if (TRI
->isAnyArgRegReserved(MF
))
3849 TRI
->emitReservedArgRegCallError(MF
);
3851 assert(Mask
&& "Missing call preserved mask for calling convention");
3852 Ops
.push_back(DAG
.getRegisterMask(Mask
));
3854 if (InFlag
.getNode())
3855 Ops
.push_back(InFlag
);
3857 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
3859 // If we're doing a tall call, use a TC_RETURN here rather than an
3860 // actual call instruction.
3862 MF
.getFrameInfo().setHasTailCall();
3863 return DAG
.getNode(AArch64ISD::TC_RETURN
, DL
, NodeTys
, Ops
);
3866 // Returns a chain and a flag for retval copy to use.
3867 Chain
= DAG
.getNode(AArch64ISD::CALL
, DL
, NodeTys
, Ops
);
3868 InFlag
= Chain
.getValue(1);
3870 uint64_t CalleePopBytes
=
3871 DoesCalleeRestoreStack(CallConv
, TailCallOpt
) ? alignTo(NumBytes
, 16) : 0;
3873 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(NumBytes
, DL
, true),
3874 DAG
.getIntPtrConstant(CalleePopBytes
, DL
, true),
3877 InFlag
= Chain
.getValue(1);
3879 // Handle result values, copying them out of physregs into vregs that we
3881 return LowerCallResult(Chain
, InFlag
, CallConv
, IsVarArg
, Ins
, DL
, DAG
,
3882 InVals
, IsThisReturn
,
3883 IsThisReturn
? OutVals
[0] : SDValue());
3886 bool AArch64TargetLowering::CanLowerReturn(
3887 CallingConv::ID CallConv
, MachineFunction
&MF
, bool isVarArg
,
3888 const SmallVectorImpl
<ISD::OutputArg
> &Outs
, LLVMContext
&Context
) const {
3889 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
3890 ? RetCC_AArch64_WebKit_JS
3891 : RetCC_AArch64_AAPCS
;
3892 SmallVector
<CCValAssign
, 16> RVLocs
;
3893 CCState
CCInfo(CallConv
, isVarArg
, MF
, RVLocs
, Context
);
3894 return CCInfo
.CheckReturn(Outs
, RetCC
);
3898 AArch64TargetLowering::LowerReturn(SDValue Chain
, CallingConv::ID CallConv
,
3900 const SmallVectorImpl
<ISD::OutputArg
> &Outs
,
3901 const SmallVectorImpl
<SDValue
> &OutVals
,
3902 const SDLoc
&DL
, SelectionDAG
&DAG
) const {
3903 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
3904 ? RetCC_AArch64_WebKit_JS
3905 : RetCC_AArch64_AAPCS
;
3906 SmallVector
<CCValAssign
, 16> RVLocs
;
3907 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), RVLocs
,
3909 CCInfo
.AnalyzeReturn(Outs
, RetCC
);
3911 // Copy the result values into the output registers.
3913 SmallVector
<SDValue
, 4> RetOps(1, Chain
);
3914 for (unsigned i
= 0, realRVLocIdx
= 0; i
!= RVLocs
.size();
3915 ++i
, ++realRVLocIdx
) {
3916 CCValAssign
&VA
= RVLocs
[i
];
3917 assert(VA
.isRegLoc() && "Can only return in registers!");
3918 SDValue Arg
= OutVals
[realRVLocIdx
];
3920 switch (VA
.getLocInfo()) {
3922 llvm_unreachable("Unknown loc info!");
3923 case CCValAssign::Full
:
3924 if (Outs
[i
].ArgVT
== MVT::i1
) {
3925 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3926 // value. This is strictly redundant on Darwin (which uses "zeroext
3927 // i1"), but will be optimised out before ISel.
3928 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i1
, Arg
);
3929 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3932 case CCValAssign::BCvt
:
3933 Arg
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getLocVT(), Arg
);
3937 Chain
= DAG
.getCopyToReg(Chain
, DL
, VA
.getLocReg(), Arg
, Flag
);
3938 Flag
= Chain
.getValue(1);
3939 RetOps
.push_back(DAG
.getRegister(VA
.getLocReg(), VA
.getLocVT()));
3941 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
3942 const MCPhysReg
*I
=
3943 TRI
->getCalleeSavedRegsViaCopy(&DAG
.getMachineFunction());
3946 if (AArch64::GPR64RegClass
.contains(*I
))
3947 RetOps
.push_back(DAG
.getRegister(*I
, MVT::i64
));
3948 else if (AArch64::FPR64RegClass
.contains(*I
))
3949 RetOps
.push_back(DAG
.getRegister(*I
, MVT::getFloatingPointVT(64)));
3951 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3955 RetOps
[0] = Chain
; // Update chain.
3957 // Add the flag if we have it.
3959 RetOps
.push_back(Flag
);
3961 return DAG
.getNode(AArch64ISD::RET_FLAG
, DL
, MVT::Other
, RetOps
);
3964 //===----------------------------------------------------------------------===//
3965 // Other Lowering Code
3966 //===----------------------------------------------------------------------===//
3968 SDValue
AArch64TargetLowering::getTargetNode(GlobalAddressSDNode
*N
, EVT Ty
,
3970 unsigned Flag
) const {
3971 return DAG
.getTargetGlobalAddress(N
->getGlobal(), SDLoc(N
), Ty
,
3972 N
->getOffset(), Flag
);
3975 SDValue
AArch64TargetLowering::getTargetNode(JumpTableSDNode
*N
, EVT Ty
,
3977 unsigned Flag
) const {
3978 return DAG
.getTargetJumpTable(N
->getIndex(), Ty
, Flag
);
3981 SDValue
AArch64TargetLowering::getTargetNode(ConstantPoolSDNode
*N
, EVT Ty
,
3983 unsigned Flag
) const {
3984 return DAG
.getTargetConstantPool(N
->getConstVal(), Ty
, N
->getAlignment(),
3985 N
->getOffset(), Flag
);
3988 SDValue
AArch64TargetLowering::getTargetNode(BlockAddressSDNode
* N
, EVT Ty
,
3990 unsigned Flag
) const {
3991 return DAG
.getTargetBlockAddress(N
->getBlockAddress(), Ty
, 0, Flag
);
3995 template <class NodeTy
>
3996 SDValue
AArch64TargetLowering::getGOT(NodeTy
*N
, SelectionDAG
&DAG
,
3997 unsigned Flags
) const {
3998 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4000 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4001 SDValue GotAddr
= getTargetNode(N
, Ty
, DAG
, AArch64II::MO_GOT
| Flags
);
4002 // FIXME: Once remat is capable of dealing with instructions with register
4003 // operands, expand this into two nodes instead of using a wrapper node.
4004 return DAG
.getNode(AArch64ISD::LOADgot
, DL
, Ty
, GotAddr
);
4007 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4008 template <class NodeTy
>
4009 SDValue
AArch64TargetLowering::getAddrLarge(NodeTy
*N
, SelectionDAG
&DAG
,
4010 unsigned Flags
) const {
4011 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4013 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4014 const unsigned char MO_NC
= AArch64II::MO_NC
;
4016 AArch64ISD::WrapperLarge
, DL
, Ty
,
4017 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G3
| Flags
),
4018 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G2
| MO_NC
| Flags
),
4019 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G1
| MO_NC
| Flags
),
4020 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G0
| MO_NC
| Flags
));
4023 // (addlow (adrp %hi(sym)) %lo(sym))
4024 template <class NodeTy
>
4025 SDValue
AArch64TargetLowering::getAddr(NodeTy
*N
, SelectionDAG
&DAG
,
4026 unsigned Flags
) const {
4027 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4029 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4030 SDValue Hi
= getTargetNode(N
, Ty
, DAG
, AArch64II::MO_PAGE
| Flags
);
4031 SDValue Lo
= getTargetNode(N
, Ty
, DAG
,
4032 AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
| Flags
);
4033 SDValue ADRP
= DAG
.getNode(AArch64ISD::ADRP
, DL
, Ty
, Hi
);
4034 return DAG
.getNode(AArch64ISD::ADDlow
, DL
, Ty
, ADRP
, Lo
);
4038 template <class NodeTy
>
4039 SDValue
AArch64TargetLowering::getAddrTiny(NodeTy
*N
, SelectionDAG
&DAG
,
4040 unsigned Flags
) const {
4041 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4043 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4044 SDValue Sym
= getTargetNode(N
, Ty
, DAG
, Flags
);
4045 return DAG
.getNode(AArch64ISD::ADR
, DL
, Ty
, Sym
);
4048 SDValue
AArch64TargetLowering::LowerGlobalAddress(SDValue Op
,
4049 SelectionDAG
&DAG
) const {
4050 GlobalAddressSDNode
*GN
= cast
<GlobalAddressSDNode
>(Op
);
4051 const GlobalValue
*GV
= GN
->getGlobal();
4052 unsigned char OpFlags
=
4053 Subtarget
->ClassifyGlobalReference(GV
, getTargetMachine());
4055 if (OpFlags
!= AArch64II::MO_NO_FLAG
)
4056 assert(cast
<GlobalAddressSDNode
>(Op
)->getOffset() == 0 &&
4057 "unexpected offset in global node");
4059 // This also catches the large code model case for Darwin, and tiny code
4060 // model with got relocations.
4061 if ((OpFlags
& AArch64II::MO_GOT
) != 0) {
4062 return getGOT(GN
, DAG
, OpFlags
);
4066 if (getTargetMachine().getCodeModel() == CodeModel::Large
) {
4067 Result
= getAddrLarge(GN
, DAG
, OpFlags
);
4068 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
4069 Result
= getAddrTiny(GN
, DAG
, OpFlags
);
4071 Result
= getAddr(GN
, DAG
, OpFlags
);
4073 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4075 if (OpFlags
& (AArch64II::MO_DLLIMPORT
| AArch64II::MO_COFFSTUB
))
4076 Result
= DAG
.getLoad(PtrVT
, DL
, DAG
.getEntryNode(), Result
,
4077 MachinePointerInfo::getGOT(DAG
.getMachineFunction()));
4081 /// Convert a TLS address reference into the correct sequence of loads
4082 /// and calls to compute the variable's address (for Darwin, currently) and
4083 /// return an SDValue containing the final node.
4085 /// Darwin only has one TLS scheme which must be capable of dealing with the
4086 /// fully general situation, in the worst case. This means:
4087 /// + "extern __thread" declaration.
4088 /// + Defined in a possibly unknown dynamic library.
4090 /// The general system is that each __thread variable has a [3 x i64] descriptor
4091 /// which contains information used by the runtime to calculate the address. The
4092 /// only part of this the compiler needs to know about is the first xword, which
4093 /// contains a function pointer that must be called with the address of the
4094 /// entire descriptor in "x0".
4096 /// Since this descriptor may be in a different unit, in general even the
4097 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4099 /// adrp x0, _var@TLVPPAGE
4100 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4101 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4102 /// ; the function pointer
4103 /// blr x1 ; Uses descriptor address in x0
4104 /// ; Address of _var is now in x0.
4106 /// If the address of _var's descriptor *is* known to the linker, then it can
4107 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4108 /// a slight efficiency gain.
4110 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op
,
4111 SelectionDAG
&DAG
) const {
4112 assert(Subtarget
->isTargetDarwin() &&
4113 "This function expects a Darwin target");
4116 MVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4117 const GlobalValue
*GV
= cast
<GlobalAddressSDNode
>(Op
)->getGlobal();
4120 DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4121 SDValue DescAddr
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, TLVPAddr
);
4123 // The first entry in the descriptor is a function pointer that we must call
4124 // to obtain the address of the variable.
4125 SDValue Chain
= DAG
.getEntryNode();
4126 SDValue FuncTLVGet
= DAG
.getLoad(
4127 MVT::i64
, DL
, Chain
, DescAddr
,
4128 MachinePointerInfo::getGOT(DAG
.getMachineFunction()),
4129 /* Alignment = */ 8,
4130 MachineMemOperand::MONonTemporal
| MachineMemOperand::MOInvariant
|
4131 MachineMemOperand::MODereferenceable
);
4132 Chain
= FuncTLVGet
.getValue(1);
4134 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
4135 MFI
.setAdjustsStack(true);
4137 // TLS calls preserve all registers except those that absolutely must be
4138 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4140 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
4141 const uint32_t *Mask
= TRI
->getTLSCallPreservedMask();
4142 if (Subtarget
->hasCustomCallingConv())
4143 TRI
->UpdateCustomCallPreservedMask(DAG
.getMachineFunction(), &Mask
);
4145 // Finally, we can make the call. This is just a degenerate version of a
4146 // normal AArch64 call node: x0 takes the address of the descriptor, and
4147 // returns the address of the variable in this thread.
4148 Chain
= DAG
.getCopyToReg(Chain
, DL
, AArch64::X0
, DescAddr
, SDValue());
4150 DAG
.getNode(AArch64ISD::CALL
, DL
, DAG
.getVTList(MVT::Other
, MVT::Glue
),
4151 Chain
, FuncTLVGet
, DAG
.getRegister(AArch64::X0
, MVT::i64
),
4152 DAG
.getRegisterMask(Mask
), Chain
.getValue(1));
4153 return DAG
.getCopyFromReg(Chain
, DL
, AArch64::X0
, PtrVT
, Chain
.getValue(1));
4156 /// When accessing thread-local variables under either the general-dynamic or
4157 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4158 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4159 /// is a function pointer to carry out the resolution.
4161 /// The sequence is:
4162 /// adrp x0, :tlsdesc:var
4163 /// ldr x1, [x0, #:tlsdesc_lo12:var]
4164 /// add x0, x0, #:tlsdesc_lo12:var
4165 /// .tlsdesccall var
4167 /// (TPIDR_EL0 offset now in x0)
4169 /// The above sequence must be produced unscheduled, to enable the linker to
4170 /// optimize/relax this sequence.
4171 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4172 /// above sequence, and expanded really late in the compilation flow, to ensure
4173 /// the sequence is produced as per above.
4174 SDValue
AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr
,
4176 SelectionDAG
&DAG
) const {
4177 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4179 SDValue Chain
= DAG
.getEntryNode();
4180 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
4183 DAG
.getNode(AArch64ISD::TLSDESC_CALLSEQ
, DL
, NodeTys
, {Chain
, SymAddr
});
4184 SDValue Glue
= Chain
.getValue(1);
4186 return DAG
.getCopyFromReg(Chain
, DL
, AArch64::X0
, PtrVT
, Glue
);
4190 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op
,
4191 SelectionDAG
&DAG
) const {
4192 assert(Subtarget
->isTargetELF() && "This function expects an ELF target");
4193 if (getTargetMachine().getCodeModel() == CodeModel::Large
)
4194 report_fatal_error("ELF TLS only supported in small memory model");
4195 // Different choices can be made for the maximum size of the TLS area for a
4196 // module. For the small address model, the default TLS size is 16MiB and the
4197 // maximum TLS size is 4GiB.
4198 // FIXME: add -mtls-size command line option and make it control the 16MiB
4199 // vs. 4GiB code sequence generation.
4200 // FIXME: add tiny codemodel support. We currently generate the same code as
4201 // small, which may be larger than needed.
4202 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4204 TLSModel::Model Model
= getTargetMachine().getTLSModel(GA
->getGlobal());
4206 if (!EnableAArch64ELFLocalDynamicTLSGeneration
) {
4207 if (Model
== TLSModel::LocalDynamic
)
4208 Model
= TLSModel::GeneralDynamic
;
4212 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4214 const GlobalValue
*GV
= GA
->getGlobal();
4216 SDValue ThreadBase
= DAG
.getNode(AArch64ISD::THREAD_POINTER
, DL
, PtrVT
);
4218 if (Model
== TLSModel::LocalExec
) {
4219 SDValue HiVar
= DAG
.getTargetGlobalAddress(
4220 GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4221 SDValue LoVar
= DAG
.getTargetGlobalAddress(
4223 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4225 SDValue TPWithOff_lo
=
4226 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, ThreadBase
,
4228 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4231 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPWithOff_lo
,
4233 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4236 } else if (Model
== TLSModel::InitialExec
) {
4237 TPOff
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4238 TPOff
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, TPOff
);
4239 } else if (Model
== TLSModel::LocalDynamic
) {
4240 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4241 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4242 // the beginning of the module's TLS region, followed by a DTPREL offset
4245 // These accesses will need deduplicating if there's more than one.
4246 AArch64FunctionInfo
*MFI
=
4247 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
4248 MFI
->incNumLocalDynamicTLSAccesses();
4250 // The call needs a relocation too for linker relaxation. It doesn't make
4251 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4253 SDValue SymAddr
= DAG
.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT
,
4256 // Now we can calculate the offset from TPIDR_EL0 to this module's
4257 // thread-local area.
4258 TPOff
= LowerELFTLSDescCallSeq(SymAddr
, DL
, DAG
);
4260 // Now use :dtprel_whatever: operations to calculate this variable's offset
4261 // in its thread-storage area.
4262 SDValue HiVar
= DAG
.getTargetGlobalAddress(
4263 GV
, DL
, MVT::i64
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4264 SDValue LoVar
= DAG
.getTargetGlobalAddress(
4265 GV
, DL
, MVT::i64
, 0,
4266 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4268 TPOff
= SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPOff
, HiVar
,
4269 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4271 TPOff
= SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPOff
, LoVar
,
4272 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4274 } else if (Model
== TLSModel::GeneralDynamic
) {
4275 // The call needs a relocation too for linker relaxation. It doesn't make
4276 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4279 DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4281 // Finally we can make a call to calculate the offset from tpidr_el0.
4282 TPOff
= LowerELFTLSDescCallSeq(SymAddr
, DL
, DAG
);
4284 llvm_unreachable("Unsupported ELF TLS access model");
4286 return DAG
.getNode(ISD::ADD
, DL
, PtrVT
, ThreadBase
, TPOff
);
4290 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op
,
4291 SelectionDAG
&DAG
) const {
4292 assert(Subtarget
->isTargetWindows() && "Windows specific TLS lowering");
4294 SDValue Chain
= DAG
.getEntryNode();
4295 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4298 SDValue TEB
= DAG
.getRegister(AArch64::X18
, MVT::i64
);
4300 // Load the ThreadLocalStoragePointer from the TEB
4301 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4303 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, TEB
, DAG
.getIntPtrConstant(0x58, DL
));
4304 TLSArray
= DAG
.getLoad(PtrVT
, DL
, Chain
, TLSArray
, MachinePointerInfo());
4305 Chain
= TLSArray
.getValue(1);
4307 // Load the TLS index from the C runtime;
4308 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4309 // This also does the same as LOADgot, but using a generic i32 load,
4310 // while LOADgot only loads i64.
4311 SDValue TLSIndexHi
=
4312 DAG
.getTargetExternalSymbol("_tls_index", PtrVT
, AArch64II::MO_PAGE
);
4313 SDValue TLSIndexLo
= DAG
.getTargetExternalSymbol(
4314 "_tls_index", PtrVT
, AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4315 SDValue ADRP
= DAG
.getNode(AArch64ISD::ADRP
, DL
, PtrVT
, TLSIndexHi
);
4317 DAG
.getNode(AArch64ISD::ADDlow
, DL
, PtrVT
, ADRP
, TLSIndexLo
);
4318 TLSIndex
= DAG
.getLoad(MVT::i32
, DL
, Chain
, TLSIndex
, MachinePointerInfo());
4319 Chain
= TLSIndex
.getValue(1);
4321 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4322 // offset into the TLSArray.
4323 TLSIndex
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, PtrVT
, TLSIndex
);
4324 SDValue Slot
= DAG
.getNode(ISD::SHL
, DL
, PtrVT
, TLSIndex
,
4325 DAG
.getConstant(3, DL
, PtrVT
));
4326 SDValue TLS
= DAG
.getLoad(PtrVT
, DL
, Chain
,
4327 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, TLSArray
, Slot
),
4328 MachinePointerInfo());
4329 Chain
= TLS
.getValue(1);
4331 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4332 const GlobalValue
*GV
= GA
->getGlobal();
4333 SDValue TGAHi
= DAG
.getTargetGlobalAddress(
4334 GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4335 SDValue TGALo
= DAG
.getTargetGlobalAddress(
4337 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4339 // Add the offset from the start of the .tls section (section base).
4341 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TLS
, TGAHi
,
4342 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4344 Addr
= DAG
.getNode(AArch64ISD::ADDlow
, DL
, PtrVT
, Addr
, TGALo
);
4348 SDValue
AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op
,
4349 SelectionDAG
&DAG
) const {
4350 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4351 if (DAG
.getTarget().useEmulatedTLS())
4352 return LowerToTLSEmulatedModel(GA
, DAG
);
4354 if (Subtarget
->isTargetDarwin())
4355 return LowerDarwinGlobalTLSAddress(Op
, DAG
);
4356 if (Subtarget
->isTargetELF())
4357 return LowerELFGlobalTLSAddress(Op
, DAG
);
4358 if (Subtarget
->isTargetWindows())
4359 return LowerWindowsGlobalTLSAddress(Op
, DAG
);
4361 llvm_unreachable("Unexpected platform trying to use TLS");
4364 SDValue
AArch64TargetLowering::LowerBR_CC(SDValue Op
, SelectionDAG
&DAG
) const {
4365 SDValue Chain
= Op
.getOperand(0);
4366 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(1))->get();
4367 SDValue LHS
= Op
.getOperand(2);
4368 SDValue RHS
= Op
.getOperand(3);
4369 SDValue Dest
= Op
.getOperand(4);
4372 MachineFunction
&MF
= DAG
.getMachineFunction();
4373 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4374 // will not be produced, as they are conditional branch instructions that do
4376 bool ProduceNonFlagSettingCondBr
=
4377 !MF
.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening
);
4379 // Handle f128 first, since lowering it will result in comparing the return
4380 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4381 // is expecting to deal with.
4382 if (LHS
.getValueType() == MVT::f128
) {
4383 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
);
4385 // If softenSetCCOperands returned a scalar, we need to compare the result
4386 // against zero to select between true and false values.
4387 if (!RHS
.getNode()) {
4388 RHS
= DAG
.getConstant(0, dl
, LHS
.getValueType());
4393 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4395 if (isOverflowIntrOpRes(LHS
) && isOneConstant(RHS
) &&
4396 (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
4397 // Only lower legal XALUO ops.
4398 if (!DAG
.getTargetLoweringInfo().isTypeLegal(LHS
->getValueType(0)))
4401 // The actual operation with overflow check.
4402 AArch64CC::CondCode OFCC
;
4403 SDValue Value
, Overflow
;
4404 std::tie(Value
, Overflow
) = getAArch64XALUOOp(OFCC
, LHS
.getValue(0), DAG
);
4406 if (CC
== ISD::SETNE
)
4407 OFCC
= getInvertedCondCode(OFCC
);
4408 SDValue CCVal
= DAG
.getConstant(OFCC
, dl
, MVT::i32
);
4410 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CCVal
,
4414 if (LHS
.getValueType().isInteger()) {
4415 assert((LHS
.getValueType() == RHS
.getValueType()) &&
4416 (LHS
.getValueType() == MVT::i32
|| LHS
.getValueType() == MVT::i64
));
4418 // If the RHS of the comparison is zero, we can potentially fold this
4419 // to a specialized branch.
4420 const ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(RHS
);
4421 if (RHSC
&& RHSC
->getZExtValue() == 0 && ProduceNonFlagSettingCondBr
) {
4422 if (CC
== ISD::SETEQ
) {
4423 // See if we can use a TBZ to fold in an AND as well.
4424 // TBZ has a smaller branch displacement than CBZ. If the offset is
4425 // out of bounds, a late MI-layer pass rewrites branches.
4426 // 403.gcc is an example that hits this case.
4427 if (LHS
.getOpcode() == ISD::AND
&&
4428 isa
<ConstantSDNode
>(LHS
.getOperand(1)) &&
4429 isPowerOf2_64(LHS
.getConstantOperandVal(1))) {
4430 SDValue Test
= LHS
.getOperand(0);
4431 uint64_t Mask
= LHS
.getConstantOperandVal(1);
4432 return DAG
.getNode(AArch64ISD::TBZ
, dl
, MVT::Other
, Chain
, Test
,
4433 DAG
.getConstant(Log2_64(Mask
), dl
, MVT::i64
),
4437 return DAG
.getNode(AArch64ISD::CBZ
, dl
, MVT::Other
, Chain
, LHS
, Dest
);
4438 } else if (CC
== ISD::SETNE
) {
4439 // See if we can use a TBZ to fold in an AND as well.
4440 // TBZ has a smaller branch displacement than CBZ. If the offset is
4441 // out of bounds, a late MI-layer pass rewrites branches.
4442 // 403.gcc is an example that hits this case.
4443 if (LHS
.getOpcode() == ISD::AND
&&
4444 isa
<ConstantSDNode
>(LHS
.getOperand(1)) &&
4445 isPowerOf2_64(LHS
.getConstantOperandVal(1))) {
4446 SDValue Test
= LHS
.getOperand(0);
4447 uint64_t Mask
= LHS
.getConstantOperandVal(1);
4448 return DAG
.getNode(AArch64ISD::TBNZ
, dl
, MVT::Other
, Chain
, Test
,
4449 DAG
.getConstant(Log2_64(Mask
), dl
, MVT::i64
),
4453 return DAG
.getNode(AArch64ISD::CBNZ
, dl
, MVT::Other
, Chain
, LHS
, Dest
);
4454 } else if (CC
== ISD::SETLT
&& LHS
.getOpcode() != ISD::AND
) {
4455 // Don't combine AND since emitComparison converts the AND to an ANDS
4456 // (a.k.a. TST) and the test in the test bit and branch instruction
4457 // becomes redundant. This would also increase register pressure.
4458 uint64_t Mask
= LHS
.getValueSizeInBits() - 1;
4459 return DAG
.getNode(AArch64ISD::TBNZ
, dl
, MVT::Other
, Chain
, LHS
,
4460 DAG
.getConstant(Mask
, dl
, MVT::i64
), Dest
);
4463 if (RHSC
&& RHSC
->getSExtValue() == -1 && CC
== ISD::SETGT
&&
4464 LHS
.getOpcode() != ISD::AND
&& ProduceNonFlagSettingCondBr
) {
4465 // Don't combine AND since emitComparison converts the AND to an ANDS
4466 // (a.k.a. TST) and the test in the test bit and branch instruction
4467 // becomes redundant. This would also increase register pressure.
4468 uint64_t Mask
= LHS
.getValueSizeInBits() - 1;
4469 return DAG
.getNode(AArch64ISD::TBZ
, dl
, MVT::Other
, Chain
, LHS
,
4470 DAG
.getConstant(Mask
, dl
, MVT::i64
), Dest
);
4474 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
4475 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CCVal
,
4479 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4480 LHS
.getValueType() == MVT::f64
);
4482 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4483 // clean. Some of them require two branches to implement.
4484 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4485 AArch64CC::CondCode CC1
, CC2
;
4486 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4487 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4489 DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CC1Val
, Cmp
);
4490 if (CC2
!= AArch64CC::AL
) {
4491 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
4492 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, BR1
, Dest
, CC2Val
,
4499 SDValue
AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op
,
4500 SelectionDAG
&DAG
) const {
4501 EVT VT
= Op
.getValueType();
4504 SDValue In1
= Op
.getOperand(0);
4505 SDValue In2
= Op
.getOperand(1);
4506 EVT SrcVT
= In2
.getValueType();
4508 if (SrcVT
.bitsLT(VT
))
4509 In2
= DAG
.getNode(ISD::FP_EXTEND
, DL
, VT
, In2
);
4510 else if (SrcVT
.bitsGT(VT
))
4511 In2
= DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, In2
, DAG
.getIntPtrConstant(0, DL
));
4515 SDValue VecVal1
, VecVal2
;
4517 auto setVecVal
= [&] (int Idx
) {
4518 if (!VT
.isVector()) {
4519 VecVal1
= DAG
.getTargetInsertSubreg(Idx
, DL
, VecVT
,
4520 DAG
.getUNDEF(VecVT
), In1
);
4521 VecVal2
= DAG
.getTargetInsertSubreg(Idx
, DL
, VecVT
,
4522 DAG
.getUNDEF(VecVT
), In2
);
4524 VecVal1
= DAG
.getNode(ISD::BITCAST
, DL
, VecVT
, In1
);
4525 VecVal2
= DAG
.getNode(ISD::BITCAST
, DL
, VecVT
, In2
);
4529 if (VT
== MVT::f32
|| VT
== MVT::v2f32
|| VT
== MVT::v4f32
) {
4530 VecVT
= (VT
== MVT::v2f32
? MVT::v2i32
: MVT::v4i32
);
4531 EltMask
= 0x80000000ULL
;
4532 setVecVal(AArch64::ssub
);
4533 } else if (VT
== MVT::f64
|| VT
== MVT::v2f64
) {
4536 // We want to materialize a mask with the high bit set, but the AdvSIMD
4537 // immediate moves cannot materialize that in a single instruction for
4538 // 64-bit elements. Instead, materialize zero and then negate it.
4541 setVecVal(AArch64::dsub
);
4542 } else if (VT
== MVT::f16
|| VT
== MVT::v4f16
|| VT
== MVT::v8f16
) {
4543 VecVT
= (VT
== MVT::v4f16
? MVT::v4i16
: MVT::v8i16
);
4544 EltMask
= 0x8000ULL
;
4545 setVecVal(AArch64::hsub
);
4547 llvm_unreachable("Invalid type for copysign!");
4550 SDValue BuildVec
= DAG
.getConstant(EltMask
, DL
, VecVT
);
4552 // If we couldn't materialize the mask above, then the mask vector will be
4553 // the zero vector, and we need to negate it here.
4554 if (VT
== MVT::f64
|| VT
== MVT::v2f64
) {
4555 BuildVec
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2f64
, BuildVec
);
4556 BuildVec
= DAG
.getNode(ISD::FNEG
, DL
, MVT::v2f64
, BuildVec
);
4557 BuildVec
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2i64
, BuildVec
);
4561 DAG
.getNode(AArch64ISD::BIT
, DL
, VecVT
, VecVal1
, VecVal2
, BuildVec
);
4564 return DAG
.getTargetExtractSubreg(AArch64::hsub
, DL
, VT
, Sel
);
4566 return DAG
.getTargetExtractSubreg(AArch64::ssub
, DL
, VT
, Sel
);
4567 else if (VT
== MVT::f64
)
4568 return DAG
.getTargetExtractSubreg(AArch64::dsub
, DL
, VT
, Sel
);
4570 return DAG
.getNode(ISD::BITCAST
, DL
, VT
, Sel
);
4573 SDValue
AArch64TargetLowering::LowerCTPOP(SDValue Op
, SelectionDAG
&DAG
) const {
4574 if (DAG
.getMachineFunction().getFunction().hasFnAttribute(
4575 Attribute::NoImplicitFloat
))
4578 if (!Subtarget
->hasNEON())
4581 // While there is no integer popcount instruction, it can
4582 // be more efficiently lowered to the following sequence that uses
4583 // AdvSIMD registers/instructions as long as the copies to/from
4584 // the AdvSIMD registers are cheap.
4585 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4586 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4587 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4588 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4589 SDValue Val
= Op
.getOperand(0);
4591 EVT VT
= Op
.getValueType();
4593 if (VT
== MVT::i32
|| VT
== MVT::i64
) {
4595 Val
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i64
, Val
);
4596 Val
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v8i8
, Val
);
4598 SDValue CtPop
= DAG
.getNode(ISD::CTPOP
, DL
, MVT::v8i8
, Val
);
4599 SDValue UaddLV
= DAG
.getNode(
4600 ISD::INTRINSIC_WO_CHAIN
, DL
, MVT::i32
,
4601 DAG
.getConstant(Intrinsic::aarch64_neon_uaddlv
, DL
, MVT::i32
), CtPop
);
4604 UaddLV
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i64
, UaddLV
);
4608 assert((VT
== MVT::v1i64
|| VT
== MVT::v2i64
|| VT
== MVT::v2i32
||
4609 VT
== MVT::v4i32
|| VT
== MVT::v4i16
|| VT
== MVT::v8i16
) &&
4610 "Unexpected type for custom ctpop lowering");
4612 EVT VT8Bit
= VT
.is64BitVector() ? MVT::v8i8
: MVT::v16i8
;
4613 Val
= DAG
.getBitcast(VT8Bit
, Val
);
4614 Val
= DAG
.getNode(ISD::CTPOP
, DL
, VT8Bit
, Val
);
4616 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4617 unsigned EltSize
= 8;
4618 unsigned NumElts
= VT
.is64BitVector() ? 8 : 16;
4619 while (EltSize
!= VT
.getScalarSizeInBits()) {
4622 MVT WidenVT
= MVT::getVectorVT(MVT::getIntegerVT(EltSize
), NumElts
);
4624 ISD::INTRINSIC_WO_CHAIN
, DL
, WidenVT
,
4625 DAG
.getConstant(Intrinsic::aarch64_neon_uaddlp
, DL
, MVT::i32
), Val
);
4631 SDValue
AArch64TargetLowering::LowerSETCC(SDValue Op
, SelectionDAG
&DAG
) const {
4633 if (Op
.getValueType().isVector())
4634 return LowerVSETCC(Op
, DAG
);
4636 SDValue LHS
= Op
.getOperand(0);
4637 SDValue RHS
= Op
.getOperand(1);
4638 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
4641 // We chose ZeroOrOneBooleanContents, so use zero and one.
4642 EVT VT
= Op
.getValueType();
4643 SDValue TVal
= DAG
.getConstant(1, dl
, VT
);
4644 SDValue FVal
= DAG
.getConstant(0, dl
, VT
);
4646 // Handle f128 first, since one possible outcome is a normal integer
4647 // comparison which gets picked up by the next if statement.
4648 if (LHS
.getValueType() == MVT::f128
) {
4649 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
);
4651 // If softenSetCCOperands returned a scalar, use it.
4652 if (!RHS
.getNode()) {
4653 assert(LHS
.getValueType() == Op
.getValueType() &&
4654 "Unexpected setcc expansion!");
4659 if (LHS
.getValueType().isInteger()) {
4662 getAArch64Cmp(LHS
, RHS
, ISD::getSetCCInverse(CC
, true), CCVal
, DAG
, dl
);
4664 // Note that we inverted the condition above, so we reverse the order of
4665 // the true and false operands here. This will allow the setcc to be
4666 // matched to a single CSINC instruction.
4667 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, FVal
, TVal
, CCVal
, Cmp
);
4670 // Now we know we're dealing with FP values.
4671 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4672 LHS
.getValueType() == MVT::f64
);
4674 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4675 // and do the comparison.
4676 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4678 AArch64CC::CondCode CC1
, CC2
;
4679 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4680 if (CC2
== AArch64CC::AL
) {
4681 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC
, false), CC1
, CC2
);
4682 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4684 // Note that we inverted the condition above, so we reverse the order of
4685 // the true and false operands here. This will allow the setcc to be
4686 // matched to a single CSINC instruction.
4687 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, FVal
, TVal
, CC1Val
, Cmp
);
4689 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4690 // totally clean. Some of them require two CSELs to implement. As is in
4691 // this case, we emit the first CSEL and then emit a second using the output
4692 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4694 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4695 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4697 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, FVal
, CC1Val
, Cmp
);
4699 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
4700 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, CS1
, CC2Val
, Cmp
);
4704 SDValue
AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC
, SDValue LHS
,
4705 SDValue RHS
, SDValue TVal
,
4706 SDValue FVal
, const SDLoc
&dl
,
4707 SelectionDAG
&DAG
) const {
4708 // Handle f128 first, because it will result in a comparison of some RTLIB
4709 // call result against zero.
4710 if (LHS
.getValueType() == MVT::f128
) {
4711 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
);
4713 // If softenSetCCOperands returned a scalar, we need to compare the result
4714 // against zero to select between true and false values.
4715 if (!RHS
.getNode()) {
4716 RHS
= DAG
.getConstant(0, dl
, LHS
.getValueType());
4721 // Also handle f16, for which we need to do a f32 comparison.
4722 if (LHS
.getValueType() == MVT::f16
&& !Subtarget
->hasFullFP16()) {
4723 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, LHS
);
4724 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, RHS
);
4727 // Next, handle integers.
4728 if (LHS
.getValueType().isInteger()) {
4729 assert((LHS
.getValueType() == RHS
.getValueType()) &&
4730 (LHS
.getValueType() == MVT::i32
|| LHS
.getValueType() == MVT::i64
));
4732 unsigned Opcode
= AArch64ISD::CSEL
;
4734 // If both the TVal and the FVal are constants, see if we can swap them in
4735 // order to for a CSINV or CSINC out of them.
4736 ConstantSDNode
*CFVal
= dyn_cast
<ConstantSDNode
>(FVal
);
4737 ConstantSDNode
*CTVal
= dyn_cast
<ConstantSDNode
>(TVal
);
4739 if (CTVal
&& CFVal
&& CTVal
->isAllOnesValue() && CFVal
->isNullValue()) {
4740 std::swap(TVal
, FVal
);
4741 std::swap(CTVal
, CFVal
);
4742 CC
= ISD::getSetCCInverse(CC
, true);
4743 } else if (CTVal
&& CFVal
&& CTVal
->isOne() && CFVal
->isNullValue()) {
4744 std::swap(TVal
, FVal
);
4745 std::swap(CTVal
, CFVal
);
4746 CC
= ISD::getSetCCInverse(CC
, true);
4747 } else if (TVal
.getOpcode() == ISD::XOR
) {
4748 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4749 // with a CSINV rather than a CSEL.
4750 if (isAllOnesConstant(TVal
.getOperand(1))) {
4751 std::swap(TVal
, FVal
);
4752 std::swap(CTVal
, CFVal
);
4753 CC
= ISD::getSetCCInverse(CC
, true);
4755 } else if (TVal
.getOpcode() == ISD::SUB
) {
4756 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4757 // that we can match with a CSNEG rather than a CSEL.
4758 if (isNullConstant(TVal
.getOperand(0))) {
4759 std::swap(TVal
, FVal
);
4760 std::swap(CTVal
, CFVal
);
4761 CC
= ISD::getSetCCInverse(CC
, true);
4763 } else if (CTVal
&& CFVal
) {
4764 const int64_t TrueVal
= CTVal
->getSExtValue();
4765 const int64_t FalseVal
= CFVal
->getSExtValue();
4768 // If both TVal and FVal are constants, see if FVal is the
4769 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4770 // instead of a CSEL in that case.
4771 if (TrueVal
== ~FalseVal
) {
4772 Opcode
= AArch64ISD::CSINV
;
4773 } else if (TrueVal
== -FalseVal
) {
4774 Opcode
= AArch64ISD::CSNEG
;
4775 } else if (TVal
.getValueType() == MVT::i32
) {
4776 // If our operands are only 32-bit wide, make sure we use 32-bit
4777 // arithmetic for the check whether we can use CSINC. This ensures that
4778 // the addition in the check will wrap around properly in case there is
4779 // an overflow (which would not be the case if we do the check with
4780 // 64-bit arithmetic).
4781 const uint32_t TrueVal32
= CTVal
->getZExtValue();
4782 const uint32_t FalseVal32
= CFVal
->getZExtValue();
4784 if ((TrueVal32
== FalseVal32
+ 1) || (TrueVal32
+ 1 == FalseVal32
)) {
4785 Opcode
= AArch64ISD::CSINC
;
4787 if (TrueVal32
> FalseVal32
) {
4791 // 64-bit check whether we can use CSINC.
4792 } else if ((TrueVal
== FalseVal
+ 1) || (TrueVal
+ 1 == FalseVal
)) {
4793 Opcode
= AArch64ISD::CSINC
;
4795 if (TrueVal
> FalseVal
) {
4800 // Swap TVal and FVal if necessary.
4802 std::swap(TVal
, FVal
);
4803 std::swap(CTVal
, CFVal
);
4804 CC
= ISD::getSetCCInverse(CC
, true);
4807 if (Opcode
!= AArch64ISD::CSEL
) {
4808 // Drop FVal since we can get its value by simply inverting/negating
4814 // Avoid materializing a constant when possible by reusing a known value in
4815 // a register. However, don't perform this optimization if the known value
4816 // is one, zero or negative one in the case of a CSEL. We can always
4817 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4818 // FVal, respectively.
4819 ConstantSDNode
*RHSVal
= dyn_cast
<ConstantSDNode
>(RHS
);
4820 if (Opcode
== AArch64ISD::CSEL
&& RHSVal
&& !RHSVal
->isOne() &&
4821 !RHSVal
->isNullValue() && !RHSVal
->isAllOnesValue()) {
4822 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
4823 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4824 // "a != C ? x : a" to avoid materializing C.
4825 if (CTVal
&& CTVal
== RHSVal
&& AArch64CC
== AArch64CC::EQ
)
4827 else if (CFVal
&& CFVal
== RHSVal
&& AArch64CC
== AArch64CC::NE
)
4829 } else if (Opcode
== AArch64ISD::CSNEG
&& RHSVal
&& RHSVal
->isOne()) {
4830 assert (CTVal
&& CFVal
&& "Expected constant operands for CSNEG.");
4831 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4832 // avoid materializing C.
4833 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
4834 if (CTVal
== RHSVal
&& AArch64CC
== AArch64CC::EQ
) {
4835 Opcode
= AArch64ISD::CSINV
;
4837 FVal
= DAG
.getConstant(0, dl
, FVal
.getValueType());
4842 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
4843 EVT VT
= TVal
.getValueType();
4844 return DAG
.getNode(Opcode
, dl
, VT
, TVal
, FVal
, CCVal
, Cmp
);
4847 // Now we know we're dealing with FP values.
4848 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4849 LHS
.getValueType() == MVT::f64
);
4850 assert(LHS
.getValueType() == RHS
.getValueType());
4851 EVT VT
= TVal
.getValueType();
4852 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4854 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4855 // clean. Some of them require two CSELs to implement.
4856 AArch64CC::CondCode CC1
, CC2
;
4857 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4859 if (DAG
.getTarget().Options
.UnsafeFPMath
) {
4860 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4861 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4862 ConstantFPSDNode
*RHSVal
= dyn_cast
<ConstantFPSDNode
>(RHS
);
4863 if (RHSVal
&& RHSVal
->isZero()) {
4864 ConstantFPSDNode
*CFVal
= dyn_cast
<ConstantFPSDNode
>(FVal
);
4865 ConstantFPSDNode
*CTVal
= dyn_cast
<ConstantFPSDNode
>(TVal
);
4867 if ((CC
== ISD::SETEQ
|| CC
== ISD::SETOEQ
|| CC
== ISD::SETUEQ
) &&
4868 CTVal
&& CTVal
->isZero() && TVal
.getValueType() == LHS
.getValueType())
4870 else if ((CC
== ISD::SETNE
|| CC
== ISD::SETONE
|| CC
== ISD::SETUNE
) &&
4871 CFVal
&& CFVal
->isZero() &&
4872 FVal
.getValueType() == LHS
.getValueType())
4877 // Emit first, and possibly only, CSEL.
4878 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4879 SDValue CS1
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, FVal
, CC1Val
, Cmp
);
4881 // If we need a second CSEL, emit it, using the output of the first as the
4882 // RHS. We're effectively OR'ing the two CC's together.
4883 if (CC2
!= AArch64CC::AL
) {
4884 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
4885 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, CS1
, CC2Val
, Cmp
);
4888 // Otherwise, return the output of the first CSEL.
4892 SDValue
AArch64TargetLowering::LowerSELECT_CC(SDValue Op
,
4893 SelectionDAG
&DAG
) const {
4894 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(4))->get();
4895 SDValue LHS
= Op
.getOperand(0);
4896 SDValue RHS
= Op
.getOperand(1);
4897 SDValue TVal
= Op
.getOperand(2);
4898 SDValue FVal
= Op
.getOperand(3);
4900 return LowerSELECT_CC(CC
, LHS
, RHS
, TVal
, FVal
, DL
, DAG
);
4903 SDValue
AArch64TargetLowering::LowerSELECT(SDValue Op
,
4904 SelectionDAG
&DAG
) const {
4905 SDValue CCVal
= Op
->getOperand(0);
4906 SDValue TVal
= Op
->getOperand(1);
4907 SDValue FVal
= Op
->getOperand(2);
4910 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4912 if (isOverflowIntrOpRes(CCVal
)) {
4913 // Only lower legal XALUO ops.
4914 if (!DAG
.getTargetLoweringInfo().isTypeLegal(CCVal
->getValueType(0)))
4917 AArch64CC::CondCode OFCC
;
4918 SDValue Value
, Overflow
;
4919 std::tie(Value
, Overflow
) = getAArch64XALUOOp(OFCC
, CCVal
.getValue(0), DAG
);
4920 SDValue CCVal
= DAG
.getConstant(OFCC
, DL
, MVT::i32
);
4922 return DAG
.getNode(AArch64ISD::CSEL
, DL
, Op
.getValueType(), TVal
, FVal
,
4926 // Lower it the same way as we would lower a SELECT_CC node.
4929 if (CCVal
.getOpcode() == ISD::SETCC
) {
4930 LHS
= CCVal
.getOperand(0);
4931 RHS
= CCVal
.getOperand(1);
4932 CC
= cast
<CondCodeSDNode
>(CCVal
->getOperand(2))->get();
4935 RHS
= DAG
.getConstant(0, DL
, CCVal
.getValueType());
4938 return LowerSELECT_CC(CC
, LHS
, RHS
, TVal
, FVal
, DL
, DAG
);
4941 SDValue
AArch64TargetLowering::LowerJumpTable(SDValue Op
,
4942 SelectionDAG
&DAG
) const {
4943 // Jump table entries as PC relative offsets. No additional tweaking
4944 // is necessary here. Just get the address of the jump table.
4945 JumpTableSDNode
*JT
= cast
<JumpTableSDNode
>(Op
);
4947 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
4948 !Subtarget
->isTargetMachO()) {
4949 return getAddrLarge(JT
, DAG
);
4950 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
4951 return getAddrTiny(JT
, DAG
);
4953 return getAddr(JT
, DAG
);
4956 SDValue
AArch64TargetLowering::LowerBR_JT(SDValue Op
,
4957 SelectionDAG
&DAG
) const {
4958 // Jump table entries as PC relative offsets. No additional tweaking
4959 // is necessary here. Just get the address of the jump table.
4961 SDValue JT
= Op
.getOperand(1);
4962 SDValue Entry
= Op
.getOperand(2);
4963 int JTI
= cast
<JumpTableSDNode
>(JT
.getNode())->getIndex();
4966 DAG
.getMachineNode(AArch64::JumpTableDest32
, DL
, MVT::i64
, MVT::i64
, JT
,
4967 Entry
, DAG
.getTargetJumpTable(JTI
, MVT::i32
));
4968 return DAG
.getNode(ISD::BRIND
, DL
, MVT::Other
, Op
.getOperand(0),
4972 SDValue
AArch64TargetLowering::LowerConstantPool(SDValue Op
,
4973 SelectionDAG
&DAG
) const {
4974 ConstantPoolSDNode
*CP
= cast
<ConstantPoolSDNode
>(Op
);
4976 if (getTargetMachine().getCodeModel() == CodeModel::Large
) {
4977 // Use the GOT for the large code model on iOS.
4978 if (Subtarget
->isTargetMachO()) {
4979 return getGOT(CP
, DAG
);
4981 return getAddrLarge(CP
, DAG
);
4982 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
4983 return getAddrTiny(CP
, DAG
);
4985 return getAddr(CP
, DAG
);
4989 SDValue
AArch64TargetLowering::LowerBlockAddress(SDValue Op
,
4990 SelectionDAG
&DAG
) const {
4991 BlockAddressSDNode
*BA
= cast
<BlockAddressSDNode
>(Op
);
4992 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
4993 !Subtarget
->isTargetMachO()) {
4994 return getAddrLarge(BA
, DAG
);
4995 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
4996 return getAddrTiny(BA
, DAG
);
4998 return getAddr(BA
, DAG
);
5001 SDValue
AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op
,
5002 SelectionDAG
&DAG
) const {
5003 AArch64FunctionInfo
*FuncInfo
=
5004 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
5007 SDValue FR
= DAG
.getFrameIndex(FuncInfo
->getVarArgsStackIndex(),
5008 getPointerTy(DAG
.getDataLayout()));
5009 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5010 return DAG
.getStore(Op
.getOperand(0), DL
, FR
, Op
.getOperand(1),
5011 MachinePointerInfo(SV
));
5014 SDValue
AArch64TargetLowering::LowerWin64_VASTART(SDValue Op
,
5015 SelectionDAG
&DAG
) const {
5016 AArch64FunctionInfo
*FuncInfo
=
5017 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
5020 SDValue FR
= DAG
.getFrameIndex(FuncInfo
->getVarArgsGPRSize() > 0
5021 ? FuncInfo
->getVarArgsGPRIndex()
5022 : FuncInfo
->getVarArgsStackIndex(),
5023 getPointerTy(DAG
.getDataLayout()));
5024 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5025 return DAG
.getStore(Op
.getOperand(0), DL
, FR
, Op
.getOperand(1),
5026 MachinePointerInfo(SV
));
5029 SDValue
AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op
,
5030 SelectionDAG
&DAG
) const {
5031 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5032 // Standard, section B.3.
5033 MachineFunction
&MF
= DAG
.getMachineFunction();
5034 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
5035 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
5038 SDValue Chain
= Op
.getOperand(0);
5039 SDValue VAList
= Op
.getOperand(1);
5040 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5041 SmallVector
<SDValue
, 4> MemOps
;
5043 // void *__stack at offset 0
5044 SDValue Stack
= DAG
.getFrameIndex(FuncInfo
->getVarArgsStackIndex(), PtrVT
);
5045 MemOps
.push_back(DAG
.getStore(Chain
, DL
, Stack
, VAList
,
5046 MachinePointerInfo(SV
), /* Alignment = */ 8));
5048 // void *__gr_top at offset 8
5049 int GPRSize
= FuncInfo
->getVarArgsGPRSize();
5051 SDValue GRTop
, GRTopAddr
;
5054 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(8, DL
, PtrVT
));
5056 GRTop
= DAG
.getFrameIndex(FuncInfo
->getVarArgsGPRIndex(), PtrVT
);
5057 GRTop
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, GRTop
,
5058 DAG
.getConstant(GPRSize
, DL
, PtrVT
));
5060 MemOps
.push_back(DAG
.getStore(Chain
, DL
, GRTop
, GRTopAddr
,
5061 MachinePointerInfo(SV
, 8),
5062 /* Alignment = */ 8));
5065 // void *__vr_top at offset 16
5066 int FPRSize
= FuncInfo
->getVarArgsFPRSize();
5068 SDValue VRTop
, VRTopAddr
;
5069 VRTopAddr
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5070 DAG
.getConstant(16, DL
, PtrVT
));
5072 VRTop
= DAG
.getFrameIndex(FuncInfo
->getVarArgsFPRIndex(), PtrVT
);
5073 VRTop
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VRTop
,
5074 DAG
.getConstant(FPRSize
, DL
, PtrVT
));
5076 MemOps
.push_back(DAG
.getStore(Chain
, DL
, VRTop
, VRTopAddr
,
5077 MachinePointerInfo(SV
, 16),
5078 /* Alignment = */ 8));
5081 // int __gr_offs at offset 24
5082 SDValue GROffsAddr
=
5083 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(24, DL
, PtrVT
));
5084 MemOps
.push_back(DAG
.getStore(
5085 Chain
, DL
, DAG
.getConstant(-GPRSize
, DL
, MVT::i32
), GROffsAddr
,
5086 MachinePointerInfo(SV
, 24), /* Alignment = */ 4));
5088 // int __vr_offs at offset 28
5089 SDValue VROffsAddr
=
5090 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(28, DL
, PtrVT
));
5091 MemOps
.push_back(DAG
.getStore(
5092 Chain
, DL
, DAG
.getConstant(-FPRSize
, DL
, MVT::i32
), VROffsAddr
,
5093 MachinePointerInfo(SV
, 28), /* Alignment = */ 4));
5095 return DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOps
);
5098 SDValue
AArch64TargetLowering::LowerVASTART(SDValue Op
,
5099 SelectionDAG
&DAG
) const {
5100 MachineFunction
&MF
= DAG
.getMachineFunction();
5102 if (Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv()))
5103 return LowerWin64_VASTART(Op
, DAG
);
5104 else if (Subtarget
->isTargetDarwin())
5105 return LowerDarwin_VASTART(Op
, DAG
);
5107 return LowerAAPCS_VASTART(Op
, DAG
);
5110 SDValue
AArch64TargetLowering::LowerVACOPY(SDValue Op
,
5111 SelectionDAG
&DAG
) const {
5112 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5115 unsigned VaListSize
=
5116 Subtarget
->isTargetDarwin() || Subtarget
->isTargetWindows() ? 8 : 32;
5117 const Value
*DestSV
= cast
<SrcValueSDNode
>(Op
.getOperand(3))->getValue();
5118 const Value
*SrcSV
= cast
<SrcValueSDNode
>(Op
.getOperand(4))->getValue();
5120 return DAG
.getMemcpy(Op
.getOperand(0), DL
, Op
.getOperand(1),
5122 DAG
.getConstant(VaListSize
, DL
, MVT::i32
),
5123 8, false, false, false, MachinePointerInfo(DestSV
),
5124 MachinePointerInfo(SrcSV
));
5127 SDValue
AArch64TargetLowering::LowerVAARG(SDValue Op
, SelectionDAG
&DAG
) const {
5128 assert(Subtarget
->isTargetDarwin() &&
5129 "automatic va_arg instruction only works on Darwin");
5131 const Value
*V
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5132 EVT VT
= Op
.getValueType();
5134 SDValue Chain
= Op
.getOperand(0);
5135 SDValue Addr
= Op
.getOperand(1);
5136 unsigned Align
= Op
.getConstantOperandVal(3);
5137 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
5139 SDValue VAList
= DAG
.getLoad(PtrVT
, DL
, Chain
, Addr
, MachinePointerInfo(V
));
5140 Chain
= VAList
.getValue(1);
5143 assert(((Align
& (Align
- 1)) == 0) && "Expected Align to be a power of 2");
5144 VAList
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5145 DAG
.getConstant(Align
- 1, DL
, PtrVT
));
5146 VAList
= DAG
.getNode(ISD::AND
, DL
, PtrVT
, VAList
,
5147 DAG
.getConstant(-(int64_t)Align
, DL
, PtrVT
));
5150 Type
*ArgTy
= VT
.getTypeForEVT(*DAG
.getContext());
5151 uint64_t ArgSize
= DAG
.getDataLayout().getTypeAllocSize(ArgTy
);
5153 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5154 // up to 64 bits. At the very least, we have to increase the striding of the
5155 // vaargs list to match this, and for FP values we need to introduce
5156 // FP_ROUND nodes as well.
5157 if (VT
.isInteger() && !VT
.isVector())
5159 bool NeedFPTrunc
= false;
5160 if (VT
.isFloatingPoint() && !VT
.isVector() && VT
!= MVT::f64
) {
5165 // Increment the pointer, VAList, to the next vaarg
5166 SDValue VANext
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5167 DAG
.getConstant(ArgSize
, DL
, PtrVT
));
5168 // Store the incremented VAList to the legalized pointer
5170 DAG
.getStore(Chain
, DL
, VANext
, Addr
, MachinePointerInfo(V
));
5172 // Load the actual argument out of the pointer VAList
5174 // Load the value as an f64.
5176 DAG
.getLoad(MVT::f64
, DL
, APStore
, VAList
, MachinePointerInfo());
5177 // Round the value down to an f32.
5178 SDValue NarrowFP
= DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, WideFP
.getValue(0),
5179 DAG
.getIntPtrConstant(1, DL
));
5180 SDValue Ops
[] = { NarrowFP
, WideFP
.getValue(1) };
5181 // Merge the rounded value with the chain output of the load.
5182 return DAG
.getMergeValues(Ops
, DL
);
5185 return DAG
.getLoad(VT
, DL
, APStore
, VAList
, MachinePointerInfo());
5188 SDValue
AArch64TargetLowering::LowerFRAMEADDR(SDValue Op
,
5189 SelectionDAG
&DAG
) const {
5190 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
5191 MFI
.setFrameAddressIsTaken(true);
5193 EVT VT
= Op
.getValueType();
5195 unsigned Depth
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
5197 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, AArch64::FP
, VT
);
5199 FrameAddr
= DAG
.getLoad(VT
, DL
, DAG
.getEntryNode(), FrameAddr
,
5200 MachinePointerInfo());
5204 SDValue
AArch64TargetLowering::LowerSPONENTRY(SDValue Op
,
5205 SelectionDAG
&DAG
) const {
5206 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
5208 EVT VT
= getPointerTy(DAG
.getDataLayout());
5210 int FI
= MFI
.CreateFixedObject(4, 0, false);
5211 return DAG
.getFrameIndex(FI
, VT
);
5214 #define GET_REGISTER_MATCHER
5215 #include "AArch64GenAsmMatcher.inc"
5217 // FIXME? Maybe this could be a TableGen attribute on some registers and
5218 // this table could be generated automatically from RegInfo.
5219 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName
, EVT VT
,
5220 SelectionDAG
&DAG
) const {
5221 unsigned Reg
= MatchRegisterName(RegName
);
5222 if (AArch64::X1
<= Reg
&& Reg
<= AArch64::X28
) {
5223 const MCRegisterInfo
*MRI
= Subtarget
->getRegisterInfo();
5224 unsigned DwarfRegNum
= MRI
->getDwarfRegNum(Reg
, false);
5225 if (!Subtarget
->isXRegisterReserved(DwarfRegNum
))
5230 report_fatal_error(Twine("Invalid register name \""
5231 + StringRef(RegName
) + "\"."));
5234 SDValue
AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op
,
5235 SelectionDAG
&DAG
) const {
5236 DAG
.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5238 EVT VT
= Op
.getValueType();
5242 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, AArch64::FP
, VT
);
5243 SDValue Offset
= DAG
.getConstant(8, DL
, getPointerTy(DAG
.getDataLayout()));
5245 return DAG
.getNode(ISD::ADD
, DL
, VT
, FrameAddr
, Offset
);
5248 SDValue
AArch64TargetLowering::LowerRETURNADDR(SDValue Op
,
5249 SelectionDAG
&DAG
) const {
5250 MachineFunction
&MF
= DAG
.getMachineFunction();
5251 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
5252 MFI
.setReturnAddressIsTaken(true);
5254 EVT VT
= Op
.getValueType();
5256 unsigned Depth
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
5258 SDValue FrameAddr
= LowerFRAMEADDR(Op
, DAG
);
5259 SDValue Offset
= DAG
.getConstant(8, DL
, getPointerTy(DAG
.getDataLayout()));
5260 return DAG
.getLoad(VT
, DL
, DAG
.getEntryNode(),
5261 DAG
.getNode(ISD::ADD
, DL
, VT
, FrameAddr
, Offset
),
5262 MachinePointerInfo());
5265 // Return LR, which contains the return address. Mark it an implicit live-in.
5266 unsigned Reg
= MF
.addLiveIn(AArch64::LR
, &AArch64::GPR64RegClass
);
5267 return DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, Reg
, VT
);
5270 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5271 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5272 SDValue
AArch64TargetLowering::LowerShiftRightParts(SDValue Op
,
5273 SelectionDAG
&DAG
) const {
5274 assert(Op
.getNumOperands() == 3 && "Not a double-shift!");
5275 EVT VT
= Op
.getValueType();
5276 unsigned VTBits
= VT
.getSizeInBits();
5278 SDValue ShOpLo
= Op
.getOperand(0);
5279 SDValue ShOpHi
= Op
.getOperand(1);
5280 SDValue ShAmt
= Op
.getOperand(2);
5281 unsigned Opc
= (Op
.getOpcode() == ISD::SRA_PARTS
) ? ISD::SRA
: ISD::SRL
;
5283 assert(Op
.getOpcode() == ISD::SRA_PARTS
|| Op
.getOpcode() == ISD::SRL_PARTS
);
5285 SDValue RevShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
,
5286 DAG
.getConstant(VTBits
, dl
, MVT::i64
), ShAmt
);
5287 SDValue HiBitsForLo
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpHi
, RevShAmt
);
5289 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5290 // is "undef". We wanted 0, so CSEL it directly.
5291 SDValue Cmp
= emitComparison(ShAmt
, DAG
.getConstant(0, dl
, MVT::i64
),
5292 ISD::SETEQ
, dl
, DAG
);
5293 SDValue CCVal
= DAG
.getConstant(AArch64CC::EQ
, dl
, MVT::i32
);
5295 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, DAG
.getConstant(0, dl
, MVT::i64
),
5296 HiBitsForLo
, CCVal
, Cmp
);
5298 SDValue ExtraShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, ShAmt
,
5299 DAG
.getConstant(VTBits
, dl
, MVT::i64
));
5301 SDValue LoBitsForLo
= DAG
.getNode(ISD::SRL
, dl
, VT
, ShOpLo
, ShAmt
);
5302 SDValue LoForNormalShift
=
5303 DAG
.getNode(ISD::OR
, dl
, VT
, LoBitsForLo
, HiBitsForLo
);
5305 Cmp
= emitComparison(ExtraShAmt
, DAG
.getConstant(0, dl
, MVT::i64
), ISD::SETGE
,
5307 CCVal
= DAG
.getConstant(AArch64CC::GE
, dl
, MVT::i32
);
5308 SDValue LoForBigShift
= DAG
.getNode(Opc
, dl
, VT
, ShOpHi
, ExtraShAmt
);
5309 SDValue Lo
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, LoForBigShift
,
5310 LoForNormalShift
, CCVal
, Cmp
);
5312 // AArch64 shifts larger than the register width are wrapped rather than
5313 // clamped, so we can't just emit "hi >> x".
5314 SDValue HiForNormalShift
= DAG
.getNode(Opc
, dl
, VT
, ShOpHi
, ShAmt
);
5315 SDValue HiForBigShift
=
5317 ? DAG
.getNode(Opc
, dl
, VT
, ShOpHi
,
5318 DAG
.getConstant(VTBits
- 1, dl
, MVT::i64
))
5319 : DAG
.getConstant(0, dl
, VT
);
5320 SDValue Hi
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, HiForBigShift
,
5321 HiForNormalShift
, CCVal
, Cmp
);
5323 SDValue Ops
[2] = { Lo
, Hi
};
5324 return DAG
.getMergeValues(Ops
, dl
);
5327 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5328 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5329 SDValue
AArch64TargetLowering::LowerShiftLeftParts(SDValue Op
,
5330 SelectionDAG
&DAG
) const {
5331 assert(Op
.getNumOperands() == 3 && "Not a double-shift!");
5332 EVT VT
= Op
.getValueType();
5333 unsigned VTBits
= VT
.getSizeInBits();
5335 SDValue ShOpLo
= Op
.getOperand(0);
5336 SDValue ShOpHi
= Op
.getOperand(1);
5337 SDValue ShAmt
= Op
.getOperand(2);
5339 assert(Op
.getOpcode() == ISD::SHL_PARTS
);
5340 SDValue RevShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
,
5341 DAG
.getConstant(VTBits
, dl
, MVT::i64
), ShAmt
);
5342 SDValue LoBitsForHi
= DAG
.getNode(ISD::SRL
, dl
, VT
, ShOpLo
, RevShAmt
);
5344 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5345 // is "undef". We wanted 0, so CSEL it directly.
5346 SDValue Cmp
= emitComparison(ShAmt
, DAG
.getConstant(0, dl
, MVT::i64
),
5347 ISD::SETEQ
, dl
, DAG
);
5348 SDValue CCVal
= DAG
.getConstant(AArch64CC::EQ
, dl
, MVT::i32
);
5350 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, DAG
.getConstant(0, dl
, MVT::i64
),
5351 LoBitsForHi
, CCVal
, Cmp
);
5353 SDValue ExtraShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, ShAmt
,
5354 DAG
.getConstant(VTBits
, dl
, MVT::i64
));
5355 SDValue HiBitsForHi
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpHi
, ShAmt
);
5356 SDValue HiForNormalShift
=
5357 DAG
.getNode(ISD::OR
, dl
, VT
, LoBitsForHi
, HiBitsForHi
);
5359 SDValue HiForBigShift
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpLo
, ExtraShAmt
);
5361 Cmp
= emitComparison(ExtraShAmt
, DAG
.getConstant(0, dl
, MVT::i64
), ISD::SETGE
,
5363 CCVal
= DAG
.getConstant(AArch64CC::GE
, dl
, MVT::i32
);
5364 SDValue Hi
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, HiForBigShift
,
5365 HiForNormalShift
, CCVal
, Cmp
);
5367 // AArch64 shifts of larger than register sizes are wrapped rather than
5368 // clamped, so we can't just emit "lo << a" if a is too big.
5369 SDValue LoForBigShift
= DAG
.getConstant(0, dl
, VT
);
5370 SDValue LoForNormalShift
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpLo
, ShAmt
);
5371 SDValue Lo
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, LoForBigShift
,
5372 LoForNormalShift
, CCVal
, Cmp
);
5374 SDValue Ops
[2] = { Lo
, Hi
};
5375 return DAG
.getMergeValues(Ops
, dl
);
5378 bool AArch64TargetLowering::isOffsetFoldingLegal(
5379 const GlobalAddressSDNode
*GA
) const {
5380 // Offsets are folded in the DAG combine rather than here so that we can
5381 // intelligently choose an offset based on the uses.
5385 bool AArch64TargetLowering::isFPImmLegal(const APFloat
&Imm
, EVT VT
) const {
5386 bool IsLegal
= false;
5387 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5388 // 16-bit case when target has full fp16 support.
5389 // FIXME: We should be able to handle f128 as well with a clever lowering.
5390 const APInt ImmInt
= Imm
.bitcastToAPInt();
5392 IsLegal
= AArch64_AM::getFP64Imm(ImmInt
) != -1 || Imm
.isPosZero();
5393 else if (VT
== MVT::f32
)
5394 IsLegal
= AArch64_AM::getFP32Imm(ImmInt
) != -1 || Imm
.isPosZero();
5395 else if (VT
== MVT::f16
&& Subtarget
->hasFullFP16())
5396 IsLegal
= AArch64_AM::getFP16Imm(ImmInt
) != -1 || Imm
.isPosZero();
5397 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5398 // generate that fmov.
5400 // If we can not materialize in immediate field for fmov, check if the
5401 // value can be encoded as the immediate operand of a logical instruction.
5402 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5403 if (!IsLegal
&& (VT
== MVT::f64
|| VT
== MVT::f32
))
5404 IsLegal
= AArch64_AM::isAnyMOVWMovAlias(ImmInt
.getZExtValue(),
5405 VT
.getSizeInBits());
5407 LLVM_DEBUG(dbgs() << (IsLegal
? "Legal " : "Illegal ") << VT
.getEVTString()
5408 << " imm value: "; Imm
.dump(););
5412 //===----------------------------------------------------------------------===//
5413 // AArch64 Optimization Hooks
5414 //===----------------------------------------------------------------------===//
5416 static SDValue
getEstimate(const AArch64Subtarget
*ST
, unsigned Opcode
,
5417 SDValue Operand
, SelectionDAG
&DAG
,
5419 EVT VT
= Operand
.getValueType();
5420 if (ST
->hasNEON() &&
5421 (VT
== MVT::f64
|| VT
== MVT::v1f64
|| VT
== MVT::v2f64
||
5422 VT
== MVT::f32
|| VT
== MVT::v1f32
||
5423 VT
== MVT::v2f32
|| VT
== MVT::v4f32
)) {
5424 if (ExtraSteps
== TargetLoweringBase::ReciprocalEstimate::Unspecified
)
5425 // For the reciprocal estimates, convergence is quadratic, so the number
5426 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5427 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5428 // the result for float (23 mantissa bits) is 2 and for double (52
5429 // mantissa bits) is 3.
5430 ExtraSteps
= VT
.getScalarType() == MVT::f64
? 3 : 2;
5432 return DAG
.getNode(Opcode
, SDLoc(Operand
), VT
, Operand
);
5438 SDValue
AArch64TargetLowering::getSqrtEstimate(SDValue Operand
,
5439 SelectionDAG
&DAG
, int Enabled
,
5442 bool Reciprocal
) const {
5443 if (Enabled
== ReciprocalEstimate::Enabled
||
5444 (Enabled
== ReciprocalEstimate::Unspecified
&& Subtarget
->useRSqrt()))
5445 if (SDValue Estimate
= getEstimate(Subtarget
, AArch64ISD::FRSQRTE
, Operand
,
5448 EVT VT
= Operand
.getValueType();
5451 Flags
.setAllowReassociation(true);
5453 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5454 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5455 for (int i
= ExtraSteps
; i
> 0; --i
) {
5456 SDValue Step
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Estimate
,
5458 Step
= DAG
.getNode(AArch64ISD::FRSQRTS
, DL
, VT
, Operand
, Step
, Flags
);
5459 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Step
, Flags
);
5462 EVT CCVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(),
5464 SDValue FPZero
= DAG
.getConstantFP(0.0, DL
, VT
);
5465 SDValue Eq
= DAG
.getSetCC(DL
, CCVT
, Operand
, FPZero
, ISD::SETEQ
);
5467 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Operand
, Estimate
, Flags
);
5468 // Correct the result if the operand is 0.0.
5469 Estimate
= DAG
.getNode(VT
.isVector() ? ISD::VSELECT
: ISD::SELECT
, DL
,
5470 VT
, Eq
, Operand
, Estimate
);
5480 SDValue
AArch64TargetLowering::getRecipEstimate(SDValue Operand
,
5481 SelectionDAG
&DAG
, int Enabled
,
5482 int &ExtraSteps
) const {
5483 if (Enabled
== ReciprocalEstimate::Enabled
)
5484 if (SDValue Estimate
= getEstimate(Subtarget
, AArch64ISD::FRECPE
, Operand
,
5487 EVT VT
= Operand
.getValueType();
5490 Flags
.setAllowReassociation(true);
5492 // Newton reciprocal iteration: E * (2 - X * E)
5493 // AArch64 reciprocal iteration instruction: (2 - M * N)
5494 for (int i
= ExtraSteps
; i
> 0; --i
) {
5495 SDValue Step
= DAG
.getNode(AArch64ISD::FRECPS
, DL
, VT
, Operand
,
5497 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Step
, Flags
);
5507 //===----------------------------------------------------------------------===//
5508 // AArch64 Inline Assembly Support
5509 //===----------------------------------------------------------------------===//
5511 // Table of Constraints
5512 // TODO: This is the current set of constraints supported by ARM for the
5513 // compiler, not all of them may make sense.
5515 // r - A general register
5516 // w - An FP/SIMD register of some size in the range v0-v31
5517 // x - An FP/SIMD register of some size in the range v0-v15
5518 // I - Constant that can be used with an ADD instruction
5519 // J - Constant that can be used with a SUB instruction
5520 // K - Constant that can be used with a 32-bit logical instruction
5521 // L - Constant that can be used with a 64-bit logical instruction
5522 // M - Constant that can be used as a 32-bit MOV immediate
5523 // N - Constant that can be used as a 64-bit MOV immediate
5524 // Q - A memory reference with base register and no offset
5525 // S - A symbolic address
5526 // Y - Floating point constant zero
5527 // Z - Integer constant zero
5529 // Note that general register operands will be output using their 64-bit x
5530 // register name, whatever the size of the variable, unless the asm operand
5531 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5532 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5534 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT
) const {
5535 // At this point, we have to lower this constraint to something else, so we
5536 // lower it to an "r" or "w". However, by doing this we will force the result
5537 // to be in register, while the X constraint is much more permissive.
5539 // Although we are correct (we are free to emit anything, without
5540 // constraints), we might break use cases that would expect us to be more
5541 // efficient and emit something else.
5542 if (!Subtarget
->hasFPARMv8())
5545 if (ConstraintVT
.isFloatingPoint())
5548 if (ConstraintVT
.isVector() &&
5549 (ConstraintVT
.getSizeInBits() == 64 ||
5550 ConstraintVT
.getSizeInBits() == 128))
5556 /// getConstraintType - Given a constraint letter, return the type of
5557 /// constraint it is for this target.
5558 AArch64TargetLowering::ConstraintType
5559 AArch64TargetLowering::getConstraintType(StringRef Constraint
) const {
5560 if (Constraint
.size() == 1) {
5561 switch (Constraint
[0]) {
5568 return C_RegisterClass
;
5569 // An address with a single base register. Due to the way we
5570 // currently handle addresses it is the same as 'r'.
5573 case 'S': // A symbolic address
5577 return TargetLowering::getConstraintType(Constraint
);
5580 /// Examine constraint type and operand type and determine a weight value.
5581 /// This object must already have been set up with the operand type
5582 /// and the current alternative constraint selected.
5583 TargetLowering::ConstraintWeight
5584 AArch64TargetLowering::getSingleConstraintMatchWeight(
5585 AsmOperandInfo
&info
, const char *constraint
) const {
5586 ConstraintWeight weight
= CW_Invalid
;
5587 Value
*CallOperandVal
= info
.CallOperandVal
;
5588 // If we don't have a value, we can't do a match,
5589 // but allow it at the lowest weight.
5590 if (!CallOperandVal
)
5592 Type
*type
= CallOperandVal
->getType();
5593 // Look at the constraint type.
5594 switch (*constraint
) {
5596 weight
= TargetLowering::getSingleConstraintMatchWeight(info
, constraint
);
5600 if (type
->isFloatingPointTy() || type
->isVectorTy())
5601 weight
= CW_Register
;
5604 weight
= CW_Constant
;
5610 std::pair
<unsigned, const TargetRegisterClass
*>
5611 AArch64TargetLowering::getRegForInlineAsmConstraint(
5612 const TargetRegisterInfo
*TRI
, StringRef Constraint
, MVT VT
) const {
5613 if (Constraint
.size() == 1) {
5614 switch (Constraint
[0]) {
5616 if (VT
.getSizeInBits() == 64)
5617 return std::make_pair(0U, &AArch64::GPR64commonRegClass
);
5618 return std::make_pair(0U, &AArch64::GPR32commonRegClass
);
5620 if (!Subtarget
->hasFPARMv8())
5622 if (VT
.getSizeInBits() == 16)
5623 return std::make_pair(0U, &AArch64::FPR16RegClass
);
5624 if (VT
.getSizeInBits() == 32)
5625 return std::make_pair(0U, &AArch64::FPR32RegClass
);
5626 if (VT
.getSizeInBits() == 64)
5627 return std::make_pair(0U, &AArch64::FPR64RegClass
);
5628 if (VT
.getSizeInBits() == 128)
5629 return std::make_pair(0U, &AArch64::FPR128RegClass
);
5631 // The instructions that this constraint is designed for can
5632 // only take 128-bit registers so just use that regclass.
5634 if (!Subtarget
->hasFPARMv8())
5636 if (VT
.getSizeInBits() == 128)
5637 return std::make_pair(0U, &AArch64::FPR128_loRegClass
);
5641 if (StringRef("{cc}").equals_lower(Constraint
))
5642 return std::make_pair(unsigned(AArch64::NZCV
), &AArch64::CCRRegClass
);
5644 // Use the default implementation in TargetLowering to convert the register
5645 // constraint into a member of a register class.
5646 std::pair
<unsigned, const TargetRegisterClass
*> Res
;
5647 Res
= TargetLowering::getRegForInlineAsmConstraint(TRI
, Constraint
, VT
);
5649 // Not found as a standard register?
5651 unsigned Size
= Constraint
.size();
5652 if ((Size
== 4 || Size
== 5) && Constraint
[0] == '{' &&
5653 tolower(Constraint
[1]) == 'v' && Constraint
[Size
- 1] == '}') {
5655 bool Failed
= Constraint
.slice(2, Size
- 1).getAsInteger(10, RegNo
);
5656 if (!Failed
&& RegNo
>= 0 && RegNo
<= 31) {
5657 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5658 // By default we'll emit v0-v31 for this unless there's a modifier where
5659 // we'll emit the correct register as well.
5660 if (VT
!= MVT::Other
&& VT
.getSizeInBits() == 64) {
5661 Res
.first
= AArch64::FPR64RegClass
.getRegister(RegNo
);
5662 Res
.second
= &AArch64::FPR64RegClass
;
5664 Res
.first
= AArch64::FPR128RegClass
.getRegister(RegNo
);
5665 Res
.second
= &AArch64::FPR128RegClass
;
5671 if (Res
.second
&& !Subtarget
->hasFPARMv8() &&
5672 !AArch64::GPR32allRegClass
.hasSubClassEq(Res
.second
) &&
5673 !AArch64::GPR64allRegClass
.hasSubClassEq(Res
.second
))
5674 return std::make_pair(0U, nullptr);
5679 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5680 /// vector. If it is invalid, don't add anything to Ops.
5681 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5682 SDValue Op
, std::string
&Constraint
, std::vector
<SDValue
> &Ops
,
5683 SelectionDAG
&DAG
) const {
5686 // Currently only support length 1 constraints.
5687 if (Constraint
.length() != 1)
5690 char ConstraintLetter
= Constraint
[0];
5691 switch (ConstraintLetter
) {
5695 // This set of constraints deal with valid constants for various instructions.
5696 // Validate and return a target constant for them if we can.
5698 // 'z' maps to xzr or wzr so it needs an input of 0.
5699 if (!isNullConstant(Op
))
5702 if (Op
.getValueType() == MVT::i64
)
5703 Result
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
5705 Result
= DAG
.getRegister(AArch64::WZR
, MVT::i32
);
5709 // An absolute symbolic address or label reference.
5710 if (const GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(Op
)) {
5711 Result
= DAG
.getTargetGlobalAddress(GA
->getGlobal(), SDLoc(Op
),
5712 GA
->getValueType(0));
5713 } else if (const BlockAddressSDNode
*BA
=
5714 dyn_cast
<BlockAddressSDNode
>(Op
)) {
5716 DAG
.getTargetBlockAddress(BA
->getBlockAddress(), BA
->getValueType(0));
5717 } else if (const ExternalSymbolSDNode
*ES
=
5718 dyn_cast
<ExternalSymbolSDNode
>(Op
)) {
5720 DAG
.getTargetExternalSymbol(ES
->getSymbol(), ES
->getValueType(0));
5732 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
);
5736 // Grab the value and do some validation.
5737 uint64_t CVal
= C
->getZExtValue();
5738 switch (ConstraintLetter
) {
5739 // The I constraint applies only to simple ADD or SUB immediate operands:
5740 // i.e. 0 to 4095 with optional shift by 12
5741 // The J constraint applies only to ADD or SUB immediates that would be
5742 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5743 // instruction [or vice versa], in other words -1 to -4095 with optional
5744 // left shift by 12.
5746 if (isUInt
<12>(CVal
) || isShiftedUInt
<12, 12>(CVal
))
5750 uint64_t NVal
= -C
->getSExtValue();
5751 if (isUInt
<12>(NVal
) || isShiftedUInt
<12, 12>(NVal
)) {
5752 CVal
= C
->getSExtValue();
5757 // The K and L constraints apply *only* to logical immediates, including
5758 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5759 // been removed and MOV should be used). So these constraints have to
5760 // distinguish between bit patterns that are valid 32-bit or 64-bit
5761 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5762 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5765 if (AArch64_AM::isLogicalImmediate(CVal
, 32))
5769 if (AArch64_AM::isLogicalImmediate(CVal
, 64))
5772 // The M and N constraints are a superset of K and L respectively, for use
5773 // with the MOV (immediate) alias. As well as the logical immediates they
5774 // also match 32 or 64-bit immediates that can be loaded either using a
5775 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5776 // (M) or 64-bit 0x1234000000000000 (N) etc.
5777 // As a note some of this code is liberally stolen from the asm parser.
5779 if (!isUInt
<32>(CVal
))
5781 if (AArch64_AM::isLogicalImmediate(CVal
, 32))
5783 if ((CVal
& 0xFFFF) == CVal
)
5785 if ((CVal
& 0xFFFF0000ULL
) == CVal
)
5787 uint64_t NCVal
= ~(uint32_t)CVal
;
5788 if ((NCVal
& 0xFFFFULL
) == NCVal
)
5790 if ((NCVal
& 0xFFFF0000ULL
) == NCVal
)
5795 if (AArch64_AM::isLogicalImmediate(CVal
, 64))
5797 if ((CVal
& 0xFFFFULL
) == CVal
)
5799 if ((CVal
& 0xFFFF0000ULL
) == CVal
)
5801 if ((CVal
& 0xFFFF00000000ULL
) == CVal
)
5803 if ((CVal
& 0xFFFF000000000000ULL
) == CVal
)
5805 uint64_t NCVal
= ~CVal
;
5806 if ((NCVal
& 0xFFFFULL
) == NCVal
)
5808 if ((NCVal
& 0xFFFF0000ULL
) == NCVal
)
5810 if ((NCVal
& 0xFFFF00000000ULL
) == NCVal
)
5812 if ((NCVal
& 0xFFFF000000000000ULL
) == NCVal
)
5820 // All assembler immediates are 64-bit integers.
5821 Result
= DAG
.getTargetConstant(CVal
, SDLoc(Op
), MVT::i64
);
5825 if (Result
.getNode()) {
5826 Ops
.push_back(Result
);
5830 return TargetLowering::LowerAsmOperandForConstraint(Op
, Constraint
, Ops
, DAG
);
5833 //===----------------------------------------------------------------------===//
5834 // AArch64 Advanced SIMD Support
5835 //===----------------------------------------------------------------------===//
5837 /// WidenVector - Given a value in the V64 register class, produce the
5838 /// equivalent value in the V128 register class.
5839 static SDValue
WidenVector(SDValue V64Reg
, SelectionDAG
&DAG
) {
5840 EVT VT
= V64Reg
.getValueType();
5841 unsigned NarrowSize
= VT
.getVectorNumElements();
5842 MVT EltTy
= VT
.getVectorElementType().getSimpleVT();
5843 MVT WideTy
= MVT::getVectorVT(EltTy
, 2 * NarrowSize
);
5846 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, WideTy
, DAG
.getUNDEF(WideTy
),
5847 V64Reg
, DAG
.getConstant(0, DL
, MVT::i32
));
5850 /// getExtFactor - Determine the adjustment factor for the position when
5851 /// generating an "extract from vector registers" instruction.
5852 static unsigned getExtFactor(SDValue
&V
) {
5853 EVT EltType
= V
.getValueType().getVectorElementType();
5854 return EltType
.getSizeInBits() / 8;
5857 /// NarrowVector - Given a value in the V128 register class, produce the
5858 /// equivalent value in the V64 register class.
5859 static SDValue
NarrowVector(SDValue V128Reg
, SelectionDAG
&DAG
) {
5860 EVT VT
= V128Reg
.getValueType();
5861 unsigned WideSize
= VT
.getVectorNumElements();
5862 MVT EltTy
= VT
.getVectorElementType().getSimpleVT();
5863 MVT NarrowTy
= MVT::getVectorVT(EltTy
, WideSize
/ 2);
5866 return DAG
.getTargetExtractSubreg(AArch64::dsub
, DL
, NarrowTy
, V128Reg
);
5869 // Gather data to see if the operation can be modelled as a
5870 // shuffle in combination with VEXTs.
5871 SDValue
AArch64TargetLowering::ReconstructShuffle(SDValue Op
,
5872 SelectionDAG
&DAG
) const {
5873 assert(Op
.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!");
5874 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
5876 EVT VT
= Op
.getValueType();
5877 unsigned NumElts
= VT
.getVectorNumElements();
5879 struct ShuffleSourceInfo
{
5884 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5885 // be compatible with the shuffle we intend to construct. As a result
5886 // ShuffleVec will be some sliding window into the original Vec.
5889 // Code should guarantee that element i in Vec starts at element "WindowBase
5890 // + i * WindowScale in ShuffleVec".
5894 ShuffleSourceInfo(SDValue Vec
)
5895 : Vec(Vec
), MinElt(std::numeric_limits
<unsigned>::max()), MaxElt(0),
5896 ShuffleVec(Vec
), WindowBase(0), WindowScale(1) {}
5898 bool operator ==(SDValue OtherVec
) { return Vec
== OtherVec
; }
5901 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5903 SmallVector
<ShuffleSourceInfo
, 2> Sources
;
5904 for (unsigned i
= 0; i
< NumElts
; ++i
) {
5905 SDValue V
= Op
.getOperand(i
);
5908 else if (V
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
5909 !isa
<ConstantSDNode
>(V
.getOperand(1))) {
5911 dbgs() << "Reshuffle failed: "
5912 "a shuffle can only come from building a vector from "
5913 "various elements of other vectors, provided their "
5914 "indices are constant\n");
5918 // Add this element source to the list if it's not already there.
5919 SDValue SourceVec
= V
.getOperand(0);
5920 auto Source
= find(Sources
, SourceVec
);
5921 if (Source
== Sources
.end())
5922 Source
= Sources
.insert(Sources
.end(), ShuffleSourceInfo(SourceVec
));
5924 // Update the minimum and maximum lane number seen.
5925 unsigned EltNo
= cast
<ConstantSDNode
>(V
.getOperand(1))->getZExtValue();
5926 Source
->MinElt
= std::min(Source
->MinElt
, EltNo
);
5927 Source
->MaxElt
= std::max(Source
->MaxElt
, EltNo
);
5930 if (Sources
.size() > 2) {
5932 dbgs() << "Reshuffle failed: currently only do something sane when at "
5933 "most two source vectors are involved\n");
5937 // Find out the smallest element size among result and two sources, and use
5938 // it as element size to build the shuffle_vector.
5939 EVT SmallestEltTy
= VT
.getVectorElementType();
5940 for (auto &Source
: Sources
) {
5941 EVT SrcEltTy
= Source
.Vec
.getValueType().getVectorElementType();
5942 if (SrcEltTy
.bitsLT(SmallestEltTy
)) {
5943 SmallestEltTy
= SrcEltTy
;
5946 unsigned ResMultiplier
=
5947 VT
.getScalarSizeInBits() / SmallestEltTy
.getSizeInBits();
5948 NumElts
= VT
.getSizeInBits() / SmallestEltTy
.getSizeInBits();
5949 EVT ShuffleVT
= EVT::getVectorVT(*DAG
.getContext(), SmallestEltTy
, NumElts
);
5951 // If the source vector is too wide or too narrow, we may nevertheless be able
5952 // to construct a compatible shuffle either by concatenating it with UNDEF or
5953 // extracting a suitable range of elements.
5954 for (auto &Src
: Sources
) {
5955 EVT SrcVT
= Src
.ShuffleVec
.getValueType();
5957 if (SrcVT
.getSizeInBits() == VT
.getSizeInBits())
5960 // This stage of the search produces a source with the same element type as
5961 // the original, but with a total width matching the BUILD_VECTOR output.
5962 EVT EltVT
= SrcVT
.getVectorElementType();
5963 unsigned NumSrcElts
= VT
.getSizeInBits() / EltVT
.getSizeInBits();
5964 EVT DestVT
= EVT::getVectorVT(*DAG
.getContext(), EltVT
, NumSrcElts
);
5966 if (SrcVT
.getSizeInBits() < VT
.getSizeInBits()) {
5967 assert(2 * SrcVT
.getSizeInBits() == VT
.getSizeInBits());
5968 // We can pad out the smaller vector for free, so if it's part of a
5971 DAG
.getNode(ISD::CONCAT_VECTORS
, dl
, DestVT
, Src
.ShuffleVec
,
5972 DAG
.getUNDEF(Src
.ShuffleVec
.getValueType()));
5976 assert(SrcVT
.getSizeInBits() == 2 * VT
.getSizeInBits());
5978 if (Src
.MaxElt
- Src
.MinElt
>= NumSrcElts
) {
5980 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
5984 if (Src
.MinElt
>= NumSrcElts
) {
5985 // The extraction can just take the second half
5987 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
5988 DAG
.getConstant(NumSrcElts
, dl
, MVT::i64
));
5989 Src
.WindowBase
= -NumSrcElts
;
5990 } else if (Src
.MaxElt
< NumSrcElts
) {
5991 // The extraction can just take the first half
5993 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
5994 DAG
.getConstant(0, dl
, MVT::i64
));
5996 // An actual VEXT is needed
5998 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
5999 DAG
.getConstant(0, dl
, MVT::i64
));
6001 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6002 DAG
.getConstant(NumSrcElts
, dl
, MVT::i64
));
6003 unsigned Imm
= Src
.MinElt
* getExtFactor(VEXTSrc1
);
6005 Src
.ShuffleVec
= DAG
.getNode(AArch64ISD::EXT
, dl
, DestVT
, VEXTSrc1
,
6007 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6008 Src
.WindowBase
= -Src
.MinElt
;
6012 // Another possible incompatibility occurs from the vector element types. We
6013 // can fix this by bitcasting the source vectors to the same type we intend
6015 for (auto &Src
: Sources
) {
6016 EVT SrcEltTy
= Src
.ShuffleVec
.getValueType().getVectorElementType();
6017 if (SrcEltTy
== SmallestEltTy
)
6019 assert(ShuffleVT
.getVectorElementType() == SmallestEltTy
);
6020 Src
.ShuffleVec
= DAG
.getNode(ISD::BITCAST
, dl
, ShuffleVT
, Src
.ShuffleVec
);
6021 Src
.WindowScale
= SrcEltTy
.getSizeInBits() / SmallestEltTy
.getSizeInBits();
6022 Src
.WindowBase
*= Src
.WindowScale
;
6025 // Final sanity check before we try to actually produce a shuffle.
6026 LLVM_DEBUG(for (auto Src
6028 assert(Src
.ShuffleVec
.getValueType() == ShuffleVT
););
6030 // The stars all align, our next step is to produce the mask for the shuffle.
6031 SmallVector
<int, 8> Mask(ShuffleVT
.getVectorNumElements(), -1);
6032 int BitsPerShuffleLane
= ShuffleVT
.getScalarSizeInBits();
6033 for (unsigned i
= 0; i
< VT
.getVectorNumElements(); ++i
) {
6034 SDValue Entry
= Op
.getOperand(i
);
6035 if (Entry
.isUndef())
6038 auto Src
= find(Sources
, Entry
.getOperand(0));
6039 int EltNo
= cast
<ConstantSDNode
>(Entry
.getOperand(1))->getSExtValue();
6041 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6042 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6044 EVT OrigEltTy
= Entry
.getOperand(0).getValueType().getVectorElementType();
6046 std::min(OrigEltTy
.getSizeInBits(), VT
.getScalarSizeInBits());
6047 int LanesDefined
= BitsDefined
/ BitsPerShuffleLane
;
6049 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6050 // starting at the appropriate offset.
6051 int *LaneMask
= &Mask
[i
* ResMultiplier
];
6053 int ExtractBase
= EltNo
* Src
->WindowScale
+ Src
->WindowBase
;
6054 ExtractBase
+= NumElts
* (Src
- Sources
.begin());
6055 for (int j
= 0; j
< LanesDefined
; ++j
)
6056 LaneMask
[j
] = ExtractBase
+ j
;
6059 // Final check before we try to produce nonsense...
6060 if (!isShuffleMaskLegal(Mask
, ShuffleVT
)) {
6061 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6065 SDValue ShuffleOps
[] = { DAG
.getUNDEF(ShuffleVT
), DAG
.getUNDEF(ShuffleVT
) };
6066 for (unsigned i
= 0; i
< Sources
.size(); ++i
)
6067 ShuffleOps
[i
] = Sources
[i
].ShuffleVec
;
6069 SDValue Shuffle
= DAG
.getVectorShuffle(ShuffleVT
, dl
, ShuffleOps
[0],
6070 ShuffleOps
[1], Mask
);
6071 SDValue V
= DAG
.getNode(ISD::BITCAST
, dl
, VT
, Shuffle
);
6073 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle
.dump();
6074 dbgs() << "Reshuffle, creating node: "; V
.dump(););
6079 // check if an EXT instruction can handle the shuffle mask when the
6080 // vector sources of the shuffle are the same.
6081 static bool isSingletonEXTMask(ArrayRef
<int> M
, EVT VT
, unsigned &Imm
) {
6082 unsigned NumElts
= VT
.getVectorNumElements();
6084 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6090 // If this is a VEXT shuffle, the immediate value is the index of the first
6091 // element. The other shuffle indices must be the successive elements after
6093 unsigned ExpectedElt
= Imm
;
6094 for (unsigned i
= 1; i
< NumElts
; ++i
) {
6095 // Increment the expected index. If it wraps around, just follow it
6096 // back to index zero and keep going.
6098 if (ExpectedElt
== NumElts
)
6102 continue; // ignore UNDEF indices
6103 if (ExpectedElt
!= static_cast<unsigned>(M
[i
]))
6110 // check if an EXT instruction can handle the shuffle mask when the
6111 // vector sources of the shuffle are different.
6112 static bool isEXTMask(ArrayRef
<int> M
, EVT VT
, bool &ReverseEXT
,
6114 // Look for the first non-undef element.
6115 const int *FirstRealElt
= find_if(M
, [](int Elt
) { return Elt
>= 0; });
6117 // Benefit form APInt to handle overflow when calculating expected element.
6118 unsigned NumElts
= VT
.getVectorNumElements();
6119 unsigned MaskBits
= APInt(32, NumElts
* 2).logBase2();
6120 APInt ExpectedElt
= APInt(MaskBits
, *FirstRealElt
+ 1);
6121 // The following shuffle indices must be the successive elements after the
6122 // first real element.
6123 const int *FirstWrongElt
= std::find_if(FirstRealElt
+ 1, M
.end(),
6124 [&](int Elt
) {return Elt
!= ExpectedElt
++ && Elt
!= -1;});
6125 if (FirstWrongElt
!= M
.end())
6128 // The index of an EXT is the first element if it is not UNDEF.
6129 // Watch out for the beginning UNDEFs. The EXT index should be the expected
6130 // value of the first element. E.g.
6131 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6132 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6133 // ExpectedElt is the last mask index plus 1.
6134 Imm
= ExpectedElt
.getZExtValue();
6136 // There are two difference cases requiring to reverse input vectors.
6137 // For example, for vector <4 x i32> we have the following cases,
6138 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6139 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6140 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6141 // to reverse two input vectors.
6150 /// isREVMask - Check if a vector shuffle corresponds to a REV
6151 /// instruction with the specified blocksize. (The order of the elements
6152 /// within each block of the vector is reversed.)
6153 static bool isREVMask(ArrayRef
<int> M
, EVT VT
, unsigned BlockSize
) {
6154 assert((BlockSize
== 16 || BlockSize
== 32 || BlockSize
== 64) &&
6155 "Only possible block sizes for REV are: 16, 32, 64");
6157 unsigned EltSz
= VT
.getScalarSizeInBits();
6161 unsigned NumElts
= VT
.getVectorNumElements();
6162 unsigned BlockElts
= M
[0] + 1;
6163 // If the first shuffle index is UNDEF, be optimistic.
6165 BlockElts
= BlockSize
/ EltSz
;
6167 if (BlockSize
<= EltSz
|| BlockSize
!= BlockElts
* EltSz
)
6170 for (unsigned i
= 0; i
< NumElts
; ++i
) {
6172 continue; // ignore UNDEF indices
6173 if ((unsigned)M
[i
] != (i
- i
% BlockElts
) + (BlockElts
- 1 - i
% BlockElts
))
6180 static bool isZIPMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6181 unsigned NumElts
= VT
.getVectorNumElements();
6182 WhichResult
= (M
[0] == 0 ? 0 : 1);
6183 unsigned Idx
= WhichResult
* NumElts
/ 2;
6184 for (unsigned i
= 0; i
!= NumElts
; i
+= 2) {
6185 if ((M
[i
] >= 0 && (unsigned)M
[i
] != Idx
) ||
6186 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != Idx
+ NumElts
))
6194 static bool isUZPMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6195 unsigned NumElts
= VT
.getVectorNumElements();
6196 WhichResult
= (M
[0] == 0 ? 0 : 1);
6197 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
6199 continue; // ignore UNDEF indices
6200 if ((unsigned)M
[i
] != 2 * i
+ WhichResult
)
6207 static bool isTRNMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6208 unsigned NumElts
= VT
.getVectorNumElements();
6209 WhichResult
= (M
[0] == 0 ? 0 : 1);
6210 for (unsigned i
= 0; i
< NumElts
; i
+= 2) {
6211 if ((M
[i
] >= 0 && (unsigned)M
[i
] != i
+ WhichResult
) ||
6212 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != i
+ NumElts
+ WhichResult
))
6218 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6219 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6220 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6221 static bool isZIP_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6222 unsigned NumElts
= VT
.getVectorNumElements();
6223 WhichResult
= (M
[0] == 0 ? 0 : 1);
6224 unsigned Idx
= WhichResult
* NumElts
/ 2;
6225 for (unsigned i
= 0; i
!= NumElts
; i
+= 2) {
6226 if ((M
[i
] >= 0 && (unsigned)M
[i
] != Idx
) ||
6227 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != Idx
))
6235 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6236 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6237 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6238 static bool isUZP_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6239 unsigned Half
= VT
.getVectorNumElements() / 2;
6240 WhichResult
= (M
[0] == 0 ? 0 : 1);
6241 for (unsigned j
= 0; j
!= 2; ++j
) {
6242 unsigned Idx
= WhichResult
;
6243 for (unsigned i
= 0; i
!= Half
; ++i
) {
6244 int MIdx
= M
[i
+ j
* Half
];
6245 if (MIdx
>= 0 && (unsigned)MIdx
!= Idx
)
6254 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6255 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6256 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6257 static bool isTRN_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6258 unsigned NumElts
= VT
.getVectorNumElements();
6259 WhichResult
= (M
[0] == 0 ? 0 : 1);
6260 for (unsigned i
= 0; i
< NumElts
; i
+= 2) {
6261 if ((M
[i
] >= 0 && (unsigned)M
[i
] != i
+ WhichResult
) ||
6262 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != i
+ WhichResult
))
6268 static bool isINSMask(ArrayRef
<int> M
, int NumInputElements
,
6269 bool &DstIsLeft
, int &Anomaly
) {
6270 if (M
.size() != static_cast<size_t>(NumInputElements
))
6273 int NumLHSMatch
= 0, NumRHSMatch
= 0;
6274 int LastLHSMismatch
= -1, LastRHSMismatch
= -1;
6276 for (int i
= 0; i
< NumInputElements
; ++i
) {
6286 LastLHSMismatch
= i
;
6288 if (M
[i
] == i
+ NumInputElements
)
6291 LastRHSMismatch
= i
;
6294 if (NumLHSMatch
== NumInputElements
- 1) {
6296 Anomaly
= LastLHSMismatch
;
6298 } else if (NumRHSMatch
== NumInputElements
- 1) {
6300 Anomaly
= LastRHSMismatch
;
6307 static bool isConcatMask(ArrayRef
<int> Mask
, EVT VT
, bool SplitLHS
) {
6308 if (VT
.getSizeInBits() != 128)
6311 unsigned NumElts
= VT
.getVectorNumElements();
6313 for (int I
= 0, E
= NumElts
/ 2; I
!= E
; I
++) {
6318 int Offset
= NumElts
/ 2;
6319 for (int I
= NumElts
/ 2, E
= NumElts
; I
!= E
; I
++) {
6320 if (Mask
[I
] != I
+ SplitLHS
* Offset
)
6327 static SDValue
tryFormConcatFromShuffle(SDValue Op
, SelectionDAG
&DAG
) {
6329 EVT VT
= Op
.getValueType();
6330 SDValue V0
= Op
.getOperand(0);
6331 SDValue V1
= Op
.getOperand(1);
6332 ArrayRef
<int> Mask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
6334 if (VT
.getVectorElementType() != V0
.getValueType().getVectorElementType() ||
6335 VT
.getVectorElementType() != V1
.getValueType().getVectorElementType())
6338 bool SplitV0
= V0
.getValueSizeInBits() == 128;
6340 if (!isConcatMask(Mask
, VT
, SplitV0
))
6343 EVT CastVT
= EVT::getVectorVT(*DAG
.getContext(), VT
.getVectorElementType(),
6344 VT
.getVectorNumElements() / 2);
6346 V0
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, CastVT
, V0
,
6347 DAG
.getConstant(0, DL
, MVT::i64
));
6349 if (V1
.getValueSizeInBits() == 128) {
6350 V1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, CastVT
, V1
,
6351 DAG
.getConstant(0, DL
, MVT::i64
));
6353 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, V0
, V1
);
6356 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6357 /// the specified operations to build the shuffle.
6358 static SDValue
GeneratePerfectShuffle(unsigned PFEntry
, SDValue LHS
,
6359 SDValue RHS
, SelectionDAG
&DAG
,
6361 unsigned OpNum
= (PFEntry
>> 26) & 0x0F;
6362 unsigned LHSID
= (PFEntry
>> 13) & ((1 << 13) - 1);
6363 unsigned RHSID
= (PFEntry
>> 0) & ((1 << 13) - 1);
6366 OP_COPY
= 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6375 OP_VUZPL
, // VUZP, left result
6376 OP_VUZPR
, // VUZP, right result
6377 OP_VZIPL
, // VZIP, left result
6378 OP_VZIPR
, // VZIP, right result
6379 OP_VTRNL
, // VTRN, left result
6380 OP_VTRNR
// VTRN, right result
6383 if (OpNum
== OP_COPY
) {
6384 if (LHSID
== (1 * 9 + 2) * 9 + 3)
6386 assert(LHSID
== ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6390 SDValue OpLHS
, OpRHS
;
6391 OpLHS
= GeneratePerfectShuffle(PerfectShuffleTable
[LHSID
], LHS
, RHS
, DAG
, dl
);
6392 OpRHS
= GeneratePerfectShuffle(PerfectShuffleTable
[RHSID
], LHS
, RHS
, DAG
, dl
);
6393 EVT VT
= OpLHS
.getValueType();
6397 llvm_unreachable("Unknown shuffle opcode!");
6399 // VREV divides the vector in half and swaps within the half.
6400 if (VT
.getVectorElementType() == MVT::i32
||
6401 VT
.getVectorElementType() == MVT::f32
)
6402 return DAG
.getNode(AArch64ISD::REV64
, dl
, VT
, OpLHS
);
6403 // vrev <4 x i16> -> REV32
6404 if (VT
.getVectorElementType() == MVT::i16
||
6405 VT
.getVectorElementType() == MVT::f16
)
6406 return DAG
.getNode(AArch64ISD::REV32
, dl
, VT
, OpLHS
);
6407 // vrev <4 x i8> -> REV16
6408 assert(VT
.getVectorElementType() == MVT::i8
);
6409 return DAG
.getNode(AArch64ISD::REV16
, dl
, VT
, OpLHS
);
6414 EVT EltTy
= VT
.getVectorElementType();
6416 if (EltTy
== MVT::i8
)
6417 Opcode
= AArch64ISD::DUPLANE8
;
6418 else if (EltTy
== MVT::i16
|| EltTy
== MVT::f16
)
6419 Opcode
= AArch64ISD::DUPLANE16
;
6420 else if (EltTy
== MVT::i32
|| EltTy
== MVT::f32
)
6421 Opcode
= AArch64ISD::DUPLANE32
;
6422 else if (EltTy
== MVT::i64
|| EltTy
== MVT::f64
)
6423 Opcode
= AArch64ISD::DUPLANE64
;
6425 llvm_unreachable("Invalid vector element type?");
6427 if (VT
.getSizeInBits() == 64)
6428 OpLHS
= WidenVector(OpLHS
, DAG
);
6429 SDValue Lane
= DAG
.getConstant(OpNum
- OP_VDUP0
, dl
, MVT::i64
);
6430 return DAG
.getNode(Opcode
, dl
, VT
, OpLHS
, Lane
);
6435 unsigned Imm
= (OpNum
- OP_VEXT1
+ 1) * getExtFactor(OpLHS
);
6436 return DAG
.getNode(AArch64ISD::EXT
, dl
, VT
, OpLHS
, OpRHS
,
6437 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6440 return DAG
.getNode(AArch64ISD::UZP1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6443 return DAG
.getNode(AArch64ISD::UZP2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6446 return DAG
.getNode(AArch64ISD::ZIP1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6449 return DAG
.getNode(AArch64ISD::ZIP2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6452 return DAG
.getNode(AArch64ISD::TRN1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6455 return DAG
.getNode(AArch64ISD::TRN2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6460 static SDValue
GenerateTBL(SDValue Op
, ArrayRef
<int> ShuffleMask
,
6461 SelectionDAG
&DAG
) {
6462 // Check to see if we can use the TBL instruction.
6463 SDValue V1
= Op
.getOperand(0);
6464 SDValue V2
= Op
.getOperand(1);
6467 EVT EltVT
= Op
.getValueType().getVectorElementType();
6468 unsigned BytesPerElt
= EltVT
.getSizeInBits() / 8;
6470 SmallVector
<SDValue
, 8> TBLMask
;
6471 for (int Val
: ShuffleMask
) {
6472 for (unsigned Byte
= 0; Byte
< BytesPerElt
; ++Byte
) {
6473 unsigned Offset
= Byte
+ Val
* BytesPerElt
;
6474 TBLMask
.push_back(DAG
.getConstant(Offset
, DL
, MVT::i32
));
6478 MVT IndexVT
= MVT::v8i8
;
6479 unsigned IndexLen
= 8;
6480 if (Op
.getValueSizeInBits() == 128) {
6481 IndexVT
= MVT::v16i8
;
6485 SDValue V1Cst
= DAG
.getNode(ISD::BITCAST
, DL
, IndexVT
, V1
);
6486 SDValue V2Cst
= DAG
.getNode(ISD::BITCAST
, DL
, IndexVT
, V2
);
6489 if (V2
.getNode()->isUndef()) {
6491 V1Cst
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v16i8
, V1Cst
, V1Cst
);
6492 Shuffle
= DAG
.getNode(
6493 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6494 DAG
.getConstant(Intrinsic::aarch64_neon_tbl1
, DL
, MVT::i32
), V1Cst
,
6495 DAG
.getBuildVector(IndexVT
, DL
,
6496 makeArrayRef(TBLMask
.data(), IndexLen
)));
6498 if (IndexLen
== 8) {
6499 V1Cst
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v16i8
, V1Cst
, V2Cst
);
6500 Shuffle
= DAG
.getNode(
6501 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6502 DAG
.getConstant(Intrinsic::aarch64_neon_tbl1
, DL
, MVT::i32
), V1Cst
,
6503 DAG
.getBuildVector(IndexVT
, DL
,
6504 makeArrayRef(TBLMask
.data(), IndexLen
)));
6506 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6507 // cannot currently represent the register constraints on the input
6509 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6510 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6512 Shuffle
= DAG
.getNode(
6513 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6514 DAG
.getConstant(Intrinsic::aarch64_neon_tbl2
, DL
, MVT::i32
), V1Cst
,
6515 V2Cst
, DAG
.getBuildVector(IndexVT
, DL
,
6516 makeArrayRef(TBLMask
.data(), IndexLen
)));
6519 return DAG
.getNode(ISD::BITCAST
, DL
, Op
.getValueType(), Shuffle
);
6522 static unsigned getDUPLANEOp(EVT EltType
) {
6523 if (EltType
== MVT::i8
)
6524 return AArch64ISD::DUPLANE8
;
6525 if (EltType
== MVT::i16
|| EltType
== MVT::f16
)
6526 return AArch64ISD::DUPLANE16
;
6527 if (EltType
== MVT::i32
|| EltType
== MVT::f32
)
6528 return AArch64ISD::DUPLANE32
;
6529 if (EltType
== MVT::i64
|| EltType
== MVT::f64
)
6530 return AArch64ISD::DUPLANE64
;
6532 llvm_unreachable("Invalid vector element type?");
6535 SDValue
AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op
,
6536 SelectionDAG
&DAG
) const {
6538 EVT VT
= Op
.getValueType();
6540 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(Op
.getNode());
6542 // Convert shuffles that are directly supported on NEON to target-specific
6543 // DAG nodes, instead of keeping them as shuffles and matching them again
6544 // during code selection. This is more efficient and avoids the possibility
6545 // of inconsistencies between legalization and selection.
6546 ArrayRef
<int> ShuffleMask
= SVN
->getMask();
6548 SDValue V1
= Op
.getOperand(0);
6549 SDValue V2
= Op
.getOperand(1);
6551 if (SVN
->isSplat()) {
6552 int Lane
= SVN
->getSplatIndex();
6553 // If this is undef splat, generate it via "just" vdup, if possible.
6557 if (Lane
== 0 && V1
.getOpcode() == ISD::SCALAR_TO_VECTOR
)
6558 return DAG
.getNode(AArch64ISD::DUP
, dl
, V1
.getValueType(),
6560 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6561 // constant. If so, we can just reference the lane's definition directly.
6562 if (V1
.getOpcode() == ISD::BUILD_VECTOR
&&
6563 !isa
<ConstantSDNode
>(V1
.getOperand(Lane
)))
6564 return DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, V1
.getOperand(Lane
));
6566 // Otherwise, duplicate from the lane of the input vector.
6567 unsigned Opcode
= getDUPLANEOp(V1
.getValueType().getVectorElementType());
6569 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6570 // to make a vector of the same size as this SHUFFLE. We can ignore the
6571 // extract entirely, and canonicalise the concat using WidenVector.
6572 if (V1
.getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
6573 Lane
+= cast
<ConstantSDNode
>(V1
.getOperand(1))->getZExtValue();
6574 V1
= V1
.getOperand(0);
6575 } else if (V1
.getOpcode() == ISD::CONCAT_VECTORS
) {
6576 unsigned Idx
= Lane
>= (int)VT
.getVectorNumElements() / 2;
6577 Lane
-= Idx
* VT
.getVectorNumElements() / 2;
6578 V1
= WidenVector(V1
.getOperand(Idx
), DAG
);
6579 } else if (VT
.getSizeInBits() == 64)
6580 V1
= WidenVector(V1
, DAG
);
6582 return DAG
.getNode(Opcode
, dl
, VT
, V1
, DAG
.getConstant(Lane
, dl
, MVT::i64
));
6585 if (isREVMask(ShuffleMask
, VT
, 64))
6586 return DAG
.getNode(AArch64ISD::REV64
, dl
, V1
.getValueType(), V1
, V2
);
6587 if (isREVMask(ShuffleMask
, VT
, 32))
6588 return DAG
.getNode(AArch64ISD::REV32
, dl
, V1
.getValueType(), V1
, V2
);
6589 if (isREVMask(ShuffleMask
, VT
, 16))
6590 return DAG
.getNode(AArch64ISD::REV16
, dl
, V1
.getValueType(), V1
, V2
);
6592 bool ReverseEXT
= false;
6594 if (isEXTMask(ShuffleMask
, VT
, ReverseEXT
, Imm
)) {
6597 Imm
*= getExtFactor(V1
);
6598 return DAG
.getNode(AArch64ISD::EXT
, dl
, V1
.getValueType(), V1
, V2
,
6599 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6600 } else if (V2
->isUndef() && isSingletonEXTMask(ShuffleMask
, VT
, Imm
)) {
6601 Imm
*= getExtFactor(V1
);
6602 return DAG
.getNode(AArch64ISD::EXT
, dl
, V1
.getValueType(), V1
, V1
,
6603 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6606 unsigned WhichResult
;
6607 if (isZIPMask(ShuffleMask
, VT
, WhichResult
)) {
6608 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::ZIP1
: AArch64ISD::ZIP2
;
6609 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6611 if (isUZPMask(ShuffleMask
, VT
, WhichResult
)) {
6612 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::UZP1
: AArch64ISD::UZP2
;
6613 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6615 if (isTRNMask(ShuffleMask
, VT
, WhichResult
)) {
6616 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::TRN1
: AArch64ISD::TRN2
;
6617 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6620 if (isZIP_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6621 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::ZIP1
: AArch64ISD::ZIP2
;
6622 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6624 if (isUZP_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6625 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::UZP1
: AArch64ISD::UZP2
;
6626 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6628 if (isTRN_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6629 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::TRN1
: AArch64ISD::TRN2
;
6630 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6633 if (SDValue Concat
= tryFormConcatFromShuffle(Op
, DAG
))
6638 int NumInputElements
= V1
.getValueType().getVectorNumElements();
6639 if (isINSMask(ShuffleMask
, NumInputElements
, DstIsLeft
, Anomaly
)) {
6640 SDValue DstVec
= DstIsLeft
? V1
: V2
;
6641 SDValue DstLaneV
= DAG
.getConstant(Anomaly
, dl
, MVT::i64
);
6643 SDValue SrcVec
= V1
;
6644 int SrcLane
= ShuffleMask
[Anomaly
];
6645 if (SrcLane
>= NumInputElements
) {
6647 SrcLane
-= VT
.getVectorNumElements();
6649 SDValue SrcLaneV
= DAG
.getConstant(SrcLane
, dl
, MVT::i64
);
6651 EVT ScalarVT
= VT
.getVectorElementType();
6653 if (ScalarVT
.getSizeInBits() < 32 && ScalarVT
.isInteger())
6654 ScalarVT
= MVT::i32
;
6657 ISD::INSERT_VECTOR_ELT
, dl
, VT
, DstVec
,
6658 DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, dl
, ScalarVT
, SrcVec
, SrcLaneV
),
6662 // If the shuffle is not directly supported and it has 4 elements, use
6663 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6664 unsigned NumElts
= VT
.getVectorNumElements();
6666 unsigned PFIndexes
[4];
6667 for (unsigned i
= 0; i
!= 4; ++i
) {
6668 if (ShuffleMask
[i
] < 0)
6671 PFIndexes
[i
] = ShuffleMask
[i
];
6674 // Compute the index in the perfect shuffle table.
6675 unsigned PFTableIndex
= PFIndexes
[0] * 9 * 9 * 9 + PFIndexes
[1] * 9 * 9 +
6676 PFIndexes
[2] * 9 + PFIndexes
[3];
6677 unsigned PFEntry
= PerfectShuffleTable
[PFTableIndex
];
6678 unsigned Cost
= (PFEntry
>> 30);
6681 return GeneratePerfectShuffle(PFEntry
, V1
, V2
, DAG
, dl
);
6684 return GenerateTBL(Op
, ShuffleMask
, DAG
);
6687 static bool resolveBuildVector(BuildVectorSDNode
*BVN
, APInt
&CnstBits
,
6689 EVT VT
= BVN
->getValueType(0);
6690 APInt SplatBits
, SplatUndef
;
6691 unsigned SplatBitSize
;
6693 if (BVN
->isConstantSplat(SplatBits
, SplatUndef
, SplatBitSize
, HasAnyUndefs
)) {
6694 unsigned NumSplats
= VT
.getSizeInBits() / SplatBitSize
;
6696 for (unsigned i
= 0; i
< NumSplats
; ++i
) {
6697 CnstBits
<<= SplatBitSize
;
6698 UndefBits
<<= SplatBitSize
;
6699 CnstBits
|= SplatBits
.zextOrTrunc(VT
.getSizeInBits());
6700 UndefBits
|= (SplatBits
^ SplatUndef
).zextOrTrunc(VT
.getSizeInBits());
6709 // Try 64-bit splatted SIMD immediate.
6710 static SDValue
tryAdvSIMDModImm64(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6711 const APInt
&Bits
) {
6712 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6713 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6714 EVT VT
= Op
.getValueType();
6715 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v2i64
: MVT::f64
;
6717 if (AArch64_AM::isAdvSIMDModImmType10(Value
)) {
6718 Value
= AArch64_AM::encodeAdvSIMDModImmType10(Value
);
6721 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6722 DAG
.getConstant(Value
, dl
, MVT::i32
));
6723 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6730 // Try 32-bit splatted SIMD immediate.
6731 static SDValue
tryAdvSIMDModImm32(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6733 const SDValue
*LHS
= nullptr) {
6734 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6735 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6736 EVT VT
= Op
.getValueType();
6737 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v4i32
: MVT::v2i32
;
6738 bool isAdvSIMDModImm
= false;
6741 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType1(Value
))) {
6742 Value
= AArch64_AM::encodeAdvSIMDModImmType1(Value
);
6745 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType2(Value
))) {
6746 Value
= AArch64_AM::encodeAdvSIMDModImmType2(Value
);
6749 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType3(Value
))) {
6750 Value
= AArch64_AM::encodeAdvSIMDModImmType3(Value
);
6753 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType4(Value
))) {
6754 Value
= AArch64_AM::encodeAdvSIMDModImmType4(Value
);
6758 if (isAdvSIMDModImm
) {
6763 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
, *LHS
,
6764 DAG
.getConstant(Value
, dl
, MVT::i32
),
6765 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6767 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6768 DAG
.getConstant(Value
, dl
, MVT::i32
),
6769 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6771 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6778 // Try 16-bit splatted SIMD immediate.
6779 static SDValue
tryAdvSIMDModImm16(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6781 const SDValue
*LHS
= nullptr) {
6782 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6783 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6784 EVT VT
= Op
.getValueType();
6785 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v8i16
: MVT::v4i16
;
6786 bool isAdvSIMDModImm
= false;
6789 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType5(Value
))) {
6790 Value
= AArch64_AM::encodeAdvSIMDModImmType5(Value
);
6793 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType6(Value
))) {
6794 Value
= AArch64_AM::encodeAdvSIMDModImmType6(Value
);
6798 if (isAdvSIMDModImm
) {
6803 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
, *LHS
,
6804 DAG
.getConstant(Value
, dl
, MVT::i32
),
6805 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6807 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6808 DAG
.getConstant(Value
, dl
, MVT::i32
),
6809 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6811 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6818 // Try 32-bit splatted SIMD immediate with shifted ones.
6819 static SDValue
tryAdvSIMDModImm321s(unsigned NewOp
, SDValue Op
,
6820 SelectionDAG
&DAG
, const APInt
&Bits
) {
6821 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6822 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6823 EVT VT
= Op
.getValueType();
6824 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v4i32
: MVT::v2i32
;
6825 bool isAdvSIMDModImm
= false;
6828 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType7(Value
))) {
6829 Value
= AArch64_AM::encodeAdvSIMDModImmType7(Value
);
6832 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType8(Value
))) {
6833 Value
= AArch64_AM::encodeAdvSIMDModImmType8(Value
);
6837 if (isAdvSIMDModImm
) {
6839 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6840 DAG
.getConstant(Value
, dl
, MVT::i32
),
6841 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6842 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6849 // Try 8-bit splatted SIMD immediate.
6850 static SDValue
tryAdvSIMDModImm8(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6851 const APInt
&Bits
) {
6852 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6853 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6854 EVT VT
= Op
.getValueType();
6855 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v16i8
: MVT::v8i8
;
6857 if (AArch64_AM::isAdvSIMDModImmType9(Value
)) {
6858 Value
= AArch64_AM::encodeAdvSIMDModImmType9(Value
);
6861 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6862 DAG
.getConstant(Value
, dl
, MVT::i32
));
6863 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6870 // Try FP splatted SIMD immediate.
6871 static SDValue
tryAdvSIMDModImmFP(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6872 const APInt
&Bits
) {
6873 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6874 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6875 EVT VT
= Op
.getValueType();
6876 bool isWide
= (VT
.getSizeInBits() == 128);
6878 bool isAdvSIMDModImm
= false;
6880 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType11(Value
))) {
6881 Value
= AArch64_AM::encodeAdvSIMDModImmType11(Value
);
6882 MovTy
= isWide
? MVT::v4f32
: MVT::v2f32
;
6885 (isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType12(Value
))) {
6886 Value
= AArch64_AM::encodeAdvSIMDModImmType12(Value
);
6890 if (isAdvSIMDModImm
) {
6892 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6893 DAG
.getConstant(Value
, dl
, MVT::i32
));
6894 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6901 SDValue
AArch64TargetLowering::LowerVectorAND(SDValue Op
,
6902 SelectionDAG
&DAG
) const {
6903 SDValue LHS
= Op
.getOperand(0);
6904 EVT VT
= Op
.getValueType();
6906 BuildVectorSDNode
*BVN
=
6907 dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(1).getNode());
6909 // AND commutes, so try swapping the operands.
6910 LHS
= Op
.getOperand(1);
6911 BVN
= dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(0).getNode());
6916 APInt
DefBits(VT
.getSizeInBits(), 0);
6917 APInt
UndefBits(VT
.getSizeInBits(), 0);
6918 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
6921 // We only have BIC vector immediate instruction, which is and-not.
6923 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::BICi
, Op
, DAG
,
6925 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::BICi
, Op
, DAG
,
6929 UndefBits
= ~UndefBits
;
6930 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::BICi
, Op
, DAG
,
6931 UndefBits
, &LHS
)) ||
6932 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::BICi
, Op
, DAG
,
6937 // We can always fall back to a non-immediate AND.
6941 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6942 // consists of only the same constant int value, returned in reference arg
6944 static bool isAllConstantBuildVector(const SDValue
&PotentialBVec
,
6945 uint64_t &ConstVal
) {
6946 BuildVectorSDNode
*Bvec
= dyn_cast
<BuildVectorSDNode
>(PotentialBVec
);
6949 ConstantSDNode
*FirstElt
= dyn_cast
<ConstantSDNode
>(Bvec
->getOperand(0));
6952 EVT VT
= Bvec
->getValueType(0);
6953 unsigned NumElts
= VT
.getVectorNumElements();
6954 for (unsigned i
= 1; i
< NumElts
; ++i
)
6955 if (dyn_cast
<ConstantSDNode
>(Bvec
->getOperand(i
)) != FirstElt
)
6957 ConstVal
= FirstElt
->getZExtValue();
6961 static unsigned getIntrinsicID(const SDNode
*N
) {
6962 unsigned Opcode
= N
->getOpcode();
6965 return Intrinsic::not_intrinsic
;
6966 case ISD::INTRINSIC_WO_CHAIN
: {
6967 unsigned IID
= cast
<ConstantSDNode
>(N
->getOperand(0))->getZExtValue();
6968 if (IID
< Intrinsic::num_intrinsics
)
6970 return Intrinsic::not_intrinsic
;
6975 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6976 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6977 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6978 // Also, logical shift right -> sri, with the same structure.
6979 static SDValue
tryLowerToSLI(SDNode
*N
, SelectionDAG
&DAG
) {
6980 EVT VT
= N
->getValueType(0);
6987 // Is the first op an AND?
6988 const SDValue And
= N
->getOperand(0);
6989 if (And
.getOpcode() != ISD::AND
)
6992 // Is the second op an shl or lshr?
6993 SDValue Shift
= N
->getOperand(1);
6994 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6995 // or AArch64ISD::VLSHR vector, #shift
6996 unsigned ShiftOpc
= Shift
.getOpcode();
6997 if ((ShiftOpc
!= AArch64ISD::VSHL
&& ShiftOpc
!= AArch64ISD::VLSHR
))
6999 bool IsShiftRight
= ShiftOpc
== AArch64ISD::VLSHR
;
7001 // Is the shift amount constant?
7002 ConstantSDNode
*C2node
= dyn_cast
<ConstantSDNode
>(Shift
.getOperand(1));
7006 // Is the and mask vector all constant?
7008 if (!isAllConstantBuildVector(And
.getOperand(1), C1
))
7011 // Is C1 == ~C2, taking into account how much one can shift elements of a
7013 uint64_t C2
= C2node
->getZExtValue();
7014 unsigned ElemSizeInBits
= VT
.getScalarSizeInBits();
7015 if (C2
> ElemSizeInBits
)
7017 unsigned ElemMask
= (1 << ElemSizeInBits
) - 1;
7018 if ((C1
& ElemMask
) != (~C2
& ElemMask
))
7021 SDValue X
= And
.getOperand(0);
7022 SDValue Y
= Shift
.getOperand(0);
7025 IsShiftRight
? Intrinsic::aarch64_neon_vsri
: Intrinsic::aarch64_neon_vsli
;
7027 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7028 DAG
.getConstant(Intrin
, DL
, MVT::i32
), X
, Y
,
7029 Shift
.getOperand(1));
7031 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7032 LLVM_DEBUG(N
->dump(&DAG
));
7033 LLVM_DEBUG(dbgs() << "into: \n");
7034 LLVM_DEBUG(ResultSLI
->dump(&DAG
));
7040 SDValue
AArch64TargetLowering::LowerVectorOR(SDValue Op
,
7041 SelectionDAG
&DAG
) const {
7042 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7043 if (EnableAArch64SlrGeneration
) {
7044 if (SDValue Res
= tryLowerToSLI(Op
.getNode(), DAG
))
7048 EVT VT
= Op
.getValueType();
7050 SDValue LHS
= Op
.getOperand(0);
7051 BuildVectorSDNode
*BVN
=
7052 dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(1).getNode());
7054 // OR commutes, so try swapping the operands.
7055 LHS
= Op
.getOperand(1);
7056 BVN
= dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(0).getNode());
7061 APInt
DefBits(VT
.getSizeInBits(), 0);
7062 APInt
UndefBits(VT
.getSizeInBits(), 0);
7063 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
7066 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::ORRi
, Op
, DAG
,
7068 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::ORRi
, Op
, DAG
,
7072 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::ORRi
, Op
, DAG
,
7073 UndefBits
, &LHS
)) ||
7074 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::ORRi
, Op
, DAG
,
7079 // We can always fall back to a non-immediate OR.
7083 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7084 // be truncated to fit element width.
7085 static SDValue
NormalizeBuildVector(SDValue Op
,
7086 SelectionDAG
&DAG
) {
7087 assert(Op
.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!");
7089 EVT VT
= Op
.getValueType();
7090 EVT EltTy
= VT
.getVectorElementType();
7092 if (EltTy
.isFloatingPoint() || EltTy
.getSizeInBits() > 16)
7095 SmallVector
<SDValue
, 16> Ops
;
7096 for (SDValue Lane
: Op
->ops()) {
7097 // For integer vectors, type legalization would have promoted the
7098 // operands already. Otherwise, if Op is a floating-point splat
7099 // (with operands cast to integers), then the only possibilities
7100 // are constants and UNDEFs.
7101 if (auto *CstLane
= dyn_cast
<ConstantSDNode
>(Lane
)) {
7102 APInt
LowBits(EltTy
.getSizeInBits(),
7103 CstLane
->getZExtValue());
7104 Lane
= DAG
.getConstant(LowBits
.getZExtValue(), dl
, MVT::i32
);
7105 } else if (Lane
.getNode()->isUndef()) {
7106 Lane
= DAG
.getUNDEF(MVT::i32
);
7108 assert(Lane
.getValueType() == MVT::i32
&&
7109 "Unexpected BUILD_VECTOR operand type");
7111 Ops
.push_back(Lane
);
7113 return DAG
.getBuildVector(VT
, dl
, Ops
);
7116 static SDValue
ConstantBuildVector(SDValue Op
, SelectionDAG
&DAG
) {
7117 EVT VT
= Op
.getValueType();
7119 APInt
DefBits(VT
.getSizeInBits(), 0);
7120 APInt
UndefBits(VT
.getSizeInBits(), 0);
7121 BuildVectorSDNode
*BVN
= cast
<BuildVectorSDNode
>(Op
.getNode());
7122 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
7124 if ((NewOp
= tryAdvSIMDModImm64(AArch64ISD::MOVIedit
, Op
, DAG
, DefBits
)) ||
7125 (NewOp
= tryAdvSIMDModImm32(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7126 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MOVImsl
, Op
, DAG
, DefBits
)) ||
7127 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7128 (NewOp
= tryAdvSIMDModImm8(AArch64ISD::MOVI
, Op
, DAG
, DefBits
)) ||
7129 (NewOp
= tryAdvSIMDModImmFP(AArch64ISD::FMOV
, Op
, DAG
, DefBits
)))
7133 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)) ||
7134 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MVNImsl
, Op
, DAG
, DefBits
)) ||
7135 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)))
7138 DefBits
= UndefBits
;
7139 if ((NewOp
= tryAdvSIMDModImm64(AArch64ISD::MOVIedit
, Op
, DAG
, DefBits
)) ||
7140 (NewOp
= tryAdvSIMDModImm32(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7141 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MOVImsl
, Op
, DAG
, DefBits
)) ||
7142 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7143 (NewOp
= tryAdvSIMDModImm8(AArch64ISD::MOVI
, Op
, DAG
, DefBits
)) ||
7144 (NewOp
= tryAdvSIMDModImmFP(AArch64ISD::FMOV
, Op
, DAG
, DefBits
)))
7147 DefBits
= ~UndefBits
;
7148 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)) ||
7149 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MVNImsl
, Op
, DAG
, DefBits
)) ||
7150 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)))
7157 SDValue
AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op
,
7158 SelectionDAG
&DAG
) const {
7159 EVT VT
= Op
.getValueType();
7161 // Try to build a simple constant vector.
7162 Op
= NormalizeBuildVector(Op
, DAG
);
7163 if (VT
.isInteger()) {
7164 // Certain vector constants, used to express things like logical NOT and
7165 // arithmetic NEG, are passed through unmodified. This allows special
7166 // patterns for these operations to match, which will lower these constants
7167 // to whatever is proven necessary.
7168 BuildVectorSDNode
*BVN
= cast
<BuildVectorSDNode
>(Op
.getNode());
7169 if (BVN
->isConstant())
7170 if (ConstantSDNode
*Const
= BVN
->getConstantSplatNode()) {
7171 unsigned BitSize
= VT
.getVectorElementType().getSizeInBits();
7173 Const
->getAPIntValue().zextOrTrunc(BitSize
).getZExtValue());
7174 if (Val
.isNullValue() || Val
.isAllOnesValue())
7179 if (SDValue V
= ConstantBuildVector(Op
, DAG
))
7182 // Scan through the operands to find some interesting properties we can
7184 // 1) If only one value is used, we can use a DUP, or
7185 // 2) if only the low element is not undef, we can just insert that, or
7186 // 3) if only one constant value is used (w/ some non-constant lanes),
7187 // we can splat the constant value into the whole vector then fill
7188 // in the non-constant lanes.
7189 // 4) FIXME: If different constant values are used, but we can intelligently
7190 // select the values we'll be overwriting for the non-constant
7191 // lanes such that we can directly materialize the vector
7192 // some other way (MOVI, e.g.), we can be sneaky.
7193 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7195 unsigned NumElts
= VT
.getVectorNumElements();
7196 bool isOnlyLowElement
= true;
7197 bool usesOnlyOneValue
= true;
7198 bool usesOnlyOneConstantValue
= true;
7199 bool isConstant
= true;
7200 bool AllLanesExtractElt
= true;
7201 unsigned NumConstantLanes
= 0;
7203 SDValue ConstantValue
;
7204 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7205 SDValue V
= Op
.getOperand(i
);
7206 if (V
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
)
7207 AllLanesExtractElt
= false;
7211 isOnlyLowElement
= false;
7212 if (!isa
<ConstantFPSDNode
>(V
) && !isa
<ConstantSDNode
>(V
))
7215 if (isa
<ConstantSDNode
>(V
) || isa
<ConstantFPSDNode
>(V
)) {
7217 if (!ConstantValue
.getNode())
7219 else if (ConstantValue
!= V
)
7220 usesOnlyOneConstantValue
= false;
7223 if (!Value
.getNode())
7225 else if (V
!= Value
)
7226 usesOnlyOneValue
= false;
7229 if (!Value
.getNode()) {
7231 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7232 return DAG
.getUNDEF(VT
);
7235 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7236 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7237 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7238 if (isOnlyLowElement
&& !(NumElts
== 1 && isa
<ConstantSDNode
>(Value
))) {
7239 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7240 "SCALAR_TO_VECTOR node\n");
7241 return DAG
.getNode(ISD::SCALAR_TO_VECTOR
, dl
, VT
, Value
);
7244 if (AllLanesExtractElt
) {
7245 SDNode
*Vector
= nullptr;
7248 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7249 // the Odd pattern <1,3,5,...>.
7250 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7251 SDValue V
= Op
.getOperand(i
);
7252 const SDNode
*N
= V
.getNode();
7253 if (!isa
<ConstantSDNode
>(N
->getOperand(1)))
7255 SDValue N0
= N
->getOperand(0);
7257 // All elements are extracted from the same vector.
7259 Vector
= N0
.getNode();
7260 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7262 if (VT
.getVectorElementType() !=
7263 N0
.getValueType().getVectorElementType())
7265 } else if (Vector
!= N0
.getNode()) {
7271 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7272 // indices <1,3,5,...>.
7273 uint64_t Val
= N
->getConstantOperandVal(1);
7278 if (Val
- 1 == 2 * i
) {
7283 // Something does not match: abort.
7290 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, SDValue(Vector
, 0),
7291 DAG
.getConstant(0, dl
, MVT::i64
));
7293 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, SDValue(Vector
, 0),
7294 DAG
.getConstant(NumElts
, dl
, MVT::i64
));
7297 return DAG
.getNode(AArch64ISD::UZP1
, dl
, DAG
.getVTList(VT
, VT
), LHS
,
7300 return DAG
.getNode(AArch64ISD::UZP2
, dl
, DAG
.getVTList(VT
, VT
), LHS
,
7305 // Use DUP for non-constant splats. For f32 constant splats, reduce to
7306 // i32 and try again.
7307 if (usesOnlyOneValue
) {
7309 if (Value
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
7310 Value
.getValueType() != VT
) {
7312 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7313 return DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, Value
);
7316 // This is actually a DUPLANExx operation, which keeps everything vectory.
7318 SDValue Lane
= Value
.getOperand(1);
7319 Value
= Value
.getOperand(0);
7320 if (Value
.getValueSizeInBits() == 64) {
7322 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7324 Value
= WidenVector(Value
, DAG
);
7327 unsigned Opcode
= getDUPLANEOp(VT
.getVectorElementType());
7328 return DAG
.getNode(Opcode
, dl
, VT
, Value
, Lane
);
7331 if (VT
.getVectorElementType().isFloatingPoint()) {
7332 SmallVector
<SDValue
, 8> Ops
;
7333 EVT EltTy
= VT
.getVectorElementType();
7334 assert ((EltTy
== MVT::f16
|| EltTy
== MVT::f32
|| EltTy
== MVT::f64
) &&
7335 "Unsupported floating-point vector type");
7337 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7338 "BITCASTS, and try again\n");
7339 MVT NewType
= MVT::getIntegerVT(EltTy
.getSizeInBits());
7340 for (unsigned i
= 0; i
< NumElts
; ++i
)
7341 Ops
.push_back(DAG
.getNode(ISD::BITCAST
, dl
, NewType
, Op
.getOperand(i
)));
7342 EVT VecVT
= EVT::getVectorVT(*DAG
.getContext(), NewType
, NumElts
);
7343 SDValue Val
= DAG
.getBuildVector(VecVT
, dl
, Ops
);
7344 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7346 Val
= LowerBUILD_VECTOR(Val
, DAG
);
7348 return DAG
.getNode(ISD::BITCAST
, dl
, VT
, Val
);
7352 // If there was only one constant value used and for more than one lane,
7353 // start by splatting that value, then replace the non-constant lanes. This
7354 // is better than the default, which will perform a separate initialization
7356 if (NumConstantLanes
> 0 && usesOnlyOneConstantValue
) {
7357 // Firstly, try to materialize the splat constant.
7358 SDValue Vec
= DAG
.getSplatBuildVector(VT
, dl
, ConstantValue
),
7359 Val
= ConstantBuildVector(Vec
, DAG
);
7361 // Otherwise, materialize the constant and splat it.
7362 Val
= DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, ConstantValue
);
7363 DAG
.ReplaceAllUsesWith(Vec
.getNode(), &Val
);
7366 // Now insert the non-constant lanes.
7367 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7368 SDValue V
= Op
.getOperand(i
);
7369 SDValue LaneIdx
= DAG
.getConstant(i
, dl
, MVT::i64
);
7370 if (!isa
<ConstantSDNode
>(V
) && !isa
<ConstantFPSDNode
>(V
))
7371 // Note that type legalization likely mucked about with the VT of the
7372 // source operand, so we may have to convert it here before inserting.
7373 Val
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, dl
, VT
, Val
, V
, LaneIdx
);
7378 // This will generate a load from the constant pool.
7381 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7386 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7388 if (SDValue shuffle
= ReconstructShuffle(Op
, DAG
))
7392 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7393 // know the default expansion would otherwise fall back on something even
7394 // worse. For a vector with one or two non-undef values, that's
7395 // scalar_to_vector for the elements followed by a shuffle (provided the
7396 // shuffle is valid for the target) and materialization element by element
7397 // on the stack followed by a load for everything else.
7398 if (!isConstant
&& !usesOnlyOneValue
) {
7400 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7401 "of INSERT_VECTOR_ELT\n");
7403 SDValue Vec
= DAG
.getUNDEF(VT
);
7404 SDValue Op0
= Op
.getOperand(0);
7407 // Use SCALAR_TO_VECTOR for lane zero to
7408 // a) Avoid a RMW dependency on the full vector register, and
7409 // b) Allow the register coalescer to fold away the copy if the
7410 // value is already in an S or D register, and we're forced to emit an
7411 // INSERT_SUBREG that we can't fold anywhere.
7413 // We also allow types like i8 and i16 which are illegal scalar but legal
7414 // vector element types. After type-legalization the inserted value is
7415 // extended (i32) and it is safe to cast them to the vector type by ignoring
7416 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7417 if (!Op0
.isUndef()) {
7418 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7419 Vec
= DAG
.getNode(ISD::SCALAR_TO_VECTOR
, dl
, VT
, Op0
);
7422 LLVM_DEBUG(if (i
< NumElts
) dbgs()
7423 << "Creating nodes for the other vector elements:\n";);
7424 for (; i
< NumElts
; ++i
) {
7425 SDValue V
= Op
.getOperand(i
);
7428 SDValue LaneIdx
= DAG
.getConstant(i
, dl
, MVT::i64
);
7429 Vec
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, dl
, VT
, Vec
, V
, LaneIdx
);
7435 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7436 "better alternative\n");
7440 SDValue
AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op
,
7441 SelectionDAG
&DAG
) const {
7442 assert(Op
.getOpcode() == ISD::INSERT_VECTOR_ELT
&& "Unknown opcode!");
7444 // Check for non-constant or out of range lane.
7445 EVT VT
= Op
.getOperand(0).getValueType();
7446 ConstantSDNode
*CI
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
7447 if (!CI
|| CI
->getZExtValue() >= VT
.getVectorNumElements())
7451 // Insertion/extraction are legal for V128 types.
7452 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
||
7453 VT
== MVT::v2i64
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
||
7457 if (VT
!= MVT::v8i8
&& VT
!= MVT::v4i16
&& VT
!= MVT::v2i32
&&
7458 VT
!= MVT::v1i64
&& VT
!= MVT::v2f32
&& VT
!= MVT::v4f16
)
7461 // For V64 types, we perform insertion by expanding the value
7462 // to a V128 type and perform the insertion on that.
7464 SDValue WideVec
= WidenVector(Op
.getOperand(0), DAG
);
7465 EVT WideTy
= WideVec
.getValueType();
7467 SDValue Node
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, DL
, WideTy
, WideVec
,
7468 Op
.getOperand(1), Op
.getOperand(2));
7469 // Re-narrow the resultant vector.
7470 return NarrowVector(Node
, DAG
);
7474 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op
,
7475 SelectionDAG
&DAG
) const {
7476 assert(Op
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&& "Unknown opcode!");
7478 // Check for non-constant or out of range lane.
7479 EVT VT
= Op
.getOperand(0).getValueType();
7480 ConstantSDNode
*CI
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
7481 if (!CI
|| CI
->getZExtValue() >= VT
.getVectorNumElements())
7485 // Insertion/extraction are legal for V128 types.
7486 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
||
7487 VT
== MVT::v2i64
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
||
7491 if (VT
!= MVT::v8i8
&& VT
!= MVT::v4i16
&& VT
!= MVT::v2i32
&&
7492 VT
!= MVT::v1i64
&& VT
!= MVT::v2f32
&& VT
!= MVT::v4f16
)
7495 // For V64 types, we perform extraction by expanding the value
7496 // to a V128 type and perform the extraction on that.
7498 SDValue WideVec
= WidenVector(Op
.getOperand(0), DAG
);
7499 EVT WideTy
= WideVec
.getValueType();
7501 EVT ExtrTy
= WideTy
.getVectorElementType();
7502 if (ExtrTy
== MVT::i16
|| ExtrTy
== MVT::i8
)
7505 // For extractions, we just return the result directly.
7506 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ExtrTy
, WideVec
,
7510 SDValue
AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op
,
7511 SelectionDAG
&DAG
) const {
7512 EVT VT
= Op
.getOperand(0).getValueType();
7518 ConstantSDNode
*Cst
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
7521 unsigned Val
= Cst
->getZExtValue();
7523 unsigned Size
= Op
.getValueSizeInBits();
7525 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7529 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7531 if (Size
== 64 && Val
* VT
.getScalarSizeInBits() == 64)
7537 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef
<int> M
, EVT VT
) const {
7538 if (VT
.getVectorNumElements() == 4 &&
7539 (VT
.is128BitVector() || VT
.is64BitVector())) {
7540 unsigned PFIndexes
[4];
7541 for (unsigned i
= 0; i
!= 4; ++i
) {
7545 PFIndexes
[i
] = M
[i
];
7548 // Compute the index in the perfect shuffle table.
7549 unsigned PFTableIndex
= PFIndexes
[0] * 9 * 9 * 9 + PFIndexes
[1] * 9 * 9 +
7550 PFIndexes
[2] * 9 + PFIndexes
[3];
7551 unsigned PFEntry
= PerfectShuffleTable
[PFTableIndex
];
7552 unsigned Cost
= (PFEntry
>> 30);
7560 unsigned DummyUnsigned
;
7562 return (ShuffleVectorSDNode::isSplatMask(&M
[0], VT
) || isREVMask(M
, VT
, 64) ||
7563 isREVMask(M
, VT
, 32) || isREVMask(M
, VT
, 16) ||
7564 isEXTMask(M
, VT
, DummyBool
, DummyUnsigned
) ||
7565 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7566 isTRNMask(M
, VT
, DummyUnsigned
) || isUZPMask(M
, VT
, DummyUnsigned
) ||
7567 isZIPMask(M
, VT
, DummyUnsigned
) ||
7568 isTRN_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7569 isUZP_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7570 isZIP_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7571 isINSMask(M
, VT
.getVectorNumElements(), DummyBool
, DummyInt
) ||
7572 isConcatMask(M
, VT
, VT
.getSizeInBits() == 128));
7575 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7576 /// operand of a vector shift operation, where all the elements of the
7577 /// build_vector must have the same constant integer value.
7578 static bool getVShiftImm(SDValue Op
, unsigned ElementBits
, int64_t &Cnt
) {
7579 // Ignore bit_converts.
7580 while (Op
.getOpcode() == ISD::BITCAST
)
7581 Op
= Op
.getOperand(0);
7582 BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(Op
.getNode());
7583 APInt SplatBits
, SplatUndef
;
7584 unsigned SplatBitSize
;
7586 if (!BVN
|| !BVN
->isConstantSplat(SplatBits
, SplatUndef
, SplatBitSize
,
7587 HasAnyUndefs
, ElementBits
) ||
7588 SplatBitSize
> ElementBits
)
7590 Cnt
= SplatBits
.getSExtValue();
7594 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7595 /// operand of a vector shift left operation. That value must be in the range:
7596 /// 0 <= Value < ElementBits for a left shift; or
7597 /// 0 <= Value <= ElementBits for a long left shift.
7598 static bool isVShiftLImm(SDValue Op
, EVT VT
, bool isLong
, int64_t &Cnt
) {
7599 assert(VT
.isVector() && "vector shift count is not a vector type");
7600 int64_t ElementBits
= VT
.getScalarSizeInBits();
7601 if (!getVShiftImm(Op
, ElementBits
, Cnt
))
7603 return (Cnt
>= 0 && (isLong
? Cnt
- 1 : Cnt
) < ElementBits
);
7606 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7607 /// operand of a vector shift right operation. The value must be in the range:
7608 /// 1 <= Value <= ElementBits for a right shift; or
7609 static bool isVShiftRImm(SDValue Op
, EVT VT
, bool isNarrow
, int64_t &Cnt
) {
7610 assert(VT
.isVector() && "vector shift count is not a vector type");
7611 int64_t ElementBits
= VT
.getScalarSizeInBits();
7612 if (!getVShiftImm(Op
, ElementBits
, Cnt
))
7614 return (Cnt
>= 1 && Cnt
<= (isNarrow
? ElementBits
/ 2 : ElementBits
));
7617 SDValue
AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op
,
7618 SelectionDAG
&DAG
) const {
7619 EVT VT
= Op
.getValueType();
7623 if (!Op
.getOperand(1).getValueType().isVector())
7625 unsigned EltSize
= VT
.getScalarSizeInBits();
7627 switch (Op
.getOpcode()) {
7629 llvm_unreachable("unexpected shift opcode");
7632 if (isVShiftLImm(Op
.getOperand(1), VT
, false, Cnt
) && Cnt
< EltSize
)
7633 return DAG
.getNode(AArch64ISD::VSHL
, DL
, VT
, Op
.getOperand(0),
7634 DAG
.getConstant(Cnt
, DL
, MVT::i32
));
7635 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7636 DAG
.getConstant(Intrinsic::aarch64_neon_ushl
, DL
,
7638 Op
.getOperand(0), Op
.getOperand(1));
7641 // Right shift immediate
7642 if (isVShiftRImm(Op
.getOperand(1), VT
, false, Cnt
) && Cnt
< EltSize
) {
7644 (Op
.getOpcode() == ISD::SRA
) ? AArch64ISD::VASHR
: AArch64ISD::VLSHR
;
7645 return DAG
.getNode(Opc
, DL
, VT
, Op
.getOperand(0),
7646 DAG
.getConstant(Cnt
, DL
, MVT::i32
));
7649 // Right shift register. Note, there is not a shift right register
7650 // instruction, but the shift left register instruction takes a signed
7651 // value, where negative numbers specify a right shift.
7652 unsigned Opc
= (Op
.getOpcode() == ISD::SRA
) ? Intrinsic::aarch64_neon_sshl
7653 : Intrinsic::aarch64_neon_ushl
;
7654 // negate the shift amount
7655 SDValue NegShift
= DAG
.getNode(AArch64ISD::NEG
, DL
, VT
, Op
.getOperand(1));
7656 SDValue NegShiftLeft
=
7657 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7658 DAG
.getConstant(Opc
, DL
, MVT::i32
), Op
.getOperand(0),
7660 return NegShiftLeft
;
7666 static SDValue
EmitVectorComparison(SDValue LHS
, SDValue RHS
,
7667 AArch64CC::CondCode CC
, bool NoNans
, EVT VT
,
7668 const SDLoc
&dl
, SelectionDAG
&DAG
) {
7669 EVT SrcVT
= LHS
.getValueType();
7670 assert(VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
7671 "function only supposed to emit natural comparisons");
7673 BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(RHS
.getNode());
7674 APInt
CnstBits(VT
.getSizeInBits(), 0);
7675 APInt
UndefBits(VT
.getSizeInBits(), 0);
7676 bool IsCnst
= BVN
&& resolveBuildVector(BVN
, CnstBits
, UndefBits
);
7677 bool IsZero
= IsCnst
&& (CnstBits
== 0);
7679 if (SrcVT
.getVectorElementType().isFloatingPoint()) {
7683 case AArch64CC::NE
: {
7686 Fcmeq
= DAG
.getNode(AArch64ISD::FCMEQz
, dl
, VT
, LHS
);
7688 Fcmeq
= DAG
.getNode(AArch64ISD::FCMEQ
, dl
, VT
, LHS
, RHS
);
7689 return DAG
.getNode(AArch64ISD::NOT
, dl
, VT
, Fcmeq
);
7693 return DAG
.getNode(AArch64ISD::FCMEQz
, dl
, VT
, LHS
);
7694 return DAG
.getNode(AArch64ISD::FCMEQ
, dl
, VT
, LHS
, RHS
);
7697 return DAG
.getNode(AArch64ISD::FCMGEz
, dl
, VT
, LHS
);
7698 return DAG
.getNode(AArch64ISD::FCMGE
, dl
, VT
, LHS
, RHS
);
7701 return DAG
.getNode(AArch64ISD::FCMGTz
, dl
, VT
, LHS
);
7702 return DAG
.getNode(AArch64ISD::FCMGT
, dl
, VT
, LHS
, RHS
);
7705 return DAG
.getNode(AArch64ISD::FCMLEz
, dl
, VT
, LHS
);
7706 return DAG
.getNode(AArch64ISD::FCMGE
, dl
, VT
, RHS
, LHS
);
7710 // If we ignore NaNs then we can use to the MI implementation.
7714 return DAG
.getNode(AArch64ISD::FCMLTz
, dl
, VT
, LHS
);
7715 return DAG
.getNode(AArch64ISD::FCMGT
, dl
, VT
, RHS
, LHS
);
7722 case AArch64CC::NE
: {
7725 Cmeq
= DAG
.getNode(AArch64ISD::CMEQz
, dl
, VT
, LHS
);
7727 Cmeq
= DAG
.getNode(AArch64ISD::CMEQ
, dl
, VT
, LHS
, RHS
);
7728 return DAG
.getNode(AArch64ISD::NOT
, dl
, VT
, Cmeq
);
7732 return DAG
.getNode(AArch64ISD::CMEQz
, dl
, VT
, LHS
);
7733 return DAG
.getNode(AArch64ISD::CMEQ
, dl
, VT
, LHS
, RHS
);
7736 return DAG
.getNode(AArch64ISD::CMGEz
, dl
, VT
, LHS
);
7737 return DAG
.getNode(AArch64ISD::CMGE
, dl
, VT
, LHS
, RHS
);
7740 return DAG
.getNode(AArch64ISD::CMGTz
, dl
, VT
, LHS
);
7741 return DAG
.getNode(AArch64ISD::CMGT
, dl
, VT
, LHS
, RHS
);
7744 return DAG
.getNode(AArch64ISD::CMLEz
, dl
, VT
, LHS
);
7745 return DAG
.getNode(AArch64ISD::CMGE
, dl
, VT
, RHS
, LHS
);
7747 return DAG
.getNode(AArch64ISD::CMHS
, dl
, VT
, RHS
, LHS
);
7749 return DAG
.getNode(AArch64ISD::CMHI
, dl
, VT
, RHS
, LHS
);
7752 return DAG
.getNode(AArch64ISD::CMLTz
, dl
, VT
, LHS
);
7753 return DAG
.getNode(AArch64ISD::CMGT
, dl
, VT
, RHS
, LHS
);
7755 return DAG
.getNode(AArch64ISD::CMHI
, dl
, VT
, LHS
, RHS
);
7757 return DAG
.getNode(AArch64ISD::CMHS
, dl
, VT
, LHS
, RHS
);
7761 SDValue
AArch64TargetLowering::LowerVSETCC(SDValue Op
,
7762 SelectionDAG
&DAG
) const {
7763 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
7764 SDValue LHS
= Op
.getOperand(0);
7765 SDValue RHS
= Op
.getOperand(1);
7766 EVT CmpVT
= LHS
.getValueType().changeVectorElementTypeToInteger();
7769 if (LHS
.getValueType().getVectorElementType().isInteger()) {
7770 assert(LHS
.getValueType() == RHS
.getValueType());
7771 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
7773 EmitVectorComparison(LHS
, RHS
, AArch64CC
, false, CmpVT
, dl
, DAG
);
7774 return DAG
.getSExtOrTrunc(Cmp
, dl
, Op
.getValueType());
7777 const bool FullFP16
=
7778 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
7780 // Make v4f16 (only) fcmp operations utilise vector instructions
7781 // v8f16 support will be a litle more complicated
7782 if (LHS
.getValueType().getVectorElementType() == MVT::f16
) {
7783 if (!FullFP16
&& LHS
.getValueType().getVectorNumElements() == 4) {
7784 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::v4f32
, LHS
);
7785 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::v4f32
, RHS
);
7786 SDValue NewSetcc
= DAG
.getSetCC(dl
, MVT::v4i16
, LHS
, RHS
, CC
);
7787 DAG
.ReplaceAllUsesWith(Op
, NewSetcc
);
7793 assert(LHS
.getValueType().getVectorElementType() == MVT::f32
||
7794 LHS
.getValueType().getVectorElementType() == MVT::f64
);
7796 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7797 // clean. Some of them require two branches to implement.
7798 AArch64CC::CondCode CC1
, CC2
;
7800 changeVectorFPCCToAArch64CC(CC
, CC1
, CC2
, ShouldInvert
);
7802 bool NoNaNs
= getTargetMachine().Options
.NoNaNsFPMath
;
7804 EmitVectorComparison(LHS
, RHS
, CC1
, NoNaNs
, CmpVT
, dl
, DAG
);
7808 if (CC2
!= AArch64CC::AL
) {
7810 EmitVectorComparison(LHS
, RHS
, CC2
, NoNaNs
, CmpVT
, dl
, DAG
);
7811 if (!Cmp2
.getNode())
7814 Cmp
= DAG
.getNode(ISD::OR
, dl
, CmpVT
, Cmp
, Cmp2
);
7817 Cmp
= DAG
.getSExtOrTrunc(Cmp
, dl
, Op
.getValueType());
7820 Cmp
= DAG
.getNOT(dl
, Cmp
, Cmp
.getValueType());
7825 static SDValue
getReductionSDNode(unsigned Op
, SDLoc DL
, SDValue ScalarOp
,
7826 SelectionDAG
&DAG
) {
7827 SDValue VecOp
= ScalarOp
.getOperand(0);
7828 auto Rdx
= DAG
.getNode(Op
, DL
, VecOp
.getSimpleValueType(), VecOp
);
7829 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ScalarOp
.getValueType(), Rdx
,
7830 DAG
.getConstant(0, DL
, MVT::i64
));
7833 SDValue
AArch64TargetLowering::LowerVECREDUCE(SDValue Op
,
7834 SelectionDAG
&DAG
) const {
7836 switch (Op
.getOpcode()) {
7837 case ISD::VECREDUCE_ADD
:
7838 return getReductionSDNode(AArch64ISD::UADDV
, dl
, Op
, DAG
);
7839 case ISD::VECREDUCE_SMAX
:
7840 return getReductionSDNode(AArch64ISD::SMAXV
, dl
, Op
, DAG
);
7841 case ISD::VECREDUCE_SMIN
:
7842 return getReductionSDNode(AArch64ISD::SMINV
, dl
, Op
, DAG
);
7843 case ISD::VECREDUCE_UMAX
:
7844 return getReductionSDNode(AArch64ISD::UMAXV
, dl
, Op
, DAG
);
7845 case ISD::VECREDUCE_UMIN
:
7846 return getReductionSDNode(AArch64ISD::UMINV
, dl
, Op
, DAG
);
7847 case ISD::VECREDUCE_FMAX
: {
7848 assert(Op
->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7850 ISD::INTRINSIC_WO_CHAIN
, dl
, Op
.getValueType(),
7851 DAG
.getConstant(Intrinsic::aarch64_neon_fmaxnmv
, dl
, MVT::i32
),
7854 case ISD::VECREDUCE_FMIN
: {
7855 assert(Op
->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7857 ISD::INTRINSIC_WO_CHAIN
, dl
, Op
.getValueType(),
7858 DAG
.getConstant(Intrinsic::aarch64_neon_fminnmv
, dl
, MVT::i32
),
7862 llvm_unreachable("Unhandled reduction");
7866 SDValue
AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op
,
7867 SelectionDAG
&DAG
) const {
7868 auto &Subtarget
= static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget());
7869 if (!Subtarget
.hasLSE())
7872 // LSE has an atomic load-add instruction, but not a load-sub.
7874 MVT VT
= Op
.getSimpleValueType();
7875 SDValue RHS
= Op
.getOperand(2);
7876 AtomicSDNode
*AN
= cast
<AtomicSDNode
>(Op
.getNode());
7877 RHS
= DAG
.getNode(ISD::SUB
, dl
, VT
, DAG
.getConstant(0, dl
, VT
), RHS
);
7878 return DAG
.getAtomic(ISD::ATOMIC_LOAD_ADD
, dl
, AN
->getMemoryVT(),
7879 Op
.getOperand(0), Op
.getOperand(1), RHS
,
7880 AN
->getMemOperand());
7883 SDValue
AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op
,
7884 SelectionDAG
&DAG
) const {
7885 auto &Subtarget
= static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget());
7886 if (!Subtarget
.hasLSE())
7889 // LSE has an atomic load-clear instruction, but not a load-and.
7891 MVT VT
= Op
.getSimpleValueType();
7892 SDValue RHS
= Op
.getOperand(2);
7893 AtomicSDNode
*AN
= cast
<AtomicSDNode
>(Op
.getNode());
7894 RHS
= DAG
.getNode(ISD::XOR
, dl
, VT
, DAG
.getConstant(-1ULL, dl
, VT
), RHS
);
7895 return DAG
.getAtomic(ISD::ATOMIC_LOAD_CLR
, dl
, AN
->getMemoryVT(),
7896 Op
.getOperand(0), Op
.getOperand(1), RHS
,
7897 AN
->getMemOperand());
7900 SDValue
AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7901 SDValue Op
, SDValue Chain
, SDValue
&Size
, SelectionDAG
&DAG
) const {
7903 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
7904 SDValue Callee
= DAG
.getTargetExternalSymbol("__chkstk", PtrVT
, 0);
7906 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
7907 const uint32_t *Mask
= TRI
->getWindowsStackProbePreservedMask();
7908 if (Subtarget
->hasCustomCallingConv())
7909 TRI
->UpdateCustomCallPreservedMask(DAG
.getMachineFunction(), &Mask
);
7911 Size
= DAG
.getNode(ISD::SRL
, dl
, MVT::i64
, Size
,
7912 DAG
.getConstant(4, dl
, MVT::i64
));
7913 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::X15
, Size
, SDValue());
7915 DAG
.getNode(AArch64ISD::CALL
, dl
, DAG
.getVTList(MVT::Other
, MVT::Glue
),
7916 Chain
, Callee
, DAG
.getRegister(AArch64::X15
, MVT::i64
),
7917 DAG
.getRegisterMask(Mask
), Chain
.getValue(1));
7918 // To match the actual intent better, we should read the output from X15 here
7919 // again (instead of potentially spilling it to the stack), but rereading Size
7920 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7923 Size
= DAG
.getNode(ISD::SHL
, dl
, MVT::i64
, Size
,
7924 DAG
.getConstant(4, dl
, MVT::i64
));
7929 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op
,
7930 SelectionDAG
&DAG
) const {
7931 assert(Subtarget
->isTargetWindows() &&
7932 "Only Windows alloca probing supported");
7935 SDNode
*Node
= Op
.getNode();
7936 SDValue Chain
= Op
.getOperand(0);
7937 SDValue Size
= Op
.getOperand(1);
7938 unsigned Align
= cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue();
7939 EVT VT
= Node
->getValueType(0);
7941 if (DAG
.getMachineFunction().getFunction().hasFnAttribute(
7942 "no-stack-arg-probe")) {
7943 SDValue SP
= DAG
.getCopyFromReg(Chain
, dl
, AArch64::SP
, MVT::i64
);
7944 Chain
= SP
.getValue(1);
7945 SP
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, SP
, Size
);
7947 SP
= DAG
.getNode(ISD::AND
, dl
, VT
, SP
.getValue(0),
7948 DAG
.getConstant(-(uint64_t)Align
, dl
, VT
));
7949 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::SP
, SP
);
7950 SDValue Ops
[2] = {SP
, Chain
};
7951 return DAG
.getMergeValues(Ops
, dl
);
7954 Chain
= DAG
.getCALLSEQ_START(Chain
, 0, 0, dl
);
7956 Chain
= LowerWindowsDYNAMIC_STACKALLOC(Op
, Chain
, Size
, DAG
);
7958 SDValue SP
= DAG
.getCopyFromReg(Chain
, dl
, AArch64::SP
, MVT::i64
);
7959 Chain
= SP
.getValue(1);
7960 SP
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, SP
, Size
);
7962 SP
= DAG
.getNode(ISD::AND
, dl
, VT
, SP
.getValue(0),
7963 DAG
.getConstant(-(uint64_t)Align
, dl
, VT
));
7964 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::SP
, SP
);
7966 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(0, dl
, true),
7967 DAG
.getIntPtrConstant(0, dl
, true), SDValue(), dl
);
7969 SDValue Ops
[2] = {SP
, Chain
};
7970 return DAG
.getMergeValues(Ops
, dl
);
7973 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7974 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7975 /// specified in the intrinsic calls.
7976 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo
&Info
,
7978 MachineFunction
&MF
,
7979 unsigned Intrinsic
) const {
7980 auto &DL
= I
.getModule()->getDataLayout();
7981 switch (Intrinsic
) {
7982 case Intrinsic::aarch64_neon_ld2
:
7983 case Intrinsic::aarch64_neon_ld3
:
7984 case Intrinsic::aarch64_neon_ld4
:
7985 case Intrinsic::aarch64_neon_ld1x2
:
7986 case Intrinsic::aarch64_neon_ld1x3
:
7987 case Intrinsic::aarch64_neon_ld1x4
:
7988 case Intrinsic::aarch64_neon_ld2lane
:
7989 case Intrinsic::aarch64_neon_ld3lane
:
7990 case Intrinsic::aarch64_neon_ld4lane
:
7991 case Intrinsic::aarch64_neon_ld2r
:
7992 case Intrinsic::aarch64_neon_ld3r
:
7993 case Intrinsic::aarch64_neon_ld4r
: {
7994 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
7995 // Conservatively set memVT to the entire set of vectors loaded.
7996 uint64_t NumElts
= DL
.getTypeSizeInBits(I
.getType()) / 64;
7997 Info
.memVT
= EVT::getVectorVT(I
.getType()->getContext(), MVT::i64
, NumElts
);
7998 Info
.ptrVal
= I
.getArgOperand(I
.getNumArgOperands() - 1);
8001 // volatile loads with NEON intrinsics not supported
8002 Info
.flags
= MachineMemOperand::MOLoad
;
8005 case Intrinsic::aarch64_neon_st2
:
8006 case Intrinsic::aarch64_neon_st3
:
8007 case Intrinsic::aarch64_neon_st4
:
8008 case Intrinsic::aarch64_neon_st1x2
:
8009 case Intrinsic::aarch64_neon_st1x3
:
8010 case Intrinsic::aarch64_neon_st1x4
:
8011 case Intrinsic::aarch64_neon_st2lane
:
8012 case Intrinsic::aarch64_neon_st3lane
:
8013 case Intrinsic::aarch64_neon_st4lane
: {
8014 Info
.opc
= ISD::INTRINSIC_VOID
;
8015 // Conservatively set memVT to the entire set of vectors stored.
8016 unsigned NumElts
= 0;
8017 for (unsigned ArgI
= 0, ArgE
= I
.getNumArgOperands(); ArgI
< ArgE
; ++ArgI
) {
8018 Type
*ArgTy
= I
.getArgOperand(ArgI
)->getType();
8019 if (!ArgTy
->isVectorTy())
8021 NumElts
+= DL
.getTypeSizeInBits(ArgTy
) / 64;
8023 Info
.memVT
= EVT::getVectorVT(I
.getType()->getContext(), MVT::i64
, NumElts
);
8024 Info
.ptrVal
= I
.getArgOperand(I
.getNumArgOperands() - 1);
8027 // volatile stores with NEON intrinsics not supported
8028 Info
.flags
= MachineMemOperand::MOStore
;
8031 case Intrinsic::aarch64_ldaxr
:
8032 case Intrinsic::aarch64_ldxr
: {
8033 PointerType
*PtrTy
= cast
<PointerType
>(I
.getArgOperand(0)->getType());
8034 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8035 Info
.memVT
= MVT::getVT(PtrTy
->getElementType());
8036 Info
.ptrVal
= I
.getArgOperand(0);
8038 Info
.align
= DL
.getABITypeAlignment(PtrTy
->getElementType());
8039 Info
.flags
= MachineMemOperand::MOLoad
| MachineMemOperand::MOVolatile
;
8042 case Intrinsic::aarch64_stlxr
:
8043 case Intrinsic::aarch64_stxr
: {
8044 PointerType
*PtrTy
= cast
<PointerType
>(I
.getArgOperand(1)->getType());
8045 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8046 Info
.memVT
= MVT::getVT(PtrTy
->getElementType());
8047 Info
.ptrVal
= I
.getArgOperand(1);
8049 Info
.align
= DL
.getABITypeAlignment(PtrTy
->getElementType());
8050 Info
.flags
= MachineMemOperand::MOStore
| MachineMemOperand::MOVolatile
;
8053 case Intrinsic::aarch64_ldaxp
:
8054 case Intrinsic::aarch64_ldxp
:
8055 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8056 Info
.memVT
= MVT::i128
;
8057 Info
.ptrVal
= I
.getArgOperand(0);
8060 Info
.flags
= MachineMemOperand::MOLoad
| MachineMemOperand::MOVolatile
;
8062 case Intrinsic::aarch64_stlxp
:
8063 case Intrinsic::aarch64_stxp
:
8064 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8065 Info
.memVT
= MVT::i128
;
8066 Info
.ptrVal
= I
.getArgOperand(2);
8069 Info
.flags
= MachineMemOperand::MOStore
| MachineMemOperand::MOVolatile
;
8078 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode
*Load
,
8079 ISD::LoadExtType ExtTy
,
8081 // TODO: This may be worth removing. Check regression tests for diffs.
8082 if (!TargetLoweringBase::shouldReduceLoadWidth(Load
, ExtTy
, NewVT
))
8085 // If we're reducing the load width in order to avoid having to use an extra
8086 // instruction to do extension then it's probably a good idea.
8087 if (ExtTy
!= ISD::NON_EXTLOAD
)
8089 // Don't reduce load width if it would prevent us from combining a shift into
8091 MemSDNode
*Mem
= dyn_cast
<MemSDNode
>(Load
);
8093 const SDValue
&Base
= Mem
->getBasePtr();
8094 if (Base
.getOpcode() == ISD::ADD
&&
8095 Base
.getOperand(1).getOpcode() == ISD::SHL
&&
8096 Base
.getOperand(1).hasOneUse() &&
8097 Base
.getOperand(1).getOperand(1).getOpcode() == ISD::Constant
) {
8098 // The shift can be combined if it matches the size of the value being
8099 // loaded (and so reducing the width would make it not match).
8100 uint64_t ShiftAmount
= Base
.getOperand(1).getConstantOperandVal(1);
8101 uint64_t LoadBytes
= Mem
->getMemoryVT().getSizeInBits()/8;
8102 if (ShiftAmount
== Log2_32(LoadBytes
))
8105 // We have no reason to disallow reducing the load width, so allow it.
8109 // Truncations from 64-bit GPR to 32-bit GPR is free.
8110 bool AArch64TargetLowering::isTruncateFree(Type
*Ty1
, Type
*Ty2
) const {
8111 if (!Ty1
->isIntegerTy() || !Ty2
->isIntegerTy())
8113 unsigned NumBits1
= Ty1
->getPrimitiveSizeInBits();
8114 unsigned NumBits2
= Ty2
->getPrimitiveSizeInBits();
8115 return NumBits1
> NumBits2
;
8117 bool AArch64TargetLowering::isTruncateFree(EVT VT1
, EVT VT2
) const {
8118 if (VT1
.isVector() || VT2
.isVector() || !VT1
.isInteger() || !VT2
.isInteger())
8120 unsigned NumBits1
= VT1
.getSizeInBits();
8121 unsigned NumBits2
= VT2
.getSizeInBits();
8122 return NumBits1
> NumBits2
;
8125 /// Check if it is profitable to hoist instruction in then/else to if.
8126 /// Not profitable if I and it's user can form a FMA instruction
8127 /// because we prefer FMSUB/FMADD.
8128 bool AArch64TargetLowering::isProfitableToHoist(Instruction
*I
) const {
8129 if (I
->getOpcode() != Instruction::FMul
)
8132 if (!I
->hasOneUse())
8135 Instruction
*User
= I
->user_back();
8138 !(User
->getOpcode() == Instruction::FSub
||
8139 User
->getOpcode() == Instruction::FAdd
))
8142 const TargetOptions
&Options
= getTargetMachine().Options
;
8143 const DataLayout
&DL
= I
->getModule()->getDataLayout();
8144 EVT VT
= getValueType(DL
, User
->getOperand(0)->getType());
8146 return !(isFMAFasterThanFMulAndFAdd(VT
) &&
8147 isOperationLegalOrCustom(ISD::FMA
, VT
) &&
8148 (Options
.AllowFPOpFusion
== FPOpFusion::Fast
||
8149 Options
.UnsafeFPMath
));
8152 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8154 bool AArch64TargetLowering::isZExtFree(Type
*Ty1
, Type
*Ty2
) const {
8155 if (!Ty1
->isIntegerTy() || !Ty2
->isIntegerTy())
8157 unsigned NumBits1
= Ty1
->getPrimitiveSizeInBits();
8158 unsigned NumBits2
= Ty2
->getPrimitiveSizeInBits();
8159 return NumBits1
== 32 && NumBits2
== 64;
8161 bool AArch64TargetLowering::isZExtFree(EVT VT1
, EVT VT2
) const {
8162 if (VT1
.isVector() || VT2
.isVector() || !VT1
.isInteger() || !VT2
.isInteger())
8164 unsigned NumBits1
= VT1
.getSizeInBits();
8165 unsigned NumBits2
= VT2
.getSizeInBits();
8166 return NumBits1
== 32 && NumBits2
== 64;
8169 bool AArch64TargetLowering::isZExtFree(SDValue Val
, EVT VT2
) const {
8170 EVT VT1
= Val
.getValueType();
8171 if (isZExtFree(VT1
, VT2
)) {
8175 if (Val
.getOpcode() != ISD::LOAD
)
8178 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8179 return (VT1
.isSimple() && !VT1
.isVector() && VT1
.isInteger() &&
8180 VT2
.isSimple() && !VT2
.isVector() && VT2
.isInteger() &&
8181 VT1
.getSizeInBits() <= 32);
8184 bool AArch64TargetLowering::isExtFreeImpl(const Instruction
*Ext
) const {
8185 if (isa
<FPExtInst
>(Ext
))
8188 // Vector types are not free.
8189 if (Ext
->getType()->isVectorTy())
8192 for (const Use
&U
: Ext
->uses()) {
8193 // The extension is free if we can fold it with a left shift in an
8194 // addressing mode or an arithmetic operation: add, sub, and cmp.
8196 // Is there a shift?
8197 const Instruction
*Instr
= cast
<Instruction
>(U
.getUser());
8199 // Is this a constant shift?
8200 switch (Instr
->getOpcode()) {
8201 case Instruction::Shl
:
8202 if (!isa
<ConstantInt
>(Instr
->getOperand(1)))
8205 case Instruction::GetElementPtr
: {
8206 gep_type_iterator GTI
= gep_type_begin(Instr
);
8207 auto &DL
= Ext
->getModule()->getDataLayout();
8208 std::advance(GTI
, U
.getOperandNo()-1);
8209 Type
*IdxTy
= GTI
.getIndexedType();
8210 // This extension will end up with a shift because of the scaling factor.
8211 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8212 // Get the shift amount based on the scaling factor:
8213 // log2(sizeof(IdxTy)) - log2(8).
8215 countTrailingZeros(DL
.getTypeStoreSizeInBits(IdxTy
)) - 3;
8216 // Is the constant foldable in the shift of the addressing mode?
8217 // I.e., shift amount is between 1 and 4 inclusive.
8218 if (ShiftAmt
== 0 || ShiftAmt
> 4)
8222 case Instruction::Trunc
:
8223 // Check if this is a noop.
8224 // trunc(sext ty1 to ty2) to ty1.
8225 if (Instr
->getType() == Ext
->getOperand(0)->getType())
8232 // At this point we can use the bfm family, so this extension is free
8238 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8239 /// or upper half of the vector elements.
8240 static bool areExtractShuffleVectors(Value
*Op1
, Value
*Op2
) {
8241 auto areTypesHalfed
= [](Value
*FullV
, Value
*HalfV
) {
8242 auto *FullVT
= cast
<VectorType
>(FullV
->getType());
8243 auto *HalfVT
= cast
<VectorType
>(HalfV
->getType());
8244 return FullVT
->getBitWidth() == 2 * HalfVT
->getBitWidth();
8247 auto extractHalf
= [](Value
*FullV
, Value
*HalfV
) {
8248 auto *FullVT
= cast
<VectorType
>(FullV
->getType());
8249 auto *HalfVT
= cast
<VectorType
>(HalfV
->getType());
8250 return FullVT
->getNumElements() == 2 * HalfVT
->getNumElements();
8254 Value
*S1Op1
, *S2Op1
;
8255 if (!match(Op1
, m_ShuffleVector(m_Value(S1Op1
), m_Undef(), m_Constant(M1
))) ||
8256 !match(Op2
, m_ShuffleVector(m_Value(S2Op1
), m_Undef(), m_Constant(M2
))))
8259 // Check that the operands are half as wide as the result and we extract
8260 // half of the elements of the input vectors.
8261 if (!areTypesHalfed(S1Op1
, Op1
) || !areTypesHalfed(S2Op1
, Op2
) ||
8262 !extractHalf(S1Op1
, Op1
) || !extractHalf(S2Op1
, Op2
))
8265 // Check the mask extracts either the lower or upper half of vector
8269 int NumElements
= cast
<VectorType
>(Op1
->getType())->getNumElements() * 2;
8270 if (!ShuffleVectorInst::isExtractSubvectorMask(M1
, NumElements
, M1Start
) ||
8271 !ShuffleVectorInst::isExtractSubvectorMask(M2
, NumElements
, M2Start
) ||
8272 M1Start
!= M2Start
|| (M1Start
!= 0 && M2Start
!= (NumElements
/ 2)))
8278 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8279 /// of the vector elements.
8280 static bool areExtractExts(Value
*Ext1
, Value
*Ext2
) {
8281 auto areExtDoubled
= [](Instruction
*Ext
) {
8282 return Ext
->getType()->getScalarSizeInBits() ==
8283 2 * Ext
->getOperand(0)->getType()->getScalarSizeInBits();
8286 if (!match(Ext1
, m_ZExtOrSExt(m_Value())) ||
8287 !match(Ext2
, m_ZExtOrSExt(m_Value())) ||
8288 !areExtDoubled(cast
<Instruction
>(Ext1
)) ||
8289 !areExtDoubled(cast
<Instruction
>(Ext2
)))
8295 /// Check if sinking \p I's operands to I's basic block is profitable, because
8296 /// the operands can be folded into a target instruction, e.g.
8297 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8298 bool AArch64TargetLowering::shouldSinkOperands(
8299 Instruction
*I
, SmallVectorImpl
<Use
*> &Ops
) const {
8300 if (!I
->getType()->isVectorTy())
8303 if (IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(I
)) {
8304 switch (II
->getIntrinsicID()) {
8305 case Intrinsic::aarch64_neon_umull
:
8306 if (!areExtractShuffleVectors(II
->getOperand(0), II
->getOperand(1)))
8308 Ops
.push_back(&II
->getOperandUse(0));
8309 Ops
.push_back(&II
->getOperandUse(1));
8316 switch (I
->getOpcode()) {
8317 case Instruction::Sub
:
8318 case Instruction::Add
: {
8319 if (!areExtractExts(I
->getOperand(0), I
->getOperand(1)))
8322 // If the exts' operands extract either the lower or upper elements, we
8323 // can sink them too.
8324 auto Ext1
= cast
<Instruction
>(I
->getOperand(0));
8325 auto Ext2
= cast
<Instruction
>(I
->getOperand(1));
8326 if (areExtractShuffleVectors(Ext1
, Ext2
)) {
8327 Ops
.push_back(&Ext1
->getOperandUse(0));
8328 Ops
.push_back(&Ext2
->getOperandUse(0));
8331 Ops
.push_back(&I
->getOperandUse(0));
8332 Ops
.push_back(&I
->getOperandUse(1));
8342 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType
,
8343 unsigned &RequiredAligment
) const {
8344 if (!LoadedType
.isSimple() ||
8345 (!LoadedType
.isInteger() && !LoadedType
.isFloatingPoint()))
8347 // Cyclone supports unaligned accesses.
8348 RequiredAligment
= 0;
8349 unsigned NumBits
= LoadedType
.getSizeInBits();
8350 return NumBits
== 32 || NumBits
== 64;
8353 /// A helper function for determining the number of interleaved accesses we
8354 /// will generate when lowering accesses of the given type.
8356 AArch64TargetLowering::getNumInterleavedAccesses(VectorType
*VecTy
,
8357 const DataLayout
&DL
) const {
8358 return (DL
.getTypeSizeInBits(VecTy
) + 127) / 128;
8361 MachineMemOperand::Flags
8362 AArch64TargetLowering::getMMOFlags(const Instruction
&I
) const {
8363 if (Subtarget
->getProcFamily() == AArch64Subtarget::Falkor
&&
8364 I
.getMetadata(FALKOR_STRIDED_ACCESS_MD
) != nullptr)
8365 return MOStridedAccess
;
8366 return MachineMemOperand::MONone
;
8369 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8370 VectorType
*VecTy
, const DataLayout
&DL
) const {
8372 unsigned VecSize
= DL
.getTypeSizeInBits(VecTy
);
8373 unsigned ElSize
= DL
.getTypeSizeInBits(VecTy
->getElementType());
8375 // Ensure the number of vector elements is greater than 1.
8376 if (VecTy
->getNumElements() < 2)
8379 // Ensure the element type is legal.
8380 if (ElSize
!= 8 && ElSize
!= 16 && ElSize
!= 32 && ElSize
!= 64)
8383 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8384 // 128 will be split into multiple interleaved accesses.
8385 return VecSize
== 64 || VecSize
% 128 == 0;
8388 /// Lower an interleaved load into a ldN intrinsic.
8390 /// E.g. Lower an interleaved load (Factor = 2):
8391 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8392 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8393 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8396 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8397 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8398 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8399 bool AArch64TargetLowering::lowerInterleavedLoad(
8400 LoadInst
*LI
, ArrayRef
<ShuffleVectorInst
*> Shuffles
,
8401 ArrayRef
<unsigned> Indices
, unsigned Factor
) const {
8402 assert(Factor
>= 2 && Factor
<= getMaxSupportedInterleaveFactor() &&
8403 "Invalid interleave factor");
8404 assert(!Shuffles
.empty() && "Empty shufflevector input");
8405 assert(Shuffles
.size() == Indices
.size() &&
8406 "Unmatched number of shufflevectors and indices");
8408 const DataLayout
&DL
= LI
->getModule()->getDataLayout();
8410 VectorType
*VecTy
= Shuffles
[0]->getType();
8412 // Skip if we do not have NEON and skip illegal vector types. We can
8413 // "legalize" wide vector types into multiple interleaved accesses as long as
8414 // the vector types are divisible by 128.
8415 if (!Subtarget
->hasNEON() || !isLegalInterleavedAccessType(VecTy
, DL
))
8418 unsigned NumLoads
= getNumInterleavedAccesses(VecTy
, DL
);
8420 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8421 // load integer vectors first and then convert to pointer vectors.
8422 Type
*EltTy
= VecTy
->getVectorElementType();
8423 if (EltTy
->isPointerTy())
8425 VectorType::get(DL
.getIntPtrType(EltTy
), VecTy
->getVectorNumElements());
8427 IRBuilder
<> Builder(LI
);
8429 // The base address of the load.
8430 Value
*BaseAddr
= LI
->getPointerOperand();
8433 // If we're going to generate more than one load, reset the sub-vector type
8434 // to something legal.
8435 VecTy
= VectorType::get(VecTy
->getVectorElementType(),
8436 VecTy
->getVectorNumElements() / NumLoads
);
8438 // We will compute the pointer operand of each load from the original base
8439 // address using GEPs. Cast the base address to a pointer to the scalar
8441 BaseAddr
= Builder
.CreateBitCast(
8442 BaseAddr
, VecTy
->getVectorElementType()->getPointerTo(
8443 LI
->getPointerAddressSpace()));
8446 Type
*PtrTy
= VecTy
->getPointerTo(LI
->getPointerAddressSpace());
8447 Type
*Tys
[2] = {VecTy
, PtrTy
};
8448 static const Intrinsic::ID LoadInts
[3] = {Intrinsic::aarch64_neon_ld2
,
8449 Intrinsic::aarch64_neon_ld3
,
8450 Intrinsic::aarch64_neon_ld4
};
8452 Intrinsic::getDeclaration(LI
->getModule(), LoadInts
[Factor
- 2], Tys
);
8454 // Holds sub-vectors extracted from the load intrinsic return values. The
8455 // sub-vectors are associated with the shufflevector instructions they will
8457 DenseMap
<ShuffleVectorInst
*, SmallVector
<Value
*, 4>> SubVecs
;
8459 for (unsigned LoadCount
= 0; LoadCount
< NumLoads
; ++LoadCount
) {
8461 // If we're generating more than one load, compute the base address of
8462 // subsequent loads as an offset from the previous.
8465 Builder
.CreateConstGEP1_32(VecTy
->getVectorElementType(), BaseAddr
,
8466 VecTy
->getVectorNumElements() * Factor
);
8468 CallInst
*LdN
= Builder
.CreateCall(
8469 LdNFunc
, Builder
.CreateBitCast(BaseAddr
, PtrTy
), "ldN");
8471 // Extract and store the sub-vectors returned by the load intrinsic.
8472 for (unsigned i
= 0; i
< Shuffles
.size(); i
++) {
8473 ShuffleVectorInst
*SVI
= Shuffles
[i
];
8474 unsigned Index
= Indices
[i
];
8476 Value
*SubVec
= Builder
.CreateExtractValue(LdN
, Index
);
8478 // Convert the integer vector to pointer vector if the element is pointer.
8479 if (EltTy
->isPointerTy())
8480 SubVec
= Builder
.CreateIntToPtr(
8481 SubVec
, VectorType::get(SVI
->getType()->getVectorElementType(),
8482 VecTy
->getVectorNumElements()));
8483 SubVecs
[SVI
].push_back(SubVec
);
8487 // Replace uses of the shufflevector instructions with the sub-vectors
8488 // returned by the load intrinsic. If a shufflevector instruction is
8489 // associated with more than one sub-vector, those sub-vectors will be
8490 // concatenated into a single wide vector.
8491 for (ShuffleVectorInst
*SVI
: Shuffles
) {
8492 auto &SubVec
= SubVecs
[SVI
];
8494 SubVec
.size() > 1 ? concatenateVectors(Builder
, SubVec
) : SubVec
[0];
8495 SVI
->replaceAllUsesWith(WideVec
);
8501 /// Lower an interleaved store into a stN intrinsic.
8503 /// E.g. Lower an interleaved store (Factor = 3):
8504 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8505 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8506 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8509 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8510 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8511 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8512 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8514 /// Note that the new shufflevectors will be removed and we'll only generate one
8515 /// st3 instruction in CodeGen.
8517 /// Example for a more general valid mask (Factor 3). Lower:
8518 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8519 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8520 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8523 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8524 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8525 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8526 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8527 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst
*SI
,
8528 ShuffleVectorInst
*SVI
,
8529 unsigned Factor
) const {
8530 assert(Factor
>= 2 && Factor
<= getMaxSupportedInterleaveFactor() &&
8531 "Invalid interleave factor");
8533 VectorType
*VecTy
= SVI
->getType();
8534 assert(VecTy
->getVectorNumElements() % Factor
== 0 &&
8535 "Invalid interleaved store");
8537 unsigned LaneLen
= VecTy
->getVectorNumElements() / Factor
;
8538 Type
*EltTy
= VecTy
->getVectorElementType();
8539 VectorType
*SubVecTy
= VectorType::get(EltTy
, LaneLen
);
8541 const DataLayout
&DL
= SI
->getModule()->getDataLayout();
8543 // Skip if we do not have NEON and skip illegal vector types. We can
8544 // "legalize" wide vector types into multiple interleaved accesses as long as
8545 // the vector types are divisible by 128.
8546 if (!Subtarget
->hasNEON() || !isLegalInterleavedAccessType(SubVecTy
, DL
))
8549 unsigned NumStores
= getNumInterleavedAccesses(SubVecTy
, DL
);
8551 Value
*Op0
= SVI
->getOperand(0);
8552 Value
*Op1
= SVI
->getOperand(1);
8553 IRBuilder
<> Builder(SI
);
8555 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8556 // vectors to integer vectors.
8557 if (EltTy
->isPointerTy()) {
8558 Type
*IntTy
= DL
.getIntPtrType(EltTy
);
8559 unsigned NumOpElts
= Op0
->getType()->getVectorNumElements();
8561 // Convert to the corresponding integer vector.
8562 Type
*IntVecTy
= VectorType::get(IntTy
, NumOpElts
);
8563 Op0
= Builder
.CreatePtrToInt(Op0
, IntVecTy
);
8564 Op1
= Builder
.CreatePtrToInt(Op1
, IntVecTy
);
8566 SubVecTy
= VectorType::get(IntTy
, LaneLen
);
8569 // The base address of the store.
8570 Value
*BaseAddr
= SI
->getPointerOperand();
8572 if (NumStores
> 1) {
8573 // If we're going to generate more than one store, reset the lane length
8574 // and sub-vector type to something legal.
8575 LaneLen
/= NumStores
;
8576 SubVecTy
= VectorType::get(SubVecTy
->getVectorElementType(), LaneLen
);
8578 // We will compute the pointer operand of each store from the original base
8579 // address using GEPs. Cast the base address to a pointer to the scalar
8581 BaseAddr
= Builder
.CreateBitCast(
8582 BaseAddr
, SubVecTy
->getVectorElementType()->getPointerTo(
8583 SI
->getPointerAddressSpace()));
8586 auto Mask
= SVI
->getShuffleMask();
8588 Type
*PtrTy
= SubVecTy
->getPointerTo(SI
->getPointerAddressSpace());
8589 Type
*Tys
[2] = {SubVecTy
, PtrTy
};
8590 static const Intrinsic::ID StoreInts
[3] = {Intrinsic::aarch64_neon_st2
,
8591 Intrinsic::aarch64_neon_st3
,
8592 Intrinsic::aarch64_neon_st4
};
8594 Intrinsic::getDeclaration(SI
->getModule(), StoreInts
[Factor
- 2], Tys
);
8596 for (unsigned StoreCount
= 0; StoreCount
< NumStores
; ++StoreCount
) {
8598 SmallVector
<Value
*, 5> Ops
;
8600 // Split the shufflevector operands into sub vectors for the new stN call.
8601 for (unsigned i
= 0; i
< Factor
; i
++) {
8602 unsigned IdxI
= StoreCount
* LaneLen
* Factor
+ i
;
8603 if (Mask
[IdxI
] >= 0) {
8604 Ops
.push_back(Builder
.CreateShuffleVector(
8605 Op0
, Op1
, createSequentialMask(Builder
, Mask
[IdxI
], LaneLen
, 0)));
8607 unsigned StartMask
= 0;
8608 for (unsigned j
= 1; j
< LaneLen
; j
++) {
8609 unsigned IdxJ
= StoreCount
* LaneLen
* Factor
+ j
;
8610 if (Mask
[IdxJ
* Factor
+ IdxI
] >= 0) {
8611 StartMask
= Mask
[IdxJ
* Factor
+ IdxI
] - IdxJ
;
8615 // Note: Filling undef gaps with random elements is ok, since
8616 // those elements were being written anyway (with undefs).
8617 // In the case of all undefs we're defaulting to using elems from 0
8618 // Note: StartMask cannot be negative, it's checked in
8619 // isReInterleaveMask
8620 Ops
.push_back(Builder
.CreateShuffleVector(
8621 Op0
, Op1
, createSequentialMask(Builder
, StartMask
, LaneLen
, 0)));
8625 // If we generating more than one store, we compute the base address of
8626 // subsequent stores as an offset from the previous.
8628 BaseAddr
= Builder
.CreateConstGEP1_32(SubVecTy
->getVectorElementType(),
8629 BaseAddr
, LaneLen
* Factor
);
8631 Ops
.push_back(Builder
.CreateBitCast(BaseAddr
, PtrTy
));
8632 Builder
.CreateCall(StNFunc
, Ops
);
8637 static bool memOpAlign(unsigned DstAlign
, unsigned SrcAlign
,
8638 unsigned AlignCheck
) {
8639 return ((SrcAlign
== 0 || SrcAlign
% AlignCheck
== 0) &&
8640 (DstAlign
== 0 || DstAlign
% AlignCheck
== 0));
8643 EVT
AArch64TargetLowering::getOptimalMemOpType(uint64_t Size
, unsigned DstAlign
,
8644 unsigned SrcAlign
, bool IsMemset
,
8647 MachineFunction
&MF
) const {
8648 const Function
&F
= MF
.getFunction();
8649 bool CanImplicitFloat
= !F
.hasFnAttribute(Attribute::NoImplicitFloat
);
8650 bool CanUseNEON
= Subtarget
->hasNEON() && CanImplicitFloat
;
8651 bool CanUseFP
= Subtarget
->hasFPARMv8() && CanImplicitFloat
;
8652 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8653 // taken one instruction to materialize the v2i64 zero and one store (with
8654 // restrictive addressing mode). Just do i64 stores.
8655 bool IsSmallMemset
= IsMemset
&& Size
< 32;
8656 auto AlignmentIsAcceptable
= [&](EVT VT
, unsigned AlignCheck
) {
8657 if (memOpAlign(SrcAlign
, DstAlign
, AlignCheck
))
8660 return allowsMisalignedMemoryAccesses(VT
, 0, 1, &Fast
) && Fast
;
8663 if (CanUseNEON
&& IsMemset
&& !IsSmallMemset
&&
8664 AlignmentIsAcceptable(MVT::v2i64
, 16))
8666 if (CanUseFP
&& !IsSmallMemset
&& AlignmentIsAcceptable(MVT::f128
, 16))
8668 if (Size
>= 8 && AlignmentIsAcceptable(MVT::i64
, 8))
8670 if (Size
>= 4 && AlignmentIsAcceptable(MVT::i32
, 4))
8675 // 12-bit optionally shifted immediates are legal for adds.
8676 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed
) const {
8677 if (Immed
== std::numeric_limits
<int64_t>::min()) {
8678 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8679 << ": avoid UB for INT64_MIN\n");
8682 // Same encoding for add/sub, just flip the sign.
8683 Immed
= std::abs(Immed
);
8684 bool IsLegal
= ((Immed
>> 12) == 0 ||
8685 ((Immed
& 0xfff) == 0 && Immed
>> 24 == 0));
8686 LLVM_DEBUG(dbgs() << "Is " << Immed
8687 << " legal add imm: " << (IsLegal
? "yes" : "no") << "\n");
8691 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8692 // immediates is the same as for an add or a sub.
8693 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed
) const {
8694 return isLegalAddImmediate(Immed
);
8697 /// isLegalAddressingMode - Return true if the addressing mode represented
8698 /// by AM is legal for this target, for a load/store of the specified type.
8699 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout
&DL
,
8700 const AddrMode
&AM
, Type
*Ty
,
8701 unsigned AS
, Instruction
*I
) const {
8702 // AArch64 has five basic addressing modes:
8704 // reg + 9-bit signed offset
8705 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8707 // reg + SIZE_IN_BYTES * reg
8709 // No global is ever allowed as a base.
8713 // No reg+reg+imm addressing.
8714 if (AM
.HasBaseReg
&& AM
.BaseOffs
&& AM
.Scale
)
8717 // check reg + imm case:
8718 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8719 uint64_t NumBytes
= 0;
8720 if (Ty
->isSized()) {
8721 uint64_t NumBits
= DL
.getTypeSizeInBits(Ty
);
8722 NumBytes
= NumBits
/ 8;
8723 if (!isPowerOf2_64(NumBits
))
8728 int64_t Offset
= AM
.BaseOffs
;
8730 // 9-bit signed offset
8731 if (isInt
<9>(Offset
))
8734 // 12-bit unsigned offset
8735 unsigned shift
= Log2_64(NumBytes
);
8736 if (NumBytes
&& Offset
> 0 && (Offset
/ NumBytes
) <= (1LL << 12) - 1 &&
8737 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8738 (Offset
>> shift
) << shift
== Offset
)
8743 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8745 return AM
.Scale
== 1 || (AM
.Scale
> 0 && (uint64_t)AM
.Scale
== NumBytes
);
8748 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8749 // Consider splitting large offset of struct or array.
8753 int AArch64TargetLowering::getScalingFactorCost(const DataLayout
&DL
,
8754 const AddrMode
&AM
, Type
*Ty
,
8755 unsigned AS
) const {
8756 // Scaling factors are not free at all.
8757 // Operands | Rt Latency
8758 // -------------------------------------------
8760 // -------------------------------------------
8761 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8762 // Rt, [Xn, Wm, <extend> #imm] |
8763 if (isLegalAddressingMode(DL
, AM
, Ty
, AS
))
8764 // Scale represents reg2 * scale, thus account for 1 if
8765 // it is not equal to 0 or 1.
8766 return AM
.Scale
!= 0 && AM
.Scale
!= 1;
8770 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT
) const {
8771 VT
= VT
.getScalarType();
8776 switch (VT
.getSimpleVT().SimpleTy
) {
8788 AArch64TargetLowering::getScratchRegisters(CallingConv::ID
) const {
8789 // LR is a callee-save register, but we must treat it as clobbered by any call
8790 // site. Hence we include LR in the scratch registers, which are in turn added
8791 // as implicit-defs for stackmaps and patchpoints.
8792 static const MCPhysReg ScratchRegs
[] = {
8793 AArch64::X16
, AArch64::X17
, AArch64::LR
, 0
8799 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode
*N
,
8800 CombineLevel Level
) const {
8801 N
= N
->getOperand(0).getNode();
8802 EVT VT
= N
->getValueType(0);
8803 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8804 // it with shift to let it be lowered to UBFX.
8805 if (N
->getOpcode() == ISD::AND
&& (VT
== MVT::i32
|| VT
== MVT::i64
) &&
8806 isa
<ConstantSDNode
>(N
->getOperand(1))) {
8807 uint64_t TruncMask
= N
->getConstantOperandVal(1);
8808 if (isMask_64(TruncMask
) &&
8809 N
->getOperand(0).getOpcode() == ISD::SRL
&&
8810 isa
<ConstantSDNode
>(N
->getOperand(0)->getOperand(1)))
8816 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt
&Imm
,
8818 assert(Ty
->isIntegerTy());
8820 unsigned BitSize
= Ty
->getPrimitiveSizeInBits();
8824 int64_t Val
= Imm
.getSExtValue();
8825 if (Val
== 0 || AArch64_AM::isLogicalImmediate(Val
, BitSize
))
8828 if ((int64_t)Val
< 0)
8831 Val
&= (1LL << 32) - 1;
8833 unsigned LZ
= countLeadingZeros((uint64_t)Val
);
8834 unsigned Shift
= (63 - LZ
) / 16;
8835 // MOVZ is free so return true for one or fewer MOVK.
8839 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT
, EVT SrcVT
,
8840 unsigned Index
) const {
8841 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR
, ResVT
))
8844 return (Index
== 0 || Index
== ResVT
.getVectorNumElements());
8847 /// Turn vector tests of the signbit in the form of:
8848 /// xor (sra X, elt_size(X)-1), -1
8851 static SDValue
foldVectorXorShiftIntoCmp(SDNode
*N
, SelectionDAG
&DAG
,
8852 const AArch64Subtarget
*Subtarget
) {
8853 EVT VT
= N
->getValueType(0);
8854 if (!Subtarget
->hasNEON() || !VT
.isVector())
8857 // There must be a shift right algebraic before the xor, and the xor must be a
8859 SDValue Shift
= N
->getOperand(0);
8860 SDValue Ones
= N
->getOperand(1);
8861 if (Shift
.getOpcode() != AArch64ISD::VASHR
|| !Shift
.hasOneUse() ||
8862 !ISD::isBuildVectorAllOnes(Ones
.getNode()))
8865 // The shift should be smearing the sign bit across each vector element.
8866 auto *ShiftAmt
= dyn_cast
<ConstantSDNode
>(Shift
.getOperand(1));
8867 EVT ShiftEltTy
= Shift
.getValueType().getVectorElementType();
8868 if (!ShiftAmt
|| ShiftAmt
->getZExtValue() != ShiftEltTy
.getSizeInBits() - 1)
8871 return DAG
.getNode(AArch64ISD::CMGEz
, SDLoc(N
), VT
, Shift
.getOperand(0));
8874 // Generate SUBS and CSEL for integer abs.
8875 static SDValue
performIntegerAbsCombine(SDNode
*N
, SelectionDAG
&DAG
) {
8876 EVT VT
= N
->getValueType(0);
8878 SDValue N0
= N
->getOperand(0);
8879 SDValue N1
= N
->getOperand(1);
8882 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8883 // and change it to SUB and CSEL.
8884 if (VT
.isInteger() && N
->getOpcode() == ISD::XOR
&&
8885 N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(1) == N1
&&
8886 N1
.getOpcode() == ISD::SRA
&& N1
.getOperand(0) == N0
.getOperand(0))
8887 if (ConstantSDNode
*Y1C
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1)))
8888 if (Y1C
->getAPIntValue() == VT
.getSizeInBits() - 1) {
8889 SDValue Neg
= DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
),
8891 // Generate SUBS & CSEL.
8893 DAG
.getNode(AArch64ISD::SUBS
, DL
, DAG
.getVTList(VT
, MVT::i32
),
8894 N0
.getOperand(0), DAG
.getConstant(0, DL
, VT
));
8895 return DAG
.getNode(AArch64ISD::CSEL
, DL
, VT
, N0
.getOperand(0), Neg
,
8896 DAG
.getConstant(AArch64CC::PL
, DL
, MVT::i32
),
8897 SDValue(Cmp
.getNode(), 1));
8902 static SDValue
performXorCombine(SDNode
*N
, SelectionDAG
&DAG
,
8903 TargetLowering::DAGCombinerInfo
&DCI
,
8904 const AArch64Subtarget
*Subtarget
) {
8905 if (DCI
.isBeforeLegalizeOps())
8908 if (SDValue Cmp
= foldVectorXorShiftIntoCmp(N
, DAG
, Subtarget
))
8911 return performIntegerAbsCombine(N
, DAG
);
8915 AArch64TargetLowering::BuildSDIVPow2(SDNode
*N
, const APInt
&Divisor
,
8917 SmallVectorImpl
<SDNode
*> &Created
) const {
8918 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
8919 if (isIntDivCheap(N
->getValueType(0), Attr
))
8920 return SDValue(N
,0); // Lower SDIV as SDIV
8922 // fold (sdiv X, pow2)
8923 EVT VT
= N
->getValueType(0);
8924 if ((VT
!= MVT::i32
&& VT
!= MVT::i64
) ||
8925 !(Divisor
.isPowerOf2() || (-Divisor
).isPowerOf2()))
8929 SDValue N0
= N
->getOperand(0);
8930 unsigned Lg2
= Divisor
.countTrailingZeros();
8931 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
8932 SDValue Pow2MinusOne
= DAG
.getConstant((1ULL << Lg2
) - 1, DL
, VT
);
8934 // Add (N0 < 0) ? Pow2 - 1 : 0;
8936 SDValue Cmp
= getAArch64Cmp(N0
, Zero
, ISD::SETLT
, CCVal
, DAG
, DL
);
8937 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Pow2MinusOne
);
8938 SDValue CSel
= DAG
.getNode(AArch64ISD::CSEL
, DL
, VT
, Add
, N0
, CCVal
, Cmp
);
8940 Created
.push_back(Cmp
.getNode());
8941 Created
.push_back(Add
.getNode());
8942 Created
.push_back(CSel
.getNode());
8946 DAG
.getNode(ISD::SRA
, DL
, VT
, CSel
, DAG
.getConstant(Lg2
, DL
, MVT::i64
));
8948 // If we're dividing by a positive value, we're done. Otherwise, we must
8949 // negate the result.
8950 if (Divisor
.isNonNegative())
8953 Created
.push_back(SRA
.getNode());
8954 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), SRA
);
8957 static SDValue
performMulCombine(SDNode
*N
, SelectionDAG
&DAG
,
8958 TargetLowering::DAGCombinerInfo
&DCI
,
8959 const AArch64Subtarget
*Subtarget
) {
8960 if (DCI
.isBeforeLegalizeOps())
8963 // The below optimizations require a constant RHS.
8964 if (!isa
<ConstantSDNode
>(N
->getOperand(1)))
8967 ConstantSDNode
*C
= cast
<ConstantSDNode
>(N
->getOperand(1));
8968 const APInt
&ConstValue
= C
->getAPIntValue();
8970 // Multiplication of a power of two plus/minus one can be done more
8971 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8972 // future CPUs have a cheaper MADD instruction, this may need to be
8973 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8974 // 64-bit is 5 cycles, so this is always a win.
8975 // More aggressively, some multiplications N0 * C can be lowered to
8976 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8977 // e.g. 6=3*2=(2+1)*2.
8978 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8979 // which equals to (1+2)*16-(1+2).
8980 SDValue N0
= N
->getOperand(0);
8981 // TrailingZeroes is used to test if the mul can be lowered to
8983 unsigned TrailingZeroes
= ConstValue
.countTrailingZeros();
8984 if (TrailingZeroes
) {
8985 // Conservatively do not lower to shift+add+shift if the mul might be
8986 // folded into smul or umul.
8987 if (N0
->hasOneUse() && (isSignExtended(N0
.getNode(), DAG
) ||
8988 isZeroExtended(N0
.getNode(), DAG
)))
8990 // Conservatively do not lower to shift+add+shift if the mul might be
8991 // folded into madd or msub.
8992 if (N
->hasOneUse() && (N
->use_begin()->getOpcode() == ISD::ADD
||
8993 N
->use_begin()->getOpcode() == ISD::SUB
))
8996 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8997 // and shift+add+shift.
8998 APInt ShiftedConstValue
= ConstValue
.ashr(TrailingZeroes
);
9000 unsigned ShiftAmt
, AddSubOpc
;
9001 // Is the shifted value the LHS operand of the add/sub?
9002 bool ShiftValUseIsN0
= true;
9003 // Do we need to negate the result?
9004 bool NegateResult
= false;
9006 if (ConstValue
.isNonNegative()) {
9007 // (mul x, 2^N + 1) => (add (shl x, N), x)
9008 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9009 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9010 APInt SCVMinus1
= ShiftedConstValue
- 1;
9011 APInt CVPlus1
= ConstValue
+ 1;
9012 if (SCVMinus1
.isPowerOf2()) {
9013 ShiftAmt
= SCVMinus1
.logBase2();
9014 AddSubOpc
= ISD::ADD
;
9015 } else if (CVPlus1
.isPowerOf2()) {
9016 ShiftAmt
= CVPlus1
.logBase2();
9017 AddSubOpc
= ISD::SUB
;
9021 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9022 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9023 APInt CVNegPlus1
= -ConstValue
+ 1;
9024 APInt CVNegMinus1
= -ConstValue
- 1;
9025 if (CVNegPlus1
.isPowerOf2()) {
9026 ShiftAmt
= CVNegPlus1
.logBase2();
9027 AddSubOpc
= ISD::SUB
;
9028 ShiftValUseIsN0
= false;
9029 } else if (CVNegMinus1
.isPowerOf2()) {
9030 ShiftAmt
= CVNegMinus1
.logBase2();
9031 AddSubOpc
= ISD::ADD
;
9032 NegateResult
= true;
9038 EVT VT
= N
->getValueType(0);
9039 SDValue ShiftedVal
= DAG
.getNode(ISD::SHL
, DL
, VT
, N0
,
9040 DAG
.getConstant(ShiftAmt
, DL
, MVT::i64
));
9042 SDValue AddSubN0
= ShiftValUseIsN0
? ShiftedVal
: N0
;
9043 SDValue AddSubN1
= ShiftValUseIsN0
? N0
: ShiftedVal
;
9044 SDValue Res
= DAG
.getNode(AddSubOpc
, DL
, VT
, AddSubN0
, AddSubN1
);
9045 assert(!(NegateResult
&& TrailingZeroes
) &&
9046 "NegateResult and TrailingZeroes cannot both be true for now.");
9047 // Negate the result.
9049 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), Res
);
9050 // Shift the result.
9052 return DAG
.getNode(ISD::SHL
, DL
, VT
, Res
,
9053 DAG
.getConstant(TrailingZeroes
, DL
, MVT::i64
));
9057 static SDValue
performVectorCompareAndMaskUnaryOpCombine(SDNode
*N
,
9058 SelectionDAG
&DAG
) {
9059 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9060 // optimize away operation when it's from a constant.
9062 // The general transformation is:
9063 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9064 // AND(VECTOR_CMP(x,y), constant2)
9065 // constant2 = UNARYOP(constant)
9067 // Early exit if this isn't a vector operation, the operand of the
9068 // unary operation isn't a bitwise AND, or if the sizes of the operations
9070 EVT VT
= N
->getValueType(0);
9071 if (!VT
.isVector() || N
->getOperand(0)->getOpcode() != ISD::AND
||
9072 N
->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC
||
9073 VT
.getSizeInBits() != N
->getOperand(0)->getValueType(0).getSizeInBits())
9076 // Now check that the other operand of the AND is a constant. We could
9077 // make the transformation for non-constant splats as well, but it's unclear
9078 // that would be a benefit as it would not eliminate any operations, just
9079 // perform one more step in scalar code before moving to the vector unit.
9080 if (BuildVectorSDNode
*BV
=
9081 dyn_cast
<BuildVectorSDNode
>(N
->getOperand(0)->getOperand(1))) {
9082 // Bail out if the vector isn't a constant.
9083 if (!BV
->isConstant())
9086 // Everything checks out. Build up the new and improved node.
9088 EVT IntVT
= BV
->getValueType(0);
9089 // Create a new constant of the appropriate type for the transformed
9091 SDValue SourceConst
= DAG
.getNode(N
->getOpcode(), DL
, VT
, SDValue(BV
, 0));
9092 // The AND node needs bitcasts to/from an integer vector type around it.
9093 SDValue MaskConst
= DAG
.getNode(ISD::BITCAST
, DL
, IntVT
, SourceConst
);
9094 SDValue NewAnd
= DAG
.getNode(ISD::AND
, DL
, IntVT
,
9095 N
->getOperand(0)->getOperand(0), MaskConst
);
9096 SDValue Res
= DAG
.getNode(ISD::BITCAST
, DL
, VT
, NewAnd
);
9103 static SDValue
performIntToFpCombine(SDNode
*N
, SelectionDAG
&DAG
,
9104 const AArch64Subtarget
*Subtarget
) {
9105 // First try to optimize away the conversion when it's conditionally from
9106 // a constant. Vectors only.
9107 if (SDValue Res
= performVectorCompareAndMaskUnaryOpCombine(N
, DAG
))
9110 EVT VT
= N
->getValueType(0);
9111 if (VT
!= MVT::f32
&& VT
!= MVT::f64
)
9114 // Only optimize when the source and destination types have the same width.
9115 if (VT
.getSizeInBits() != N
->getOperand(0).getValueSizeInBits())
9118 // If the result of an integer load is only used by an integer-to-float
9119 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9120 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9121 SDValue N0
= N
->getOperand(0);
9122 if (Subtarget
->hasNEON() && ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
9123 // Do not change the width of a volatile load.
9124 !cast
<LoadSDNode
>(N0
)->isVolatile()) {
9125 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9126 SDValue Load
= DAG
.getLoad(VT
, SDLoc(N
), LN0
->getChain(), LN0
->getBasePtr(),
9127 LN0
->getPointerInfo(), LN0
->getAlignment(),
9128 LN0
->getMemOperand()->getFlags());
9130 // Make sure successors of the original load stay after it by updating them
9131 // to use the new Chain.
9132 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), Load
.getValue(1));
9135 (N
->getOpcode() == ISD::SINT_TO_FP
) ? AArch64ISD::SITOF
: AArch64ISD::UITOF
;
9136 return DAG
.getNode(Opcode
, SDLoc(N
), VT
, Load
);
9142 /// Fold a floating-point multiply by power of two into floating-point to
9143 /// fixed-point conversion.
9144 static SDValue
performFpToIntCombine(SDNode
*N
, SelectionDAG
&DAG
,
9145 TargetLowering::DAGCombinerInfo
&DCI
,
9146 const AArch64Subtarget
*Subtarget
) {
9147 if (!Subtarget
->hasNEON())
9150 SDValue Op
= N
->getOperand(0);
9151 if (!Op
.getValueType().isVector() || !Op
.getValueType().isSimple() ||
9152 Op
.getOpcode() != ISD::FMUL
)
9155 SDValue ConstVec
= Op
->getOperand(1);
9156 if (!isa
<BuildVectorSDNode
>(ConstVec
))
9159 MVT FloatTy
= Op
.getSimpleValueType().getVectorElementType();
9160 uint32_t FloatBits
= FloatTy
.getSizeInBits();
9161 if (FloatBits
!= 32 && FloatBits
!= 64)
9164 MVT IntTy
= N
->getSimpleValueType(0).getVectorElementType();
9165 uint32_t IntBits
= IntTy
.getSizeInBits();
9166 if (IntBits
!= 16 && IntBits
!= 32 && IntBits
!= 64)
9169 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9170 if (IntBits
> FloatBits
)
9173 BitVector UndefElements
;
9174 BuildVectorSDNode
*BV
= cast
<BuildVectorSDNode
>(ConstVec
);
9175 int32_t Bits
= IntBits
== 64 ? 64 : 32;
9176 int32_t C
= BV
->getConstantFPSplatPow2ToLog2Int(&UndefElements
, Bits
+ 1);
9177 if (C
== -1 || C
== 0 || C
> Bits
)
9181 unsigned NumLanes
= Op
.getValueType().getVectorNumElements();
9186 ResTy
= FloatBits
== 32 ? MVT::v2i32
: MVT::v2i64
;
9189 ResTy
= FloatBits
== 32 ? MVT::v4i32
: MVT::v4i64
;
9193 if (ResTy
== MVT::v4i64
&& DCI
.isBeforeLegalizeOps())
9196 assert((ResTy
!= MVT::v4i64
|| DCI
.isBeforeLegalizeOps()) &&
9197 "Illegal vector type after legalization");
9200 bool IsSigned
= N
->getOpcode() == ISD::FP_TO_SINT
;
9201 unsigned IntrinsicOpcode
= IsSigned
? Intrinsic::aarch64_neon_vcvtfp2fxs
9202 : Intrinsic::aarch64_neon_vcvtfp2fxu
;
9204 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, ResTy
,
9205 DAG
.getConstant(IntrinsicOpcode
, DL
, MVT::i32
),
9206 Op
->getOperand(0), DAG
.getConstant(C
, DL
, MVT::i32
));
9207 // We can handle smaller integers by generating an extra trunc.
9208 if (IntBits
< FloatBits
)
9209 FixConv
= DAG
.getNode(ISD::TRUNCATE
, DL
, N
->getValueType(0), FixConv
);
9214 /// Fold a floating-point divide by power of two into fixed-point to
9215 /// floating-point conversion.
9216 static SDValue
performFDivCombine(SDNode
*N
, SelectionDAG
&DAG
,
9217 TargetLowering::DAGCombinerInfo
&DCI
,
9218 const AArch64Subtarget
*Subtarget
) {
9219 if (!Subtarget
->hasNEON())
9222 SDValue Op
= N
->getOperand(0);
9223 unsigned Opc
= Op
->getOpcode();
9224 if (!Op
.getValueType().isVector() || !Op
.getValueType().isSimple() ||
9225 !Op
.getOperand(0).getValueType().isSimple() ||
9226 (Opc
!= ISD::SINT_TO_FP
&& Opc
!= ISD::UINT_TO_FP
))
9229 SDValue ConstVec
= N
->getOperand(1);
9230 if (!isa
<BuildVectorSDNode
>(ConstVec
))
9233 MVT IntTy
= Op
.getOperand(0).getSimpleValueType().getVectorElementType();
9234 int32_t IntBits
= IntTy
.getSizeInBits();
9235 if (IntBits
!= 16 && IntBits
!= 32 && IntBits
!= 64)
9238 MVT FloatTy
= N
->getSimpleValueType(0).getVectorElementType();
9239 int32_t FloatBits
= FloatTy
.getSizeInBits();
9240 if (FloatBits
!= 32 && FloatBits
!= 64)
9243 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9244 if (IntBits
> FloatBits
)
9247 BitVector UndefElements
;
9248 BuildVectorSDNode
*BV
= cast
<BuildVectorSDNode
>(ConstVec
);
9249 int32_t C
= BV
->getConstantFPSplatPow2ToLog2Int(&UndefElements
, FloatBits
+ 1);
9250 if (C
== -1 || C
== 0 || C
> FloatBits
)
9254 unsigned NumLanes
= Op
.getValueType().getVectorNumElements();
9259 ResTy
= FloatBits
== 32 ? MVT::v2i32
: MVT::v2i64
;
9262 ResTy
= FloatBits
== 32 ? MVT::v4i32
: MVT::v4i64
;
9266 if (ResTy
== MVT::v4i64
&& DCI
.isBeforeLegalizeOps())
9270 SDValue ConvInput
= Op
.getOperand(0);
9271 bool IsSigned
= Opc
== ISD::SINT_TO_FP
;
9272 if (IntBits
< FloatBits
)
9273 ConvInput
= DAG
.getNode(IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
, DL
,
9276 unsigned IntrinsicOpcode
= IsSigned
? Intrinsic::aarch64_neon_vcvtfxs2fp
9277 : Intrinsic::aarch64_neon_vcvtfxu2fp
;
9278 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, Op
.getValueType(),
9279 DAG
.getConstant(IntrinsicOpcode
, DL
, MVT::i32
), ConvInput
,
9280 DAG
.getConstant(C
, DL
, MVT::i32
));
9283 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9284 /// searches for and classifies those shifts.
9285 static bool findEXTRHalf(SDValue N
, SDValue
&Src
, uint32_t &ShiftAmount
,
9287 if (N
.getOpcode() == ISD::SHL
)
9289 else if (N
.getOpcode() == ISD::SRL
)
9294 if (!isa
<ConstantSDNode
>(N
.getOperand(1)))
9297 ShiftAmount
= N
->getConstantOperandVal(1);
9298 Src
= N
->getOperand(0);
9302 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9303 /// registers viewed as a high/low pair. This function looks for the pattern:
9304 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9305 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9306 /// aren't independent.
9307 static SDValue
tryCombineToEXTR(SDNode
*N
,
9308 TargetLowering::DAGCombinerInfo
&DCI
) {
9309 SelectionDAG
&DAG
= DCI
.DAG
;
9311 EVT VT
= N
->getValueType(0);
9313 assert(N
->getOpcode() == ISD::OR
&& "Unexpected root");
9315 if (VT
!= MVT::i32
&& VT
!= MVT::i64
)
9319 uint32_t ShiftLHS
= 0;
9320 bool LHSFromHi
= false;
9321 if (!findEXTRHalf(N
->getOperand(0), LHS
, ShiftLHS
, LHSFromHi
))
9325 uint32_t ShiftRHS
= 0;
9326 bool RHSFromHi
= false;
9327 if (!findEXTRHalf(N
->getOperand(1), RHS
, ShiftRHS
, RHSFromHi
))
9330 // If they're both trying to come from the high part of the register, they're
9331 // not really an EXTR.
9332 if (LHSFromHi
== RHSFromHi
)
9335 if (ShiftLHS
+ ShiftRHS
!= VT
.getSizeInBits())
9339 std::swap(LHS
, RHS
);
9340 std::swap(ShiftLHS
, ShiftRHS
);
9343 return DAG
.getNode(AArch64ISD::EXTR
, DL
, VT
, LHS
, RHS
,
9344 DAG
.getConstant(ShiftRHS
, DL
, MVT::i64
));
9347 static SDValue
tryCombineToBSL(SDNode
*N
,
9348 TargetLowering::DAGCombinerInfo
&DCI
) {
9349 EVT VT
= N
->getValueType(0);
9350 SelectionDAG
&DAG
= DCI
.DAG
;
9356 SDValue N0
= N
->getOperand(0);
9357 if (N0
.getOpcode() != ISD::AND
)
9360 SDValue N1
= N
->getOperand(1);
9361 if (N1
.getOpcode() != ISD::AND
)
9364 // We only have to look for constant vectors here since the general, variable
9365 // case can be handled in TableGen.
9366 unsigned Bits
= VT
.getScalarSizeInBits();
9367 uint64_t BitMask
= Bits
== 64 ? -1ULL : ((1ULL << Bits
) - 1);
9368 for (int i
= 1; i
>= 0; --i
)
9369 for (int j
= 1; j
>= 0; --j
) {
9370 BuildVectorSDNode
*BVN0
= dyn_cast
<BuildVectorSDNode
>(N0
->getOperand(i
));
9371 BuildVectorSDNode
*BVN1
= dyn_cast
<BuildVectorSDNode
>(N1
->getOperand(j
));
9375 bool FoundMatch
= true;
9376 for (unsigned k
= 0; k
< VT
.getVectorNumElements(); ++k
) {
9377 ConstantSDNode
*CN0
= dyn_cast
<ConstantSDNode
>(BVN0
->getOperand(k
));
9378 ConstantSDNode
*CN1
= dyn_cast
<ConstantSDNode
>(BVN1
->getOperand(k
));
9380 CN0
->getZExtValue() != (BitMask
& ~CN1
->getZExtValue())) {
9387 return DAG
.getNode(AArch64ISD::BSL
, DL
, VT
, SDValue(BVN0
, 0),
9388 N0
->getOperand(1 - i
), N1
->getOperand(1 - j
));
9394 static SDValue
performORCombine(SDNode
*N
, TargetLowering::DAGCombinerInfo
&DCI
,
9395 const AArch64Subtarget
*Subtarget
) {
9396 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9397 SelectionDAG
&DAG
= DCI
.DAG
;
9398 EVT VT
= N
->getValueType(0);
9400 if (!DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
9403 if (SDValue Res
= tryCombineToEXTR(N
, DCI
))
9406 if (SDValue Res
= tryCombineToBSL(N
, DCI
))
9412 static SDValue
performSRLCombine(SDNode
*N
,
9413 TargetLowering::DAGCombinerInfo
&DCI
) {
9414 SelectionDAG
&DAG
= DCI
.DAG
;
9415 EVT VT
= N
->getValueType(0);
9416 if (VT
!= MVT::i32
&& VT
!= MVT::i64
)
9419 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9420 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9421 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9422 SDValue N0
= N
->getOperand(0);
9423 if (N0
.getOpcode() == ISD::BSWAP
) {
9425 SDValue N1
= N
->getOperand(1);
9426 SDValue N00
= N0
.getOperand(0);
9427 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N1
)) {
9428 uint64_t ShiftAmt
= C
->getZExtValue();
9429 if (VT
== MVT::i32
&& ShiftAmt
== 16 &&
9430 DAG
.MaskedValueIsZero(N00
, APInt::getHighBitsSet(32, 16)))
9431 return DAG
.getNode(ISD::ROTR
, DL
, VT
, N0
, N1
);
9432 if (VT
== MVT::i64
&& ShiftAmt
== 32 &&
9433 DAG
.MaskedValueIsZero(N00
, APInt::getHighBitsSet(64, 32)))
9434 return DAG
.getNode(ISD::ROTR
, DL
, VT
, N0
, N1
);
9440 static SDValue
performBitcastCombine(SDNode
*N
,
9441 TargetLowering::DAGCombinerInfo
&DCI
,
9442 SelectionDAG
&DAG
) {
9443 // Wait 'til after everything is legalized to try this. That way we have
9444 // legal vector types and such.
9445 if (DCI
.isBeforeLegalizeOps())
9448 // Remove extraneous bitcasts around an extract_subvector.
9450 // (v4i16 (bitconvert
9451 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9453 // (extract_subvector ((v8i16 ...), (i64 4)))
9455 // Only interested in 64-bit vectors as the ultimate result.
9456 EVT VT
= N
->getValueType(0);
9459 if (VT
.getSimpleVT().getSizeInBits() != 64)
9461 // Is the operand an extract_subvector starting at the beginning or halfway
9462 // point of the vector? A low half may also come through as an
9463 // EXTRACT_SUBREG, so look for that, too.
9464 SDValue Op0
= N
->getOperand(0);
9465 if (Op0
->getOpcode() != ISD::EXTRACT_SUBVECTOR
&&
9466 !(Op0
->isMachineOpcode() &&
9467 Op0
->getMachineOpcode() == AArch64::EXTRACT_SUBREG
))
9469 uint64_t idx
= cast
<ConstantSDNode
>(Op0
->getOperand(1))->getZExtValue();
9470 if (Op0
->getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
9471 if (Op0
->getValueType(0).getVectorNumElements() != idx
&& idx
!= 0)
9473 } else if (Op0
->getMachineOpcode() == AArch64::EXTRACT_SUBREG
) {
9474 if (idx
!= AArch64::dsub
)
9476 // The dsub reference is equivalent to a lane zero subvector reference.
9479 // Look through the bitcast of the input to the extract.
9480 if (Op0
->getOperand(0)->getOpcode() != ISD::BITCAST
)
9482 SDValue Source
= Op0
->getOperand(0)->getOperand(0);
9483 // If the source type has twice the number of elements as our destination
9484 // type, we know this is an extract of the high or low half of the vector.
9485 EVT SVT
= Source
->getValueType(0);
9486 if (!SVT
.isVector() ||
9487 SVT
.getVectorNumElements() != VT
.getVectorNumElements() * 2)
9491 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9493 // Create the simplified form to just extract the low or high half of the
9494 // vector directly rather than bothering with the bitcasts.
9496 unsigned NumElements
= VT
.getVectorNumElements();
9498 SDValue HalfIdx
= DAG
.getConstant(NumElements
, dl
, MVT::i64
);
9499 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, Source
, HalfIdx
);
9501 SDValue SubReg
= DAG
.getTargetConstant(AArch64::dsub
, dl
, MVT::i32
);
9502 return SDValue(DAG
.getMachineNode(TargetOpcode::EXTRACT_SUBREG
, dl
, VT
,
9508 static SDValue
performConcatVectorsCombine(SDNode
*N
,
9509 TargetLowering::DAGCombinerInfo
&DCI
,
9510 SelectionDAG
&DAG
) {
9512 EVT VT
= N
->getValueType(0);
9513 SDValue N0
= N
->getOperand(0), N1
= N
->getOperand(1);
9515 // Optimize concat_vectors of truncated vectors, where the intermediate
9516 // type is illegal, to avoid said illegality, e.g.,
9517 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9518 // (v2i16 (truncate (v2i64)))))
9520 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9521 // (v4i32 (bitcast (v2i64))),
9523 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9524 // on both input and result type, so we might generate worse code.
9525 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9526 if (N
->getNumOperands() == 2 &&
9527 N0
->getOpcode() == ISD::TRUNCATE
&&
9528 N1
->getOpcode() == ISD::TRUNCATE
) {
9529 SDValue N00
= N0
->getOperand(0);
9530 SDValue N10
= N1
->getOperand(0);
9531 EVT N00VT
= N00
.getValueType();
9533 if (N00VT
== N10
.getValueType() &&
9534 (N00VT
== MVT::v2i64
|| N00VT
== MVT::v4i32
) &&
9535 N00VT
.getScalarSizeInBits() == 4 * VT
.getScalarSizeInBits()) {
9536 MVT MidVT
= (N00VT
== MVT::v2i64
? MVT::v4i32
: MVT::v8i16
);
9537 SmallVector
<int, 8> Mask(MidVT
.getVectorNumElements());
9538 for (size_t i
= 0; i
< Mask
.size(); ++i
)
9540 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
9541 DAG
.getVectorShuffle(
9543 DAG
.getNode(ISD::BITCAST
, dl
, MidVT
, N00
),
9544 DAG
.getNode(ISD::BITCAST
, dl
, MidVT
, N10
), Mask
));
9548 // Wait 'til after everything is legalized to try this. That way we have
9549 // legal vector types and such.
9550 if (DCI
.isBeforeLegalizeOps())
9553 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9554 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9555 // canonicalise to that.
9556 if (N0
== N1
&& VT
.getVectorNumElements() == 2) {
9557 assert(VT
.getScalarSizeInBits() == 64);
9558 return DAG
.getNode(AArch64ISD::DUPLANE64
, dl
, VT
, WidenVector(N0
, DAG
),
9559 DAG
.getConstant(0, dl
, MVT::i64
));
9562 // Canonicalise concat_vectors so that the right-hand vector has as few
9563 // bit-casts as possible before its real operation. The primary matching
9564 // destination for these operations will be the narrowing "2" instructions,
9565 // which depend on the operation being performed on this right-hand vector.
9567 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9569 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9571 if (N1
->getOpcode() != ISD::BITCAST
)
9573 SDValue RHS
= N1
->getOperand(0);
9574 MVT RHSTy
= RHS
.getValueType().getSimpleVT();
9575 // If the RHS is not a vector, this is not the pattern we're looking for.
9576 if (!RHSTy
.isVector())
9580 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9582 MVT ConcatTy
= MVT::getVectorVT(RHSTy
.getVectorElementType(),
9583 RHSTy
.getVectorNumElements() * 2);
9584 return DAG
.getNode(ISD::BITCAST
, dl
, VT
,
9585 DAG
.getNode(ISD::CONCAT_VECTORS
, dl
, ConcatTy
,
9586 DAG
.getNode(ISD::BITCAST
, dl
, RHSTy
, N0
),
9590 static SDValue
tryCombineFixedPointConvert(SDNode
*N
,
9591 TargetLowering::DAGCombinerInfo
&DCI
,
9592 SelectionDAG
&DAG
) {
9593 // Wait until after everything is legalized to try this. That way we have
9594 // legal vector types and such.
9595 if (DCI
.isBeforeLegalizeOps())
9597 // Transform a scalar conversion of a value from a lane extract into a
9598 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9599 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9600 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9602 // The second form interacts better with instruction selection and the
9603 // register allocator to avoid cross-class register copies that aren't
9604 // coalescable due to a lane reference.
9606 // Check the operand and see if it originates from a lane extract.
9607 SDValue Op1
= N
->getOperand(1);
9608 if (Op1
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
) {
9609 // Yep, no additional predication needed. Perform the transform.
9610 SDValue IID
= N
->getOperand(0);
9611 SDValue Shift
= N
->getOperand(2);
9612 SDValue Vec
= Op1
.getOperand(0);
9613 SDValue Lane
= Op1
.getOperand(1);
9614 EVT ResTy
= N
->getValueType(0);
9618 // The vector width should be 128 bits by the time we get here, even
9619 // if it started as 64 bits (the extract_vector handling will have
9621 assert(Vec
.getValueSizeInBits() == 128 &&
9622 "unexpected vector size on extract_vector_elt!");
9623 if (Vec
.getValueType() == MVT::v4i32
)
9624 VecResTy
= MVT::v4f32
;
9625 else if (Vec
.getValueType() == MVT::v2i64
)
9626 VecResTy
= MVT::v2f64
;
9628 llvm_unreachable("unexpected vector type!");
9631 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VecResTy
, IID
, Vec
, Shift
);
9632 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ResTy
, Convert
, Lane
);
9637 // AArch64 high-vector "long" operations are formed by performing the non-high
9638 // version on an extract_subvector of each operand which gets the high half:
9640 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9642 // However, there are cases which don't have an extract_high explicitly, but
9643 // have another operation that can be made compatible with one for free. For
9646 // (dupv64 scalar) --> (extract_high (dup128 scalar))
9648 // This routine does the actual conversion of such DUPs, once outer routines
9649 // have determined that everything else is in order.
9650 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9652 static SDValue
tryExtendDUPToExtractHigh(SDValue N
, SelectionDAG
&DAG
) {
9653 switch (N
.getOpcode()) {
9654 case AArch64ISD::DUP
:
9655 case AArch64ISD::DUPLANE8
:
9656 case AArch64ISD::DUPLANE16
:
9657 case AArch64ISD::DUPLANE32
:
9658 case AArch64ISD::DUPLANE64
:
9659 case AArch64ISD::MOVI
:
9660 case AArch64ISD::MOVIshift
:
9661 case AArch64ISD::MOVIedit
:
9662 case AArch64ISD::MOVImsl
:
9663 case AArch64ISD::MVNIshift
:
9664 case AArch64ISD::MVNImsl
:
9667 // FMOV could be supported, but isn't very useful, as it would only occur
9668 // if you passed a bitcast' floating point immediate to an eligible long
9669 // integer op (addl, smull, ...).
9673 MVT NarrowTy
= N
.getSimpleValueType();
9674 if (!NarrowTy
.is64BitVector())
9677 MVT ElementTy
= NarrowTy
.getVectorElementType();
9678 unsigned NumElems
= NarrowTy
.getVectorNumElements();
9679 MVT NewVT
= MVT::getVectorVT(ElementTy
, NumElems
* 2);
9682 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, NarrowTy
,
9683 DAG
.getNode(N
->getOpcode(), dl
, NewVT
, N
->ops()),
9684 DAG
.getConstant(NumElems
, dl
, MVT::i64
));
9687 static bool isEssentiallyExtractHighSubvector(SDValue N
) {
9688 if (N
.getOpcode() == ISD::BITCAST
)
9689 N
= N
.getOperand(0);
9690 if (N
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
9692 return cast
<ConstantSDNode
>(N
.getOperand(1))->getAPIntValue() ==
9693 N
.getOperand(0).getValueType().getVectorNumElements() / 2;
9696 /// Helper structure to keep track of ISD::SET_CC operands.
9697 struct GenericSetCCInfo
{
9698 const SDValue
*Opnd0
;
9699 const SDValue
*Opnd1
;
9703 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9704 struct AArch64SetCCInfo
{
9706 AArch64CC::CondCode CC
;
9709 /// Helper structure to keep track of SetCC information.
9711 GenericSetCCInfo Generic
;
9712 AArch64SetCCInfo AArch64
;
9715 /// Helper structure to be able to read SetCC information. If set to
9716 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9717 /// GenericSetCCInfo.
9718 struct SetCCInfoAndKind
{
9723 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9725 /// AArch64 lowered one.
9726 /// \p SetCCInfo is filled accordingly.
9727 /// \post SetCCInfo is meanginfull only when this function returns true.
9728 /// \return True when Op is a kind of SET_CC operation.
9729 static bool isSetCC(SDValue Op
, SetCCInfoAndKind
&SetCCInfo
) {
9730 // If this is a setcc, this is straight forward.
9731 if (Op
.getOpcode() == ISD::SETCC
) {
9732 SetCCInfo
.Info
.Generic
.Opnd0
= &Op
.getOperand(0);
9733 SetCCInfo
.Info
.Generic
.Opnd1
= &Op
.getOperand(1);
9734 SetCCInfo
.Info
.Generic
.CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
9735 SetCCInfo
.IsAArch64
= false;
9738 // Otherwise, check if this is a matching csel instruction.
9742 if (Op
.getOpcode() != AArch64ISD::CSEL
)
9744 // Set the information about the operands.
9745 // TODO: we want the operands of the Cmp not the csel
9746 SetCCInfo
.Info
.AArch64
.Cmp
= &Op
.getOperand(3);
9747 SetCCInfo
.IsAArch64
= true;
9748 SetCCInfo
.Info
.AArch64
.CC
= static_cast<AArch64CC::CondCode
>(
9749 cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue());
9751 // Check that the operands matches the constraints:
9752 // (1) Both operands must be constants.
9753 // (2) One must be 1 and the other must be 0.
9754 ConstantSDNode
*TValue
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(0));
9755 ConstantSDNode
*FValue
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
9758 if (!TValue
|| !FValue
)
9762 if (!TValue
->isOne()) {
9763 // Update the comparison when we are interested in !cc.
9764 std::swap(TValue
, FValue
);
9765 SetCCInfo
.Info
.AArch64
.CC
=
9766 AArch64CC::getInvertedCondCode(SetCCInfo
.Info
.AArch64
.CC
);
9768 return TValue
->isOne() && FValue
->isNullValue();
9771 // Returns true if Op is setcc or zext of setcc.
9772 static bool isSetCCOrZExtSetCC(const SDValue
& Op
, SetCCInfoAndKind
&Info
) {
9773 if (isSetCC(Op
, Info
))
9775 return ((Op
.getOpcode() == ISD::ZERO_EXTEND
) &&
9776 isSetCC(Op
->getOperand(0), Info
));
9779 // The folding we want to perform is:
9780 // (add x, [zext] (setcc cc ...) )
9782 // (csel x, (add x, 1), !cc ...)
9784 // The latter will get matched to a CSINC instruction.
9785 static SDValue
performSetccAddFolding(SDNode
*Op
, SelectionDAG
&DAG
) {
9786 assert(Op
&& Op
->getOpcode() == ISD::ADD
&& "Unexpected operation!");
9787 SDValue LHS
= Op
->getOperand(0);
9788 SDValue RHS
= Op
->getOperand(1);
9789 SetCCInfoAndKind InfoAndKind
;
9791 // If neither operand is a SET_CC, give up.
9792 if (!isSetCCOrZExtSetCC(LHS
, InfoAndKind
)) {
9793 std::swap(LHS
, RHS
);
9794 if (!isSetCCOrZExtSetCC(LHS
, InfoAndKind
))
9798 // FIXME: This could be generatized to work for FP comparisons.
9799 EVT CmpVT
= InfoAndKind
.IsAArch64
9800 ? InfoAndKind
.Info
.AArch64
.Cmp
->getOperand(0).getValueType()
9801 : InfoAndKind
.Info
.Generic
.Opnd0
->getValueType();
9802 if (CmpVT
!= MVT::i32
&& CmpVT
!= MVT::i64
)
9808 if (InfoAndKind
.IsAArch64
) {
9809 CCVal
= DAG
.getConstant(
9810 AArch64CC::getInvertedCondCode(InfoAndKind
.Info
.AArch64
.CC
), dl
,
9812 Cmp
= *InfoAndKind
.Info
.AArch64
.Cmp
;
9814 Cmp
= getAArch64Cmp(*InfoAndKind
.Info
.Generic
.Opnd0
,
9815 *InfoAndKind
.Info
.Generic
.Opnd1
,
9816 ISD::getSetCCInverse(InfoAndKind
.Info
.Generic
.CC
, true),
9819 EVT VT
= Op
->getValueType(0);
9820 LHS
= DAG
.getNode(ISD::ADD
, dl
, VT
, RHS
, DAG
.getConstant(1, dl
, VT
));
9821 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, RHS
, LHS
, CCVal
, Cmp
);
9824 // The basic add/sub long vector instructions have variants with "2" on the end
9825 // which act on the high-half of their inputs. They are normally matched by
9828 // (add (zeroext (extract_high LHS)),
9829 // (zeroext (extract_high RHS)))
9830 // -> uaddl2 vD, vN, vM
9832 // However, if one of the extracts is something like a duplicate, this
9833 // instruction can still be used profitably. This function puts the DAG into a
9834 // more appropriate form for those patterns to trigger.
9835 static SDValue
performAddSubLongCombine(SDNode
*N
,
9836 TargetLowering::DAGCombinerInfo
&DCI
,
9837 SelectionDAG
&DAG
) {
9838 if (DCI
.isBeforeLegalizeOps())
9841 MVT VT
= N
->getSimpleValueType(0);
9842 if (!VT
.is128BitVector()) {
9843 if (N
->getOpcode() == ISD::ADD
)
9844 return performSetccAddFolding(N
, DAG
);
9848 // Make sure both branches are extended in the same way.
9849 SDValue LHS
= N
->getOperand(0);
9850 SDValue RHS
= N
->getOperand(1);
9851 if ((LHS
.getOpcode() != ISD::ZERO_EXTEND
&&
9852 LHS
.getOpcode() != ISD::SIGN_EXTEND
) ||
9853 LHS
.getOpcode() != RHS
.getOpcode())
9856 unsigned ExtType
= LHS
.getOpcode();
9858 // It's not worth doing if at least one of the inputs isn't already an
9859 // extract, but we don't know which it'll be so we have to try both.
9860 if (isEssentiallyExtractHighSubvector(LHS
.getOperand(0))) {
9861 RHS
= tryExtendDUPToExtractHigh(RHS
.getOperand(0), DAG
);
9865 RHS
= DAG
.getNode(ExtType
, SDLoc(N
), VT
, RHS
);
9866 } else if (isEssentiallyExtractHighSubvector(RHS
.getOperand(0))) {
9867 LHS
= tryExtendDUPToExtractHigh(LHS
.getOperand(0), DAG
);
9871 LHS
= DAG
.getNode(ExtType
, SDLoc(N
), VT
, LHS
);
9874 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, LHS
, RHS
);
9877 // Massage DAGs which we can use the high-half "long" operations on into
9878 // something isel will recognize better. E.g.
9880 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9881 // (aarch64_neon_umull (extract_high (v2i64 vec)))
9882 // (extract_high (v2i64 (dup128 scalar)))))
9884 static SDValue
tryCombineLongOpWithDup(unsigned IID
, SDNode
*N
,
9885 TargetLowering::DAGCombinerInfo
&DCI
,
9886 SelectionDAG
&DAG
) {
9887 if (DCI
.isBeforeLegalizeOps())
9890 SDValue LHS
= N
->getOperand(1);
9891 SDValue RHS
= N
->getOperand(2);
9892 assert(LHS
.getValueType().is64BitVector() &&
9893 RHS
.getValueType().is64BitVector() &&
9894 "unexpected shape for long operation");
9896 // Either node could be a DUP, but it's not worth doing both of them (you'd
9897 // just as well use the non-high version) so look for a corresponding extract
9898 // operation on the other "wing".
9899 if (isEssentiallyExtractHighSubvector(LHS
)) {
9900 RHS
= tryExtendDUPToExtractHigh(RHS
, DAG
);
9903 } else if (isEssentiallyExtractHighSubvector(RHS
)) {
9904 LHS
= tryExtendDUPToExtractHigh(LHS
, DAG
);
9909 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, SDLoc(N
), N
->getValueType(0),
9910 N
->getOperand(0), LHS
, RHS
);
9913 static SDValue
tryCombineShiftImm(unsigned IID
, SDNode
*N
, SelectionDAG
&DAG
) {
9914 MVT ElemTy
= N
->getSimpleValueType(0).getScalarType();
9915 unsigned ElemBits
= ElemTy
.getSizeInBits();
9917 int64_t ShiftAmount
;
9918 if (BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(N
->getOperand(2))) {
9919 APInt SplatValue
, SplatUndef
;
9920 unsigned SplatBitSize
;
9922 if (!BVN
->isConstantSplat(SplatValue
, SplatUndef
, SplatBitSize
,
9923 HasAnyUndefs
, ElemBits
) ||
9924 SplatBitSize
!= ElemBits
)
9927 ShiftAmount
= SplatValue
.getSExtValue();
9928 } else if (ConstantSDNode
*CVN
= dyn_cast
<ConstantSDNode
>(N
->getOperand(2))) {
9929 ShiftAmount
= CVN
->getSExtValue();
9937 llvm_unreachable("Unknown shift intrinsic");
9938 case Intrinsic::aarch64_neon_sqshl
:
9939 Opcode
= AArch64ISD::SQSHL_I
;
9940 IsRightShift
= false;
9942 case Intrinsic::aarch64_neon_uqshl
:
9943 Opcode
= AArch64ISD::UQSHL_I
;
9944 IsRightShift
= false;
9946 case Intrinsic::aarch64_neon_srshl
:
9947 Opcode
= AArch64ISD::SRSHR_I
;
9948 IsRightShift
= true;
9950 case Intrinsic::aarch64_neon_urshl
:
9951 Opcode
= AArch64ISD::URSHR_I
;
9952 IsRightShift
= true;
9954 case Intrinsic::aarch64_neon_sqshlu
:
9955 Opcode
= AArch64ISD::SQSHLU_I
;
9956 IsRightShift
= false;
9960 if (IsRightShift
&& ShiftAmount
<= -1 && ShiftAmount
>= -(int)ElemBits
) {
9962 return DAG
.getNode(Opcode
, dl
, N
->getValueType(0), N
->getOperand(1),
9963 DAG
.getConstant(-ShiftAmount
, dl
, MVT::i32
));
9964 } else if (!IsRightShift
&& ShiftAmount
>= 0 && ShiftAmount
< ElemBits
) {
9966 return DAG
.getNode(Opcode
, dl
, N
->getValueType(0), N
->getOperand(1),
9967 DAG
.getConstant(ShiftAmount
, dl
, MVT::i32
));
9973 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9974 // the intrinsics must be legal and take an i32, this means there's almost
9975 // certainly going to be a zext in the DAG which we can eliminate.
9976 static SDValue
tryCombineCRC32(unsigned Mask
, SDNode
*N
, SelectionDAG
&DAG
) {
9977 SDValue AndN
= N
->getOperand(2);
9978 if (AndN
.getOpcode() != ISD::AND
)
9981 ConstantSDNode
*CMask
= dyn_cast
<ConstantSDNode
>(AndN
.getOperand(1));
9982 if (!CMask
|| CMask
->getZExtValue() != Mask
)
9985 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, SDLoc(N
), MVT::i32
,
9986 N
->getOperand(0), N
->getOperand(1), AndN
.getOperand(0));
9989 static SDValue
combineAcrossLanesIntrinsic(unsigned Opc
, SDNode
*N
,
9990 SelectionDAG
&DAG
) {
9992 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, dl
, N
->getValueType(0),
9993 DAG
.getNode(Opc
, dl
,
9994 N
->getOperand(1).getSimpleValueType(),
9996 DAG
.getConstant(0, dl
, MVT::i64
));
9999 static SDValue
performIntrinsicCombine(SDNode
*N
,
10000 TargetLowering::DAGCombinerInfo
&DCI
,
10001 const AArch64Subtarget
*Subtarget
) {
10002 SelectionDAG
&DAG
= DCI
.DAG
;
10003 unsigned IID
= getIntrinsicID(N
);
10007 case Intrinsic::aarch64_neon_vcvtfxs2fp
:
10008 case Intrinsic::aarch64_neon_vcvtfxu2fp
:
10009 return tryCombineFixedPointConvert(N
, DCI
, DAG
);
10010 case Intrinsic::aarch64_neon_saddv
:
10011 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV
, N
, DAG
);
10012 case Intrinsic::aarch64_neon_uaddv
:
10013 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV
, N
, DAG
);
10014 case Intrinsic::aarch64_neon_sminv
:
10015 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV
, N
, DAG
);
10016 case Intrinsic::aarch64_neon_uminv
:
10017 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV
, N
, DAG
);
10018 case Intrinsic::aarch64_neon_smaxv
:
10019 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV
, N
, DAG
);
10020 case Intrinsic::aarch64_neon_umaxv
:
10021 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV
, N
, DAG
);
10022 case Intrinsic::aarch64_neon_fmax
:
10023 return DAG
.getNode(ISD::FMAXIMUM
, SDLoc(N
), N
->getValueType(0),
10024 N
->getOperand(1), N
->getOperand(2));
10025 case Intrinsic::aarch64_neon_fmin
:
10026 return DAG
.getNode(ISD::FMINIMUM
, SDLoc(N
), N
->getValueType(0),
10027 N
->getOperand(1), N
->getOperand(2));
10028 case Intrinsic::aarch64_neon_fmaxnm
:
10029 return DAG
.getNode(ISD::FMAXNUM
, SDLoc(N
), N
->getValueType(0),
10030 N
->getOperand(1), N
->getOperand(2));
10031 case Intrinsic::aarch64_neon_fminnm
:
10032 return DAG
.getNode(ISD::FMINNUM
, SDLoc(N
), N
->getValueType(0),
10033 N
->getOperand(1), N
->getOperand(2));
10034 case Intrinsic::aarch64_neon_smull
:
10035 case Intrinsic::aarch64_neon_umull
:
10036 case Intrinsic::aarch64_neon_pmull
:
10037 case Intrinsic::aarch64_neon_sqdmull
:
10038 return tryCombineLongOpWithDup(IID
, N
, DCI
, DAG
);
10039 case Intrinsic::aarch64_neon_sqshl
:
10040 case Intrinsic::aarch64_neon_uqshl
:
10041 case Intrinsic::aarch64_neon_sqshlu
:
10042 case Intrinsic::aarch64_neon_srshl
:
10043 case Intrinsic::aarch64_neon_urshl
:
10044 return tryCombineShiftImm(IID
, N
, DAG
);
10045 case Intrinsic::aarch64_crc32b
:
10046 case Intrinsic::aarch64_crc32cb
:
10047 return tryCombineCRC32(0xff, N
, DAG
);
10048 case Intrinsic::aarch64_crc32h
:
10049 case Intrinsic::aarch64_crc32ch
:
10050 return tryCombineCRC32(0xffff, N
, DAG
);
10055 static SDValue
performExtendCombine(SDNode
*N
,
10056 TargetLowering::DAGCombinerInfo
&DCI
,
10057 SelectionDAG
&DAG
) {
10058 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10059 // we can convert that DUP into another extract_high (of a bigger DUP), which
10060 // helps the backend to decide that an sabdl2 would be useful, saving a real
10061 // extract_high operation.
10062 if (!DCI
.isBeforeLegalizeOps() && N
->getOpcode() == ISD::ZERO_EXTEND
&&
10063 N
->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN
) {
10064 SDNode
*ABDNode
= N
->getOperand(0).getNode();
10065 unsigned IID
= getIntrinsicID(ABDNode
);
10066 if (IID
== Intrinsic::aarch64_neon_sabd
||
10067 IID
== Intrinsic::aarch64_neon_uabd
) {
10068 SDValue NewABD
= tryCombineLongOpWithDup(IID
, ABDNode
, DCI
, DAG
);
10069 if (!NewABD
.getNode())
10072 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
), N
->getValueType(0),
10077 // This is effectively a custom type legalization for AArch64.
10079 // Type legalization will split an extend of a small, legal, type to a larger
10080 // illegal type by first splitting the destination type, often creating
10081 // illegal source types, which then get legalized in isel-confusing ways,
10082 // leading to really terrible codegen. E.g.,
10083 // %result = v8i32 sext v8i8 %value
10085 // %losrc = extract_subreg %value, ...
10086 // %hisrc = extract_subreg %value, ...
10087 // %lo = v4i32 sext v4i8 %losrc
10088 // %hi = v4i32 sext v4i8 %hisrc
10089 // Things go rapidly downhill from there.
10091 // For AArch64, the [sz]ext vector instructions can only go up one element
10092 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10093 // take two instructions.
10095 // This implies that the most efficient way to do the extend from v8i8
10096 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10097 // the normal splitting to happen for the v8i16->v8i32.
10099 // This is pre-legalization to catch some cases where the default
10100 // type legalization will create ill-tempered code.
10101 if (!DCI
.isBeforeLegalizeOps())
10104 // We're only interested in cleaning things up for non-legal vector types
10105 // here. If both the source and destination are legal, things will just
10106 // work naturally without any fiddling.
10107 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
10108 EVT ResVT
= N
->getValueType(0);
10109 if (!ResVT
.isVector() || TLI
.isTypeLegal(ResVT
))
10111 // If the vector type isn't a simple VT, it's beyond the scope of what
10112 // we're worried about here. Let legalization do its thing and hope for
10114 SDValue Src
= N
->getOperand(0);
10115 EVT SrcVT
= Src
->getValueType(0);
10116 if (!ResVT
.isSimple() || !SrcVT
.isSimple())
10119 // If the source VT is a 64-bit vector, we can play games and get the
10120 // better results we want.
10121 if (SrcVT
.getSizeInBits() != 64)
10124 unsigned SrcEltSize
= SrcVT
.getScalarSizeInBits();
10125 unsigned ElementCount
= SrcVT
.getVectorNumElements();
10126 SrcVT
= MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize
* 2), ElementCount
);
10128 Src
= DAG
.getNode(N
->getOpcode(), DL
, SrcVT
, Src
);
10130 // Now split the rest of the operation into two halves, each with a 64
10134 unsigned NumElements
= ResVT
.getVectorNumElements();
10135 assert(!(NumElements
& 1) && "Splitting vector, but not in half!");
10136 LoVT
= HiVT
= EVT::getVectorVT(*DAG
.getContext(),
10137 ResVT
.getVectorElementType(), NumElements
/ 2);
10139 EVT InNVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
.getVectorElementType(),
10140 LoVT
.getVectorNumElements());
10141 Lo
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InNVT
, Src
,
10142 DAG
.getConstant(0, DL
, MVT::i64
));
10143 Hi
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InNVT
, Src
,
10144 DAG
.getConstant(InNVT
.getVectorNumElements(), DL
, MVT::i64
));
10145 Lo
= DAG
.getNode(N
->getOpcode(), DL
, LoVT
, Lo
);
10146 Hi
= DAG
.getNode(N
->getOpcode(), DL
, HiVT
, Hi
);
10148 // Now combine the parts back together so we still have a single result
10149 // like the combiner expects.
10150 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, ResVT
, Lo
, Hi
);
10153 static SDValue
splitStoreSplat(SelectionDAG
&DAG
, StoreSDNode
&St
,
10154 SDValue SplatVal
, unsigned NumVecElts
) {
10155 assert(!St
.isTruncatingStore() && "cannot split truncating vector store");
10156 unsigned OrigAlignment
= St
.getAlignment();
10157 unsigned EltOffset
= SplatVal
.getValueType().getSizeInBits() / 8;
10159 // Create scalar stores. This is at least as good as the code sequence for a
10160 // split unaligned store which is a dup.s, ext.b, and two stores.
10161 // Most of the time the three stores should be replaced by store pair
10162 // instructions (stp).
10164 SDValue BasePtr
= St
.getBasePtr();
10165 uint64_t BaseOffset
= 0;
10167 const MachinePointerInfo
&PtrInfo
= St
.getPointerInfo();
10169 DAG
.getStore(St
.getChain(), DL
, SplatVal
, BasePtr
, PtrInfo
,
10170 OrigAlignment
, St
.getMemOperand()->getFlags());
10172 // As this in ISel, we will not merge this add which may degrade results.
10173 if (BasePtr
->getOpcode() == ISD::ADD
&&
10174 isa
<ConstantSDNode
>(BasePtr
->getOperand(1))) {
10175 BaseOffset
= cast
<ConstantSDNode
>(BasePtr
->getOperand(1))->getSExtValue();
10176 BasePtr
= BasePtr
->getOperand(0);
10179 unsigned Offset
= EltOffset
;
10180 while (--NumVecElts
) {
10181 unsigned Alignment
= MinAlign(OrigAlignment
, Offset
);
10182 SDValue OffsetPtr
=
10183 DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, BasePtr
,
10184 DAG
.getConstant(BaseOffset
+ Offset
, DL
, MVT::i64
));
10185 NewST1
= DAG
.getStore(NewST1
.getValue(0), DL
, SplatVal
, OffsetPtr
,
10186 PtrInfo
.getWithOffset(Offset
), Alignment
,
10187 St
.getMemOperand()->getFlags());
10188 Offset
+= EltOffset
;
10193 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10194 /// load store optimizer pass will merge them to store pair stores. This should
10195 /// be better than a movi to create the vector zero followed by a vector store
10196 /// if the zero constant is not re-used, since one instructions and one register
10197 /// live range will be removed.
10199 /// For example, the final generated code should be:
10201 /// stp xzr, xzr, [x0]
10208 static SDValue
replaceZeroVectorStore(SelectionDAG
&DAG
, StoreSDNode
&St
) {
10209 SDValue StVal
= St
.getValue();
10210 EVT VT
= StVal
.getValueType();
10212 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10213 // 2, 3 or 4 i32 elements.
10214 int NumVecElts
= VT
.getVectorNumElements();
10215 if (!(((NumVecElts
== 2 || NumVecElts
== 3) &&
10216 VT
.getVectorElementType().getSizeInBits() == 64) ||
10217 ((NumVecElts
== 2 || NumVecElts
== 3 || NumVecElts
== 4) &&
10218 VT
.getVectorElementType().getSizeInBits() == 32)))
10221 if (StVal
.getOpcode() != ISD::BUILD_VECTOR
)
10224 // If the zero constant has more than one use then the vector store could be
10225 // better since the constant mov will be amortized and stp q instructions
10226 // should be able to be formed.
10227 if (!StVal
.hasOneUse())
10230 // If the store is truncating then it's going down to i16 or smaller, which
10231 // means it can be implemented in a single store anyway.
10232 if (St
.isTruncatingStore())
10235 // If the immediate offset of the address operand is too large for the stp
10236 // instruction, then bail out.
10237 if (DAG
.isBaseWithConstantOffset(St
.getBasePtr())) {
10238 int64_t Offset
= St
.getBasePtr()->getConstantOperandVal(1);
10239 if (Offset
< -512 || Offset
> 504)
10243 for (int I
= 0; I
< NumVecElts
; ++I
) {
10244 SDValue EltVal
= StVal
.getOperand(I
);
10245 if (!isNullConstant(EltVal
) && !isNullFPConstant(EltVal
))
10249 // Use a CopyFromReg WZR/XZR here to prevent
10250 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10254 if (VT
.getVectorElementType().getSizeInBits() == 32) {
10255 ZeroReg
= AArch64::WZR
;
10258 ZeroReg
= AArch64::XZR
;
10262 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, ZeroReg
, ZeroVT
);
10263 return splitStoreSplat(DAG
, St
, SplatVal
, NumVecElts
);
10266 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10267 /// value. The load store optimizer pass will merge them to store pair stores.
10268 /// This has better performance than a splat of the scalar followed by a split
10269 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10270 /// followed by an ext.b and two stores.
10271 static SDValue
replaceSplatVectorStore(SelectionDAG
&DAG
, StoreSDNode
&St
) {
10272 SDValue StVal
= St
.getValue();
10273 EVT VT
= StVal
.getValueType();
10275 // Don't replace floating point stores, they possibly won't be transformed to
10276 // stp because of the store pair suppress pass.
10277 if (VT
.isFloatingPoint())
10280 // We can express a splat as store pair(s) for 2 or 4 elements.
10281 unsigned NumVecElts
= VT
.getVectorNumElements();
10282 if (NumVecElts
!= 4 && NumVecElts
!= 2)
10285 // If the store is truncating then it's going down to i16 or smaller, which
10286 // means it can be implemented in a single store anyway.
10287 if (St
.isTruncatingStore())
10290 // Check that this is a splat.
10291 // Make sure that each of the relevant vector element locations are inserted
10292 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10293 std::bitset
<4> IndexNotInserted((1 << NumVecElts
) - 1);
10295 for (unsigned I
= 0; I
< NumVecElts
; ++I
) {
10296 // Check for insert vector elements.
10297 if (StVal
.getOpcode() != ISD::INSERT_VECTOR_ELT
)
10300 // Check that same value is inserted at each vector element.
10302 SplatVal
= StVal
.getOperand(1);
10303 else if (StVal
.getOperand(1) != SplatVal
)
10306 // Check insert element index.
10307 ConstantSDNode
*CIndex
= dyn_cast
<ConstantSDNode
>(StVal
.getOperand(2));
10310 uint64_t IndexVal
= CIndex
->getZExtValue();
10311 if (IndexVal
>= NumVecElts
)
10313 IndexNotInserted
.reset(IndexVal
);
10315 StVal
= StVal
.getOperand(0);
10317 // Check that all vector element locations were inserted to.
10318 if (IndexNotInserted
.any())
10321 return splitStoreSplat(DAG
, St
, SplatVal
, NumVecElts
);
10324 static SDValue
splitStores(SDNode
*N
, TargetLowering::DAGCombinerInfo
&DCI
,
10326 const AArch64Subtarget
*Subtarget
) {
10328 StoreSDNode
*S
= cast
<StoreSDNode
>(N
);
10329 if (S
->isVolatile() || S
->isIndexed())
10332 SDValue StVal
= S
->getValue();
10333 EVT VT
= StVal
.getValueType();
10334 if (!VT
.isVector())
10337 // If we get a splat of zeros, convert this vector store to a store of
10338 // scalars. They will be merged into store pairs of xzr thereby removing one
10339 // instruction and one register.
10340 if (SDValue ReplacedZeroSplat
= replaceZeroVectorStore(DAG
, *S
))
10341 return ReplacedZeroSplat
;
10343 // FIXME: The logic for deciding if an unaligned store should be split should
10344 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10345 // a call to that function here.
10347 if (!Subtarget
->isMisaligned128StoreSlow())
10350 // Don't split at -Oz.
10351 if (DAG
.getMachineFunction().getFunction().optForMinSize())
10354 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10355 // those up regresses performance on micro-benchmarks and olden/bh.
10356 if (VT
.getVectorNumElements() < 2 || VT
== MVT::v2i64
)
10359 // Split unaligned 16B stores. They are terrible for performance.
10360 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10361 // extensions can use this to mark that it does not want splitting to happen
10362 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10363 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10364 if (VT
.getSizeInBits() != 128 || S
->getAlignment() >= 16 ||
10365 S
->getAlignment() <= 2)
10368 // If we get a splat of a scalar convert this vector store to a store of
10369 // scalars. They will be merged into store pairs thereby removing two
10371 if (SDValue ReplacedSplat
= replaceSplatVectorStore(DAG
, *S
))
10372 return ReplacedSplat
;
10375 unsigned NumElts
= VT
.getVectorNumElements() / 2;
10376 // Split VT into two.
10378 EVT::getVectorVT(*DAG
.getContext(), VT
.getVectorElementType(), NumElts
);
10379 SDValue SubVector0
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, HalfVT
, StVal
,
10380 DAG
.getConstant(0, DL
, MVT::i64
));
10381 SDValue SubVector1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, HalfVT
, StVal
,
10382 DAG
.getConstant(NumElts
, DL
, MVT::i64
));
10383 SDValue BasePtr
= S
->getBasePtr();
10385 DAG
.getStore(S
->getChain(), DL
, SubVector0
, BasePtr
, S
->getPointerInfo(),
10386 S
->getAlignment(), S
->getMemOperand()->getFlags());
10387 SDValue OffsetPtr
= DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, BasePtr
,
10388 DAG
.getConstant(8, DL
, MVT::i64
));
10389 return DAG
.getStore(NewST1
.getValue(0), DL
, SubVector1
, OffsetPtr
,
10390 S
->getPointerInfo(), S
->getAlignment(),
10391 S
->getMemOperand()->getFlags());
10394 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10395 /// post-increment LD1R.
10396 static SDValue
performPostLD1Combine(SDNode
*N
,
10397 TargetLowering::DAGCombinerInfo
&DCI
,
10399 if (DCI
.isBeforeLegalizeOps())
10402 SelectionDAG
&DAG
= DCI
.DAG
;
10403 EVT VT
= N
->getValueType(0);
10405 unsigned LoadIdx
= IsLaneOp
? 1 : 0;
10406 SDNode
*LD
= N
->getOperand(LoadIdx
).getNode();
10407 // If it is not LOAD, can not do such combine.
10408 if (LD
->getOpcode() != ISD::LOAD
)
10411 // The vector lane must be a constant in the LD1LANE opcode.
10414 Lane
= N
->getOperand(2);
10415 auto *LaneC
= dyn_cast
<ConstantSDNode
>(Lane
);
10416 if (!LaneC
|| LaneC
->getZExtValue() >= VT
.getVectorNumElements())
10420 LoadSDNode
*LoadSDN
= cast
<LoadSDNode
>(LD
);
10421 EVT MemVT
= LoadSDN
->getMemoryVT();
10422 // Check if memory operand is the same type as the vector element.
10423 if (MemVT
!= VT
.getVectorElementType())
10426 // Check if there are other uses. If so, do not combine as it will introduce
10428 for (SDNode::use_iterator UI
= LD
->use_begin(), UE
= LD
->use_end(); UI
!= UE
;
10430 if (UI
.getUse().getResNo() == 1) // Ignore uses of the chain result.
10436 SDValue Addr
= LD
->getOperand(1);
10437 SDValue Vector
= N
->getOperand(0);
10438 // Search for a use of the address operand that is an increment.
10439 for (SDNode::use_iterator UI
= Addr
.getNode()->use_begin(), UE
=
10440 Addr
.getNode()->use_end(); UI
!= UE
; ++UI
) {
10441 SDNode
*User
= *UI
;
10442 if (User
->getOpcode() != ISD::ADD
10443 || UI
.getUse().getResNo() != Addr
.getResNo())
10446 // If the increment is a constant, it must match the memory ref size.
10447 SDValue Inc
= User
->getOperand(User
->getOperand(0) == Addr
? 1 : 0);
10448 if (ConstantSDNode
*CInc
= dyn_cast
<ConstantSDNode
>(Inc
.getNode())) {
10449 uint32_t IncVal
= CInc
->getZExtValue();
10450 unsigned NumBytes
= VT
.getScalarSizeInBits() / 8;
10451 if (IncVal
!= NumBytes
)
10453 Inc
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
10456 // To avoid cycle construction make sure that neither the load nor the add
10457 // are predecessors to each other or the Vector.
10458 SmallPtrSet
<const SDNode
*, 32> Visited
;
10459 SmallVector
<const SDNode
*, 16> Worklist
;
10461 Worklist
.push_back(User
);
10462 Worklist
.push_back(LD
);
10463 Worklist
.push_back(Vector
.getNode());
10464 if (SDNode::hasPredecessorHelper(LD
, Visited
, Worklist
) ||
10465 SDNode::hasPredecessorHelper(User
, Visited
, Worklist
))
10468 SmallVector
<SDValue
, 8> Ops
;
10469 Ops
.push_back(LD
->getOperand(0)); // Chain
10471 Ops
.push_back(Vector
); // The vector to be inserted
10472 Ops
.push_back(Lane
); // The lane to be inserted in the vector
10474 Ops
.push_back(Addr
);
10475 Ops
.push_back(Inc
);
10477 EVT Tys
[3] = { VT
, MVT::i64
, MVT::Other
};
10478 SDVTList SDTys
= DAG
.getVTList(Tys
);
10479 unsigned NewOp
= IsLaneOp
? AArch64ISD::LD1LANEpost
: AArch64ISD::LD1DUPpost
;
10480 SDValue UpdN
= DAG
.getMemIntrinsicNode(NewOp
, SDLoc(N
), SDTys
, Ops
,
10482 LoadSDN
->getMemOperand());
10484 // Update the uses.
10485 SDValue NewResults
[] = {
10486 SDValue(LD
, 0), // The result of load
10487 SDValue(UpdN
.getNode(), 2) // Chain
10489 DCI
.CombineTo(LD
, NewResults
);
10490 DCI
.CombineTo(N
, SDValue(UpdN
.getNode(), 0)); // Dup/Inserted Result
10491 DCI
.CombineTo(User
, SDValue(UpdN
.getNode(), 1)); // Write back register
10498 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10499 /// address translation.
10500 static bool performTBISimplification(SDValue Addr
,
10501 TargetLowering::DAGCombinerInfo
&DCI
,
10502 SelectionDAG
&DAG
) {
10503 APInt DemandedMask
= APInt::getLowBitsSet(64, 56);
10505 TargetLowering::TargetLoweringOpt
TLO(DAG
, !DCI
.isBeforeLegalize(),
10506 !DCI
.isBeforeLegalizeOps());
10507 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
10508 if (TLI
.SimplifyDemandedBits(Addr
, DemandedMask
, Known
, TLO
)) {
10509 DCI
.CommitTargetLoweringOpt(TLO
);
10515 static SDValue
performSTORECombine(SDNode
*N
,
10516 TargetLowering::DAGCombinerInfo
&DCI
,
10518 const AArch64Subtarget
*Subtarget
) {
10519 if (SDValue Split
= splitStores(N
, DCI
, DAG
, Subtarget
))
10522 if (Subtarget
->supportsAddressTopByteIgnored() &&
10523 performTBISimplification(N
->getOperand(2), DCI
, DAG
))
10524 return SDValue(N
, 0);
10530 /// Target-specific DAG combine function for NEON load/store intrinsics
10531 /// to merge base address updates.
10532 static SDValue
performNEONPostLDSTCombine(SDNode
*N
,
10533 TargetLowering::DAGCombinerInfo
&DCI
,
10534 SelectionDAG
&DAG
) {
10535 if (DCI
.isBeforeLegalize() || DCI
.isCalledByLegalizer())
10538 unsigned AddrOpIdx
= N
->getNumOperands() - 1;
10539 SDValue Addr
= N
->getOperand(AddrOpIdx
);
10541 // Search for a use of the address operand that is an increment.
10542 for (SDNode::use_iterator UI
= Addr
.getNode()->use_begin(),
10543 UE
= Addr
.getNode()->use_end(); UI
!= UE
; ++UI
) {
10544 SDNode
*User
= *UI
;
10545 if (User
->getOpcode() != ISD::ADD
||
10546 UI
.getUse().getResNo() != Addr
.getResNo())
10549 // Check that the add is independent of the load/store. Otherwise, folding
10550 // it would create a cycle.
10551 SmallPtrSet
<const SDNode
*, 32> Visited
;
10552 SmallVector
<const SDNode
*, 16> Worklist
;
10553 Visited
.insert(Addr
.getNode());
10554 Worklist
.push_back(N
);
10555 Worklist
.push_back(User
);
10556 if (SDNode::hasPredecessorHelper(N
, Visited
, Worklist
) ||
10557 SDNode::hasPredecessorHelper(User
, Visited
, Worklist
))
10560 // Find the new opcode for the updating load/store.
10561 bool IsStore
= false;
10562 bool IsLaneOp
= false;
10563 bool IsDupOp
= false;
10564 unsigned NewOpc
= 0;
10565 unsigned NumVecs
= 0;
10566 unsigned IntNo
= cast
<ConstantSDNode
>(N
->getOperand(1))->getZExtValue();
10568 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10569 case Intrinsic::aarch64_neon_ld2
: NewOpc
= AArch64ISD::LD2post
;
10570 NumVecs
= 2; break;
10571 case Intrinsic::aarch64_neon_ld3
: NewOpc
= AArch64ISD::LD3post
;
10572 NumVecs
= 3; break;
10573 case Intrinsic::aarch64_neon_ld4
: NewOpc
= AArch64ISD::LD4post
;
10574 NumVecs
= 4; break;
10575 case Intrinsic::aarch64_neon_st2
: NewOpc
= AArch64ISD::ST2post
;
10576 NumVecs
= 2; IsStore
= true; break;
10577 case Intrinsic::aarch64_neon_st3
: NewOpc
= AArch64ISD::ST3post
;
10578 NumVecs
= 3; IsStore
= true; break;
10579 case Intrinsic::aarch64_neon_st4
: NewOpc
= AArch64ISD::ST4post
;
10580 NumVecs
= 4; IsStore
= true; break;
10581 case Intrinsic::aarch64_neon_ld1x2
: NewOpc
= AArch64ISD::LD1x2post
;
10582 NumVecs
= 2; break;
10583 case Intrinsic::aarch64_neon_ld1x3
: NewOpc
= AArch64ISD::LD1x3post
;
10584 NumVecs
= 3; break;
10585 case Intrinsic::aarch64_neon_ld1x4
: NewOpc
= AArch64ISD::LD1x4post
;
10586 NumVecs
= 4; break;
10587 case Intrinsic::aarch64_neon_st1x2
: NewOpc
= AArch64ISD::ST1x2post
;
10588 NumVecs
= 2; IsStore
= true; break;
10589 case Intrinsic::aarch64_neon_st1x3
: NewOpc
= AArch64ISD::ST1x3post
;
10590 NumVecs
= 3; IsStore
= true; break;
10591 case Intrinsic::aarch64_neon_st1x4
: NewOpc
= AArch64ISD::ST1x4post
;
10592 NumVecs
= 4; IsStore
= true; break;
10593 case Intrinsic::aarch64_neon_ld2r
: NewOpc
= AArch64ISD::LD2DUPpost
;
10594 NumVecs
= 2; IsDupOp
= true; break;
10595 case Intrinsic::aarch64_neon_ld3r
: NewOpc
= AArch64ISD::LD3DUPpost
;
10596 NumVecs
= 3; IsDupOp
= true; break;
10597 case Intrinsic::aarch64_neon_ld4r
: NewOpc
= AArch64ISD::LD4DUPpost
;
10598 NumVecs
= 4; IsDupOp
= true; break;
10599 case Intrinsic::aarch64_neon_ld2lane
: NewOpc
= AArch64ISD::LD2LANEpost
;
10600 NumVecs
= 2; IsLaneOp
= true; break;
10601 case Intrinsic::aarch64_neon_ld3lane
: NewOpc
= AArch64ISD::LD3LANEpost
;
10602 NumVecs
= 3; IsLaneOp
= true; break;
10603 case Intrinsic::aarch64_neon_ld4lane
: NewOpc
= AArch64ISD::LD4LANEpost
;
10604 NumVecs
= 4; IsLaneOp
= true; break;
10605 case Intrinsic::aarch64_neon_st2lane
: NewOpc
= AArch64ISD::ST2LANEpost
;
10606 NumVecs
= 2; IsStore
= true; IsLaneOp
= true; break;
10607 case Intrinsic::aarch64_neon_st3lane
: NewOpc
= AArch64ISD::ST3LANEpost
;
10608 NumVecs
= 3; IsStore
= true; IsLaneOp
= true; break;
10609 case Intrinsic::aarch64_neon_st4lane
: NewOpc
= AArch64ISD::ST4LANEpost
;
10610 NumVecs
= 4; IsStore
= true; IsLaneOp
= true; break;
10615 VecTy
= N
->getOperand(2).getValueType();
10617 VecTy
= N
->getValueType(0);
10619 // If the increment is a constant, it must match the memory ref size.
10620 SDValue Inc
= User
->getOperand(User
->getOperand(0) == Addr
? 1 : 0);
10621 if (ConstantSDNode
*CInc
= dyn_cast
<ConstantSDNode
>(Inc
.getNode())) {
10622 uint32_t IncVal
= CInc
->getZExtValue();
10623 unsigned NumBytes
= NumVecs
* VecTy
.getSizeInBits() / 8;
10624 if (IsLaneOp
|| IsDupOp
)
10625 NumBytes
/= VecTy
.getVectorNumElements();
10626 if (IncVal
!= NumBytes
)
10628 Inc
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
10630 SmallVector
<SDValue
, 8> Ops
;
10631 Ops
.push_back(N
->getOperand(0)); // Incoming chain
10632 // Load lane and store have vector list as input.
10633 if (IsLaneOp
|| IsStore
)
10634 for (unsigned i
= 2; i
< AddrOpIdx
; ++i
)
10635 Ops
.push_back(N
->getOperand(i
));
10636 Ops
.push_back(Addr
); // Base register
10637 Ops
.push_back(Inc
);
10641 unsigned NumResultVecs
= (IsStore
? 0 : NumVecs
);
10643 for (n
= 0; n
< NumResultVecs
; ++n
)
10645 Tys
[n
++] = MVT::i64
; // Type of write back register
10646 Tys
[n
] = MVT::Other
; // Type of the chain
10647 SDVTList SDTys
= DAG
.getVTList(makeArrayRef(Tys
, NumResultVecs
+ 2));
10649 MemIntrinsicSDNode
*MemInt
= cast
<MemIntrinsicSDNode
>(N
);
10650 SDValue UpdN
= DAG
.getMemIntrinsicNode(NewOpc
, SDLoc(N
), SDTys
, Ops
,
10651 MemInt
->getMemoryVT(),
10652 MemInt
->getMemOperand());
10654 // Update the uses.
10655 std::vector
<SDValue
> NewResults
;
10656 for (unsigned i
= 0; i
< NumResultVecs
; ++i
) {
10657 NewResults
.push_back(SDValue(UpdN
.getNode(), i
));
10659 NewResults
.push_back(SDValue(UpdN
.getNode(), NumResultVecs
+ 1));
10660 DCI
.CombineTo(N
, NewResults
);
10661 DCI
.CombineTo(User
, SDValue(UpdN
.getNode(), NumResultVecs
));
10668 // Checks to see if the value is the prescribed width and returns information
10669 // about its extension mode.
10671 bool checkValueWidth(SDValue V
, unsigned width
, ISD::LoadExtType
&ExtType
) {
10672 ExtType
= ISD::NON_EXTLOAD
;
10673 switch(V
.getNode()->getOpcode()) {
10677 LoadSDNode
*LoadNode
= cast
<LoadSDNode
>(V
.getNode());
10678 if ((LoadNode
->getMemoryVT() == MVT::i8
&& width
== 8)
10679 || (LoadNode
->getMemoryVT() == MVT::i16
&& width
== 16)) {
10680 ExtType
= LoadNode
->getExtensionType();
10685 case ISD::AssertSext
: {
10686 VTSDNode
*TypeNode
= cast
<VTSDNode
>(V
.getNode()->getOperand(1));
10687 if ((TypeNode
->getVT() == MVT::i8
&& width
== 8)
10688 || (TypeNode
->getVT() == MVT::i16
&& width
== 16)) {
10689 ExtType
= ISD::SEXTLOAD
;
10694 case ISD::AssertZext
: {
10695 VTSDNode
*TypeNode
= cast
<VTSDNode
>(V
.getNode()->getOperand(1));
10696 if ((TypeNode
->getVT() == MVT::i8
&& width
== 8)
10697 || (TypeNode
->getVT() == MVT::i16
&& width
== 16)) {
10698 ExtType
= ISD::ZEXTLOAD
;
10703 case ISD::Constant
:
10704 case ISD::TargetConstant
: {
10705 return std::abs(cast
<ConstantSDNode
>(V
.getNode())->getSExtValue()) <
10706 1LL << (width
- 1);
10713 // This function does a whole lot of voodoo to determine if the tests are
10714 // equivalent without and with a mask. Essentially what happens is that given a
10717 // +-------------+ +-------------+ +-------------+ +-------------+
10718 // | Input | | AddConstant | | CompConstant| | CC |
10719 // +-------------+ +-------------+ +-------------+ +-------------+
10721 // V V | +----------+
10722 // +-------------+ +----+ | |
10723 // | ADD | |0xff| | |
10724 // +-------------+ +----+ | |
10727 // +-------------+ | |
10729 // +-------------+ | |
10738 // The AND node may be safely removed for some combinations of inputs. In
10739 // particular we need to take into account the extension type of the Input,
10740 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10741 // width of the input (this can work for any width inputs, the above graph is
10742 // specific to 8 bits.
10744 // The specific equations were worked out by generating output tables for each
10745 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10746 // problem was simplified by working with 4 bit inputs, which means we only
10747 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10748 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10749 // patterns present in both extensions (0,7). For every distinct set of
10750 // AddConstant and CompConstants bit patterns we can consider the masked and
10751 // unmasked versions to be equivalent if the result of this function is true for
10752 // all 16 distinct bit patterns of for the current extension type of Input (w0).
10755 // and w10, w8, #0x0f
10757 // cset w9, AArch64CC
10759 // cset w11, AArch64CC
10764 // Since the above function shows when the outputs are equivalent it defines
10765 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10766 // would be expensive to run during compiles. The equations below were written
10767 // in a test harness that confirmed they gave equivalent outputs to the above
10768 // for all inputs function, so they can be used determine if the removal is
10771 // isEquivalentMaskless() is the code for testing if the AND can be removed
10772 // factored out of the DAG recognition as the DAG can take several forms.
10774 static bool isEquivalentMaskless(unsigned CC
, unsigned width
,
10775 ISD::LoadExtType ExtType
, int AddConstant
,
10776 int CompConstant
) {
10777 // By being careful about our equations and only writing the in term
10778 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10779 // make them generally applicable to all bit widths.
10780 int MaxUInt
= (1 << width
);
10782 // For the purposes of these comparisons sign extending the type is
10783 // equivalent to zero extending the add and displacing it by half the integer
10784 // width. Provided we are careful and make sure our equations are valid over
10785 // the whole range we can just adjust the input and avoid writing equations
10786 // for sign extended inputs.
10787 if (ExtType
== ISD::SEXTLOAD
)
10788 AddConstant
-= (1 << (width
-1));
10791 case AArch64CC::LE
:
10792 case AArch64CC::GT
:
10793 if ((AddConstant
== 0) ||
10794 (CompConstant
== MaxUInt
- 1 && AddConstant
< 0) ||
10795 (AddConstant
>= 0 && CompConstant
< 0) ||
10796 (AddConstant
<= 0 && CompConstant
<= 0 && CompConstant
< AddConstant
))
10799 case AArch64CC::LT
:
10800 case AArch64CC::GE
:
10801 if ((AddConstant
== 0) ||
10802 (AddConstant
>= 0 && CompConstant
<= 0) ||
10803 (AddConstant
<= 0 && CompConstant
<= 0 && CompConstant
<= AddConstant
))
10806 case AArch64CC::HI
:
10807 case AArch64CC::LS
:
10808 if ((AddConstant
>= 0 && CompConstant
< 0) ||
10809 (AddConstant
<= 0 && CompConstant
>= -1 &&
10810 CompConstant
< AddConstant
+ MaxUInt
))
10813 case AArch64CC::PL
:
10814 case AArch64CC::MI
:
10815 if ((AddConstant
== 0) ||
10816 (AddConstant
> 0 && CompConstant
<= 0) ||
10817 (AddConstant
< 0 && CompConstant
<= AddConstant
))
10820 case AArch64CC::LO
:
10821 case AArch64CC::HS
:
10822 if ((AddConstant
>= 0 && CompConstant
<= 0) ||
10823 (AddConstant
<= 0 && CompConstant
>= 0 &&
10824 CompConstant
<= AddConstant
+ MaxUInt
))
10827 case AArch64CC::EQ
:
10828 case AArch64CC::NE
:
10829 if ((AddConstant
> 0 && CompConstant
< 0) ||
10830 (AddConstant
< 0 && CompConstant
>= 0 &&
10831 CompConstant
< AddConstant
+ MaxUInt
) ||
10832 (AddConstant
>= 0 && CompConstant
>= 0 &&
10833 CompConstant
>= AddConstant
) ||
10834 (AddConstant
<= 0 && CompConstant
< 0 && CompConstant
< AddConstant
))
10837 case AArch64CC::VS
:
10838 case AArch64CC::VC
:
10839 case AArch64CC::AL
:
10840 case AArch64CC::NV
:
10842 case AArch64CC::Invalid
:
10850 SDValue
performCONDCombine(SDNode
*N
,
10851 TargetLowering::DAGCombinerInfo
&DCI
,
10852 SelectionDAG
&DAG
, unsigned CCIndex
,
10853 unsigned CmpIndex
) {
10854 unsigned CC
= cast
<ConstantSDNode
>(N
->getOperand(CCIndex
))->getSExtValue();
10855 SDNode
*SubsNode
= N
->getOperand(CmpIndex
).getNode();
10856 unsigned CondOpcode
= SubsNode
->getOpcode();
10858 if (CondOpcode
!= AArch64ISD::SUBS
)
10861 // There is a SUBS feeding this condition. Is it fed by a mask we can
10864 SDNode
*AndNode
= SubsNode
->getOperand(0).getNode();
10865 unsigned MaskBits
= 0;
10867 if (AndNode
->getOpcode() != ISD::AND
)
10870 if (ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(AndNode
->getOperand(1))) {
10871 uint32_t CNV
= CN
->getZExtValue();
10874 else if (CNV
== 65535)
10881 SDValue AddValue
= AndNode
->getOperand(0);
10883 if (AddValue
.getOpcode() != ISD::ADD
)
10886 // The basic dag structure is correct, grab the inputs and validate them.
10888 SDValue AddInputValue1
= AddValue
.getNode()->getOperand(0);
10889 SDValue AddInputValue2
= AddValue
.getNode()->getOperand(1);
10890 SDValue SubsInputValue
= SubsNode
->getOperand(1);
10892 // The mask is present and the provenance of all the values is a smaller type,
10893 // lets see if the mask is superfluous.
10895 if (!isa
<ConstantSDNode
>(AddInputValue2
.getNode()) ||
10896 !isa
<ConstantSDNode
>(SubsInputValue
.getNode()))
10899 ISD::LoadExtType ExtType
;
10901 if (!checkValueWidth(SubsInputValue
, MaskBits
, ExtType
) ||
10902 !checkValueWidth(AddInputValue2
, MaskBits
, ExtType
) ||
10903 !checkValueWidth(AddInputValue1
, MaskBits
, ExtType
) )
10906 if(!isEquivalentMaskless(CC
, MaskBits
, ExtType
,
10907 cast
<ConstantSDNode
>(AddInputValue2
.getNode())->getSExtValue(),
10908 cast
<ConstantSDNode
>(SubsInputValue
.getNode())->getSExtValue()))
10911 // The AND is not necessary, remove it.
10913 SDVTList VTs
= DAG
.getVTList(SubsNode
->getValueType(0),
10914 SubsNode
->getValueType(1));
10915 SDValue Ops
[] = { AddValue
, SubsNode
->getOperand(1) };
10917 SDValue NewValue
= DAG
.getNode(CondOpcode
, SDLoc(SubsNode
), VTs
, Ops
);
10918 DAG
.ReplaceAllUsesWith(SubsNode
, NewValue
.getNode());
10920 return SDValue(N
, 0);
10923 // Optimize compare with zero and branch.
10924 static SDValue
performBRCONDCombine(SDNode
*N
,
10925 TargetLowering::DAGCombinerInfo
&DCI
,
10926 SelectionDAG
&DAG
) {
10927 MachineFunction
&MF
= DAG
.getMachineFunction();
10928 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
10929 // will not be produced, as they are conditional branch instructions that do
10931 if (MF
.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening
))
10934 if (SDValue NV
= performCONDCombine(N
, DCI
, DAG
, 2, 3))
10936 SDValue Chain
= N
->getOperand(0);
10937 SDValue Dest
= N
->getOperand(1);
10938 SDValue CCVal
= N
->getOperand(2);
10939 SDValue Cmp
= N
->getOperand(3);
10941 assert(isa
<ConstantSDNode
>(CCVal
) && "Expected a ConstantSDNode here!");
10942 unsigned CC
= cast
<ConstantSDNode
>(CCVal
)->getZExtValue();
10943 if (CC
!= AArch64CC::EQ
&& CC
!= AArch64CC::NE
)
10946 unsigned CmpOpc
= Cmp
.getOpcode();
10947 if (CmpOpc
!= AArch64ISD::ADDS
&& CmpOpc
!= AArch64ISD::SUBS
)
10950 // Only attempt folding if there is only one use of the flag and no use of the
10952 if (!Cmp
->hasNUsesOfValue(0, 0) || !Cmp
->hasNUsesOfValue(1, 1))
10955 SDValue LHS
= Cmp
.getOperand(0);
10956 SDValue RHS
= Cmp
.getOperand(1);
10958 assert(LHS
.getValueType() == RHS
.getValueType() &&
10959 "Expected the value type to be the same for both operands!");
10960 if (LHS
.getValueType() != MVT::i32
&& LHS
.getValueType() != MVT::i64
)
10963 if (isNullConstant(LHS
))
10964 std::swap(LHS
, RHS
);
10966 if (!isNullConstant(RHS
))
10969 if (LHS
.getOpcode() == ISD::SHL
|| LHS
.getOpcode() == ISD::SRA
||
10970 LHS
.getOpcode() == ISD::SRL
)
10973 // Fold the compare into the branch instruction.
10975 if (CC
== AArch64CC::EQ
)
10976 BR
= DAG
.getNode(AArch64ISD::CBZ
, SDLoc(N
), MVT::Other
, Chain
, LHS
, Dest
);
10978 BR
= DAG
.getNode(AArch64ISD::CBNZ
, SDLoc(N
), MVT::Other
, Chain
, LHS
, Dest
);
10980 // Do not add new nodes to DAG combiner worklist.
10981 DCI
.CombineTo(N
, BR
, false);
10986 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10987 // as well as whether the test should be inverted. This code is required to
10988 // catch these cases (as opposed to standard dag combines) because
10989 // AArch64ISD::TBZ is matched during legalization.
10990 static SDValue
getTestBitOperand(SDValue Op
, unsigned &Bit
, bool &Invert
,
10991 SelectionDAG
&DAG
) {
10993 if (!Op
->hasOneUse())
10996 // We don't handle undef/constant-fold cases below, as they should have
10997 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11000 // (tbz (trunc x), b) -> (tbz x, b)
11001 // This case is just here to enable more of the below cases to be caught.
11002 if (Op
->getOpcode() == ISD::TRUNCATE
&&
11003 Bit
< Op
->getValueType(0).getSizeInBits()) {
11004 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11007 if (Op
->getNumOperands() != 2)
11010 auto *C
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1));
11014 switch (Op
->getOpcode()) {
11018 // (tbz (and x, m), b) -> (tbz x, b)
11020 if ((C
->getZExtValue() >> Bit
) & 1)
11021 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11024 // (tbz (shl x, c), b) -> (tbz x, b-c)
11026 if (C
->getZExtValue() <= Bit
&&
11027 (Bit
- C
->getZExtValue()) < Op
->getValueType(0).getSizeInBits()) {
11028 Bit
= Bit
- C
->getZExtValue();
11029 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11033 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11035 Bit
= Bit
+ C
->getZExtValue();
11036 if (Bit
>= Op
->getValueType(0).getSizeInBits())
11037 Bit
= Op
->getValueType(0).getSizeInBits() - 1;
11038 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11040 // (tbz (srl x, c), b) -> (tbz x, b+c)
11042 if ((Bit
+ C
->getZExtValue()) < Op
->getValueType(0).getSizeInBits()) {
11043 Bit
= Bit
+ C
->getZExtValue();
11044 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11048 // (tbz (xor x, -1), b) -> (tbnz x, b)
11050 if ((C
->getZExtValue() >> Bit
) & 1)
11052 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11056 // Optimize test single bit zero/non-zero and branch.
11057 static SDValue
performTBZCombine(SDNode
*N
,
11058 TargetLowering::DAGCombinerInfo
&DCI
,
11059 SelectionDAG
&DAG
) {
11060 unsigned Bit
= cast
<ConstantSDNode
>(N
->getOperand(2))->getZExtValue();
11061 bool Invert
= false;
11062 SDValue TestSrc
= N
->getOperand(1);
11063 SDValue NewTestSrc
= getTestBitOperand(TestSrc
, Bit
, Invert
, DAG
);
11065 if (TestSrc
== NewTestSrc
)
11068 unsigned NewOpc
= N
->getOpcode();
11070 if (NewOpc
== AArch64ISD::TBZ
)
11071 NewOpc
= AArch64ISD::TBNZ
;
11073 assert(NewOpc
== AArch64ISD::TBNZ
);
11074 NewOpc
= AArch64ISD::TBZ
;
11079 return DAG
.getNode(NewOpc
, DL
, MVT::Other
, N
->getOperand(0), NewTestSrc
,
11080 DAG
.getConstant(Bit
, DL
, MVT::i64
), N
->getOperand(3));
11083 // vselect (v1i1 setcc) ->
11084 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
11085 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11086 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11088 static SDValue
performVSelectCombine(SDNode
*N
, SelectionDAG
&DAG
) {
11089 SDValue N0
= N
->getOperand(0);
11090 EVT CCVT
= N0
.getValueType();
11092 if (N0
.getOpcode() != ISD::SETCC
|| CCVT
.getVectorNumElements() != 1 ||
11093 CCVT
.getVectorElementType() != MVT::i1
)
11096 EVT ResVT
= N
->getValueType(0);
11097 EVT CmpVT
= N0
.getOperand(0).getValueType();
11098 // Only combine when the result type is of the same size as the compared
11100 if (ResVT
.getSizeInBits() != CmpVT
.getSizeInBits())
11103 SDValue IfTrue
= N
->getOperand(1);
11104 SDValue IfFalse
= N
->getOperand(2);
11106 DAG
.getSetCC(SDLoc(N
), CmpVT
.changeVectorElementTypeToInteger(),
11107 N0
.getOperand(0), N0
.getOperand(1),
11108 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
11109 return DAG
.getNode(ISD::VSELECT
, SDLoc(N
), ResVT
, SetCC
,
11113 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11114 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11115 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11116 /// with a vector one followed by a DUP shuffle on the result.
11117 static SDValue
performSelectCombine(SDNode
*N
,
11118 TargetLowering::DAGCombinerInfo
&DCI
) {
11119 SelectionDAG
&DAG
= DCI
.DAG
;
11120 SDValue N0
= N
->getOperand(0);
11121 EVT ResVT
= N
->getValueType(0);
11123 if (N0
.getOpcode() != ISD::SETCC
)
11126 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11127 // scalar SetCCResultType. We also don't expect vectors, because we assume
11128 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11129 assert((N0
.getValueType() == MVT::i1
|| N0
.getValueType() == MVT::i32
) &&
11130 "Scalar-SETCC feeding SELECT has unexpected result type!");
11132 // If NumMaskElts == 0, the comparison is larger than select result. The
11133 // largest real NEON comparison is 64-bits per lane, which means the result is
11134 // at most 32-bits and an illegal vector. Just bail out for now.
11135 EVT SrcVT
= N0
.getOperand(0).getValueType();
11137 // Don't try to do this optimization when the setcc itself has i1 operands.
11138 // There are no legal vectors of i1, so this would be pointless.
11139 if (SrcVT
== MVT::i1
)
11142 int NumMaskElts
= ResVT
.getSizeInBits() / SrcVT
.getSizeInBits();
11143 if (!ResVT
.isVector() || NumMaskElts
== 0)
11146 SrcVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
, NumMaskElts
);
11147 EVT CCVT
= SrcVT
.changeVectorElementTypeToInteger();
11149 // Also bail out if the vector CCVT isn't the same size as ResVT.
11150 // This can happen if the SETCC operand size doesn't divide the ResVT size
11151 // (e.g., f64 vs v3f32).
11152 if (CCVT
.getSizeInBits() != ResVT
.getSizeInBits())
11155 // Make sure we didn't create illegal types, if we're not supposed to.
11156 assert(DCI
.isBeforeLegalize() ||
11157 DAG
.getTargetLoweringInfo().isTypeLegal(SrcVT
));
11159 // First perform a vector comparison, where lane 0 is the one we're interested
11163 DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, SrcVT
, N0
.getOperand(0));
11165 DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, SrcVT
, N0
.getOperand(1));
11166 SDValue SetCC
= DAG
.getNode(ISD::SETCC
, DL
, CCVT
, LHS
, RHS
, N0
.getOperand(2));
11168 // Now duplicate the comparison mask we want across all other lanes.
11169 SmallVector
<int, 8> DUPMask(CCVT
.getVectorNumElements(), 0);
11170 SDValue Mask
= DAG
.getVectorShuffle(CCVT
, DL
, SetCC
, SetCC
, DUPMask
);
11171 Mask
= DAG
.getNode(ISD::BITCAST
, DL
,
11172 ResVT
.changeVectorElementTypeToInteger(), Mask
);
11174 return DAG
.getSelect(DL
, ResVT
, Mask
, N
->getOperand(1), N
->getOperand(2));
11177 /// Get rid of unnecessary NVCASTs (that don't change the type).
11178 static SDValue
performNVCASTCombine(SDNode
*N
) {
11179 if (N
->getValueType(0) == N
->getOperand(0).getValueType())
11180 return N
->getOperand(0);
11185 // If all users of the globaladdr are of the form (globaladdr + constant), find
11186 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11187 // globaladdr as (globaladdr + constant) - constant.
11188 static SDValue
performGlobalAddressCombine(SDNode
*N
, SelectionDAG
&DAG
,
11189 const AArch64Subtarget
*Subtarget
,
11190 const TargetMachine
&TM
) {
11191 auto *GN
= cast
<GlobalAddressSDNode
>(N
);
11192 if (Subtarget
->ClassifyGlobalReference(GN
->getGlobal(), TM
) !=
11193 AArch64II::MO_NO_FLAG
)
11196 uint64_t MinOffset
= -1ull;
11197 for (SDNode
*N
: GN
->uses()) {
11198 if (N
->getOpcode() != ISD::ADD
)
11200 auto *C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(0));
11202 C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
11205 MinOffset
= std::min(MinOffset
, C
->getZExtValue());
11207 uint64_t Offset
= MinOffset
+ GN
->getOffset();
11209 // Require that the new offset is larger than the existing one. Otherwise, we
11210 // can end up oscillating between two possible DAGs, for example,
11211 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11212 if (Offset
<= uint64_t(GN
->getOffset()))
11215 // Check whether folding this offset is legal. It must not go out of bounds of
11216 // the referenced object to avoid violating the code model, and must be
11217 // smaller than 2^21 because this is the largest offset expressible in all
11220 // This check also prevents us from folding negative offsets, which will end
11221 // up being treated in the same way as large positive ones. They could also
11222 // cause code model violations, and aren't really common enough to matter.
11223 if (Offset
>= (1 << 21))
11226 const GlobalValue
*GV
= GN
->getGlobal();
11227 Type
*T
= GV
->getValueType();
11228 if (!T
->isSized() ||
11229 Offset
> GV
->getParent()->getDataLayout().getTypeAllocSize(T
))
11233 SDValue Result
= DAG
.getGlobalAddress(GV
, DL
, MVT::i64
, Offset
);
11234 return DAG
.getNode(ISD::SUB
, DL
, MVT::i64
, Result
,
11235 DAG
.getConstant(MinOffset
, DL
, MVT::i64
));
11238 SDValue
AArch64TargetLowering::PerformDAGCombine(SDNode
*N
,
11239 DAGCombinerInfo
&DCI
) const {
11240 SelectionDAG
&DAG
= DCI
.DAG
;
11241 switch (N
->getOpcode()) {
11243 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11247 return performAddSubLongCombine(N
, DCI
, DAG
);
11249 return performXorCombine(N
, DAG
, DCI
, Subtarget
);
11251 return performMulCombine(N
, DAG
, DCI
, Subtarget
);
11252 case ISD::SINT_TO_FP
:
11253 case ISD::UINT_TO_FP
:
11254 return performIntToFpCombine(N
, DAG
, Subtarget
);
11255 case ISD::FP_TO_SINT
:
11256 case ISD::FP_TO_UINT
:
11257 return performFpToIntCombine(N
, DAG
, DCI
, Subtarget
);
11259 return performFDivCombine(N
, DAG
, DCI
, Subtarget
);
11261 return performORCombine(N
, DCI
, Subtarget
);
11263 return performSRLCombine(N
, DCI
);
11264 case ISD::INTRINSIC_WO_CHAIN
:
11265 return performIntrinsicCombine(N
, DCI
, Subtarget
);
11266 case ISD::ANY_EXTEND
:
11267 case ISD::ZERO_EXTEND
:
11268 case ISD::SIGN_EXTEND
:
11269 return performExtendCombine(N
, DCI
, DAG
);
11271 return performBitcastCombine(N
, DCI
, DAG
);
11272 case ISD::CONCAT_VECTORS
:
11273 return performConcatVectorsCombine(N
, DCI
, DAG
);
11275 return performSelectCombine(N
, DCI
);
11277 return performVSelectCombine(N
, DCI
.DAG
);
11279 if (performTBISimplification(N
->getOperand(1), DCI
, DAG
))
11280 return SDValue(N
, 0);
11283 return performSTORECombine(N
, DCI
, DAG
, Subtarget
);
11284 case AArch64ISD::BRCOND
:
11285 return performBRCONDCombine(N
, DCI
, DAG
);
11286 case AArch64ISD::TBNZ
:
11287 case AArch64ISD::TBZ
:
11288 return performTBZCombine(N
, DCI
, DAG
);
11289 case AArch64ISD::CSEL
:
11290 return performCONDCombine(N
, DCI
, DAG
, 2, 3);
11291 case AArch64ISD::DUP
:
11292 return performPostLD1Combine(N
, DCI
, false);
11293 case AArch64ISD::NVCAST
:
11294 return performNVCASTCombine(N
);
11295 case ISD::INSERT_VECTOR_ELT
:
11296 return performPostLD1Combine(N
, DCI
, true);
11297 case ISD::INTRINSIC_VOID
:
11298 case ISD::INTRINSIC_W_CHAIN
:
11299 switch (cast
<ConstantSDNode
>(N
->getOperand(1))->getZExtValue()) {
11300 case Intrinsic::aarch64_neon_ld2
:
11301 case Intrinsic::aarch64_neon_ld3
:
11302 case Intrinsic::aarch64_neon_ld4
:
11303 case Intrinsic::aarch64_neon_ld1x2
:
11304 case Intrinsic::aarch64_neon_ld1x3
:
11305 case Intrinsic::aarch64_neon_ld1x4
:
11306 case Intrinsic::aarch64_neon_ld2lane
:
11307 case Intrinsic::aarch64_neon_ld3lane
:
11308 case Intrinsic::aarch64_neon_ld4lane
:
11309 case Intrinsic::aarch64_neon_ld2r
:
11310 case Intrinsic::aarch64_neon_ld3r
:
11311 case Intrinsic::aarch64_neon_ld4r
:
11312 case Intrinsic::aarch64_neon_st2
:
11313 case Intrinsic::aarch64_neon_st3
:
11314 case Intrinsic::aarch64_neon_st4
:
11315 case Intrinsic::aarch64_neon_st1x2
:
11316 case Intrinsic::aarch64_neon_st1x3
:
11317 case Intrinsic::aarch64_neon_st1x4
:
11318 case Intrinsic::aarch64_neon_st2lane
:
11319 case Intrinsic::aarch64_neon_st3lane
:
11320 case Intrinsic::aarch64_neon_st4lane
:
11321 return performNEONPostLDSTCombine(N
, DCI
, DAG
);
11326 case ISD::GlobalAddress
:
11327 return performGlobalAddressCombine(N
, DAG
, Subtarget
, getTargetMachine());
11332 // Check if the return value is used as only a return value, as otherwise
11333 // we can't perform a tail-call. In particular, we need to check for
11334 // target ISD nodes that are returns and any other "odd" constructs
11335 // that the generic analysis code won't necessarily catch.
11336 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode
*N
,
11337 SDValue
&Chain
) const {
11338 if (N
->getNumValues() != 1)
11340 if (!N
->hasNUsesOfValue(1, 0))
11343 SDValue TCChain
= Chain
;
11344 SDNode
*Copy
= *N
->use_begin();
11345 if (Copy
->getOpcode() == ISD::CopyToReg
) {
11346 // If the copy has a glue operand, we conservatively assume it isn't safe to
11347 // perform a tail call.
11348 if (Copy
->getOperand(Copy
->getNumOperands() - 1).getValueType() ==
11351 TCChain
= Copy
->getOperand(0);
11352 } else if (Copy
->getOpcode() != ISD::FP_EXTEND
)
11355 bool HasRet
= false;
11356 for (SDNode
*Node
: Copy
->uses()) {
11357 if (Node
->getOpcode() != AArch64ISD::RET_FLAG
)
11369 // Return whether the an instruction can potentially be optimized to a tail
11370 // call. This will cause the optimizers to attempt to move, or duplicate,
11371 // return instructions to help enable tail call optimizations for this
11373 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst
*CI
) const {
11374 return CI
->isTailCall();
11377 bool AArch64TargetLowering::getIndexedAddressParts(SDNode
*Op
, SDValue
&Base
,
11379 ISD::MemIndexedMode
&AM
,
11381 SelectionDAG
&DAG
) const {
11382 if (Op
->getOpcode() != ISD::ADD
&& Op
->getOpcode() != ISD::SUB
)
11385 Base
= Op
->getOperand(0);
11386 // All of the indexed addressing mode instructions take a signed
11387 // 9 bit immediate offset.
11388 if (ConstantSDNode
*RHS
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1))) {
11389 int64_t RHSC
= RHS
->getSExtValue();
11390 if (Op
->getOpcode() == ISD::SUB
)
11391 RHSC
= -(uint64_t)RHSC
;
11392 if (!isInt
<9>(RHSC
))
11394 IsInc
= (Op
->getOpcode() == ISD::ADD
);
11395 Offset
= Op
->getOperand(1);
11401 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode
*N
, SDValue
&Base
,
11403 ISD::MemIndexedMode
&AM
,
11404 SelectionDAG
&DAG
) const {
11407 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
11408 VT
= LD
->getMemoryVT();
11409 Ptr
= LD
->getBasePtr();
11410 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
11411 VT
= ST
->getMemoryVT();
11412 Ptr
= ST
->getBasePtr();
11417 if (!getIndexedAddressParts(Ptr
.getNode(), Base
, Offset
, AM
, IsInc
, DAG
))
11419 AM
= IsInc
? ISD::PRE_INC
: ISD::PRE_DEC
;
11423 bool AArch64TargetLowering::getPostIndexedAddressParts(
11424 SDNode
*N
, SDNode
*Op
, SDValue
&Base
, SDValue
&Offset
,
11425 ISD::MemIndexedMode
&AM
, SelectionDAG
&DAG
) const {
11428 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
11429 VT
= LD
->getMemoryVT();
11430 Ptr
= LD
->getBasePtr();
11431 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
11432 VT
= ST
->getMemoryVT();
11433 Ptr
= ST
->getBasePtr();
11438 if (!getIndexedAddressParts(Op
, Base
, Offset
, AM
, IsInc
, DAG
))
11440 // Post-indexing updates the base, so it's not a valid transform
11441 // if that's not the same as the load's pointer.
11444 AM
= IsInc
? ISD::POST_INC
: ISD::POST_DEC
;
11448 static void ReplaceBITCASTResults(SDNode
*N
, SmallVectorImpl
<SDValue
> &Results
,
11449 SelectionDAG
&DAG
) {
11451 SDValue Op
= N
->getOperand(0);
11453 if (N
->getValueType(0) != MVT::i16
|| Op
.getValueType() != MVT::f16
)
11457 DAG
.getMachineNode(TargetOpcode::INSERT_SUBREG
, DL
, MVT::f32
,
11458 DAG
.getUNDEF(MVT::i32
), Op
,
11459 DAG
.getTargetConstant(AArch64::hsub
, DL
, MVT::i32
)),
11461 Op
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::i32
, Op
);
11462 Results
.push_back(DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i16
, Op
));
11465 static void ReplaceReductionResults(SDNode
*N
,
11466 SmallVectorImpl
<SDValue
> &Results
,
11467 SelectionDAG
&DAG
, unsigned InterOp
,
11468 unsigned AcrossOp
) {
11472 std::tie(LoVT
, HiVT
) = DAG
.GetSplitDestVTs(N
->getValueType(0));
11473 std::tie(Lo
, Hi
) = DAG
.SplitVectorOperand(N
, 0);
11474 SDValue InterVal
= DAG
.getNode(InterOp
, dl
, LoVT
, Lo
, Hi
);
11475 SDValue SplitVal
= DAG
.getNode(AcrossOp
, dl
, LoVT
, InterVal
);
11476 Results
.push_back(SplitVal
);
11479 static std::pair
<SDValue
, SDValue
> splitInt128(SDValue N
, SelectionDAG
&DAG
) {
11481 SDValue Lo
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i64
, N
);
11482 SDValue Hi
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i64
,
11483 DAG
.getNode(ISD::SRL
, DL
, MVT::i128
, N
,
11484 DAG
.getConstant(64, DL
, MVT::i64
)));
11485 return std::make_pair(Lo
, Hi
);
11488 // Create an even/odd pair of X registers holding integer value V.
11489 static SDValue
createGPRPairNode(SelectionDAG
&DAG
, SDValue V
) {
11490 SDLoc
dl(V
.getNode());
11491 SDValue VLo
= DAG
.getAnyExtOrTrunc(V
, dl
, MVT::i64
);
11492 SDValue VHi
= DAG
.getAnyExtOrTrunc(
11493 DAG
.getNode(ISD::SRL
, dl
, MVT::i128
, V
, DAG
.getConstant(64, dl
, MVT::i64
)),
11495 if (DAG
.getDataLayout().isBigEndian())
11496 std::swap (VLo
, VHi
);
11498 DAG
.getTargetConstant(AArch64::XSeqPairsClassRegClassID
, dl
, MVT::i32
);
11499 SDValue SubReg0
= DAG
.getTargetConstant(AArch64::sube64
, dl
, MVT::i32
);
11500 SDValue SubReg1
= DAG
.getTargetConstant(AArch64::subo64
, dl
, MVT::i32
);
11501 const SDValue Ops
[] = { RegClass
, VLo
, SubReg0
, VHi
, SubReg1
};
11503 DAG
.getMachineNode(TargetOpcode::REG_SEQUENCE
, dl
, MVT::Untyped
, Ops
), 0);
11506 static void ReplaceCMP_SWAP_128Results(SDNode
*N
,
11507 SmallVectorImpl
<SDValue
> &Results
,
11509 const AArch64Subtarget
*Subtarget
) {
11510 assert(N
->getValueType(0) == MVT::i128
&&
11511 "AtomicCmpSwap on types less than 128 should be legal");
11513 if (Subtarget
->hasLSE()) {
11514 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11515 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11517 createGPRPairNode(DAG
, N
->getOperand(2)), // Compare value
11518 createGPRPairNode(DAG
, N
->getOperand(3)), // Store value
11519 N
->getOperand(1), // Ptr
11520 N
->getOperand(0), // Chain in
11523 MachineMemOperand
*MemOp
= cast
<MemSDNode
>(N
)->getMemOperand();
11526 switch (MemOp
->getOrdering()) {
11527 case AtomicOrdering::Monotonic
:
11528 Opcode
= AArch64::CASPX
;
11530 case AtomicOrdering::Acquire
:
11531 Opcode
= AArch64::CASPAX
;
11533 case AtomicOrdering::Release
:
11534 Opcode
= AArch64::CASPLX
;
11536 case AtomicOrdering::AcquireRelease
:
11537 case AtomicOrdering::SequentiallyConsistent
:
11538 Opcode
= AArch64::CASPALX
;
11541 llvm_unreachable("Unexpected ordering!");
11544 MachineSDNode
*CmpSwap
= DAG
.getMachineNode(
11545 Opcode
, SDLoc(N
), DAG
.getVTList(MVT::Untyped
, MVT::Other
), Ops
);
11546 DAG
.setNodeMemRefs(CmpSwap
, {MemOp
});
11548 unsigned SubReg1
= AArch64::sube64
, SubReg2
= AArch64::subo64
;
11549 if (DAG
.getDataLayout().isBigEndian())
11550 std::swap(SubReg1
, SubReg2
);
11551 Results
.push_back(DAG
.getTargetExtractSubreg(SubReg1
, SDLoc(N
), MVT::i64
,
11552 SDValue(CmpSwap
, 0)));
11553 Results
.push_back(DAG
.getTargetExtractSubreg(SubReg2
, SDLoc(N
), MVT::i64
,
11554 SDValue(CmpSwap
, 0)));
11555 Results
.push_back(SDValue(CmpSwap
, 1)); // Chain out
11559 auto Desired
= splitInt128(N
->getOperand(2), DAG
);
11560 auto New
= splitInt128(N
->getOperand(3), DAG
);
11561 SDValue Ops
[] = {N
->getOperand(1), Desired
.first
, Desired
.second
,
11562 New
.first
, New
.second
, N
->getOperand(0)};
11563 SDNode
*CmpSwap
= DAG
.getMachineNode(
11564 AArch64::CMP_SWAP_128
, SDLoc(N
),
11565 DAG
.getVTList(MVT::i64
, MVT::i64
, MVT::i32
, MVT::Other
), Ops
);
11567 MachineMemOperand
*MemOp
= cast
<MemSDNode
>(N
)->getMemOperand();
11568 DAG
.setNodeMemRefs(cast
<MachineSDNode
>(CmpSwap
), {MemOp
});
11570 Results
.push_back(SDValue(CmpSwap
, 0));
11571 Results
.push_back(SDValue(CmpSwap
, 1));
11572 Results
.push_back(SDValue(CmpSwap
, 3));
11575 void AArch64TargetLowering::ReplaceNodeResults(
11576 SDNode
*N
, SmallVectorImpl
<SDValue
> &Results
, SelectionDAG
&DAG
) const {
11577 switch (N
->getOpcode()) {
11579 llvm_unreachable("Don't know how to custom expand this");
11581 ReplaceBITCASTResults(N
, Results
, DAG
);
11583 case ISD::VECREDUCE_ADD
:
11584 case ISD::VECREDUCE_SMAX
:
11585 case ISD::VECREDUCE_SMIN
:
11586 case ISD::VECREDUCE_UMAX
:
11587 case ISD::VECREDUCE_UMIN
:
11588 Results
.push_back(LowerVECREDUCE(SDValue(N
, 0), DAG
));
11591 case AArch64ISD::SADDV
:
11592 ReplaceReductionResults(N
, Results
, DAG
, ISD::ADD
, AArch64ISD::SADDV
);
11594 case AArch64ISD::UADDV
:
11595 ReplaceReductionResults(N
, Results
, DAG
, ISD::ADD
, AArch64ISD::UADDV
);
11597 case AArch64ISD::SMINV
:
11598 ReplaceReductionResults(N
, Results
, DAG
, ISD::SMIN
, AArch64ISD::SMINV
);
11600 case AArch64ISD::UMINV
:
11601 ReplaceReductionResults(N
, Results
, DAG
, ISD::UMIN
, AArch64ISD::UMINV
);
11603 case AArch64ISD::SMAXV
:
11604 ReplaceReductionResults(N
, Results
, DAG
, ISD::SMAX
, AArch64ISD::SMAXV
);
11606 case AArch64ISD::UMAXV
:
11607 ReplaceReductionResults(N
, Results
, DAG
, ISD::UMAX
, AArch64ISD::UMAXV
);
11609 case ISD::FP_TO_UINT
:
11610 case ISD::FP_TO_SINT
:
11611 assert(N
->getValueType(0) == MVT::i128
&& "unexpected illegal conversion");
11612 // Let normal code take care of it by not adding anything to Results.
11614 case ISD::ATOMIC_CMP_SWAP
:
11615 ReplaceCMP_SWAP_128Results(N
, Results
, DAG
, Subtarget
);
11620 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11621 if (Subtarget
->isTargetAndroid() || Subtarget
->isTargetFuchsia())
11622 return TargetLowering::useLoadStackGuardNode();
11626 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11627 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11628 // reciprocal if there are three or more FDIVs.
11632 TargetLoweringBase::LegalizeTypeAction
11633 AArch64TargetLowering::getPreferredVectorAction(MVT VT
) const {
11634 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11635 // v4i16, v2i32 instead of to promote.
11636 if (VT
== MVT::v1i8
|| VT
== MVT::v1i16
|| VT
== MVT::v1i32
||
11638 return TypeWidenVector
;
11640 return TargetLoweringBase::getPreferredVectorAction(VT
);
11643 // Loads and stores less than 128-bits are already atomic; ones above that
11644 // are doomed anyway, so defer to the default libcall and blame the OS when
11645 // things go wrong.
11646 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst
*SI
) const {
11647 unsigned Size
= SI
->getValueOperand()->getType()->getPrimitiveSizeInBits();
11648 return Size
== 128;
11651 // Loads and stores less than 128-bits are already atomic; ones above that
11652 // are doomed anyway, so defer to the default libcall and blame the OS when
11653 // things go wrong.
11654 TargetLowering::AtomicExpansionKind
11655 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst
*LI
) const {
11656 unsigned Size
= LI
->getType()->getPrimitiveSizeInBits();
11657 return Size
== 128 ? AtomicExpansionKind::LLSC
: AtomicExpansionKind::None
;
11660 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11661 TargetLowering::AtomicExpansionKind
11662 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst
*AI
) const {
11663 if (AI
->isFloatingPointOperation())
11664 return AtomicExpansionKind::CmpXChg
;
11666 unsigned Size
= AI
->getType()->getPrimitiveSizeInBits();
11667 if (Size
> 128) return AtomicExpansionKind::None
;
11668 // Nand not supported in LSE.
11669 if (AI
->getOperation() == AtomicRMWInst::Nand
) return AtomicExpansionKind::LLSC
;
11670 // Leave 128 bits to LLSC.
11671 return (Subtarget
->hasLSE() && Size
< 128) ? AtomicExpansionKind::None
: AtomicExpansionKind::LLSC
;
11674 TargetLowering::AtomicExpansionKind
11675 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11676 AtomicCmpXchgInst
*AI
) const {
11677 // If subtarget has LSE, leave cmpxchg intact for codegen.
11678 if (Subtarget
->hasLSE())
11679 return AtomicExpansionKind::None
;
11680 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11681 // implement cmpxchg without spilling. If the address being exchanged is also
11682 // on the stack and close enough to the spill slot, this can lead to a
11683 // situation where the monitor always gets cleared and the atomic operation
11684 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11685 if (getTargetMachine().getOptLevel() == 0)
11686 return AtomicExpansionKind::None
;
11687 return AtomicExpansionKind::LLSC
;
11690 Value
*AArch64TargetLowering::emitLoadLinked(IRBuilder
<> &Builder
, Value
*Addr
,
11691 AtomicOrdering Ord
) const {
11692 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11693 Type
*ValTy
= cast
<PointerType
>(Addr
->getType())->getElementType();
11694 bool IsAcquire
= isAcquireOrStronger(Ord
);
11696 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11697 // intrinsic must return {i64, i64} and we have to recombine them into a
11698 // single i128 here.
11699 if (ValTy
->getPrimitiveSizeInBits() == 128) {
11700 Intrinsic::ID Int
=
11701 IsAcquire
? Intrinsic::aarch64_ldaxp
: Intrinsic::aarch64_ldxp
;
11702 Function
*Ldxr
= Intrinsic::getDeclaration(M
, Int
);
11704 Addr
= Builder
.CreateBitCast(Addr
, Type::getInt8PtrTy(M
->getContext()));
11705 Value
*LoHi
= Builder
.CreateCall(Ldxr
, Addr
, "lohi");
11707 Value
*Lo
= Builder
.CreateExtractValue(LoHi
, 0, "lo");
11708 Value
*Hi
= Builder
.CreateExtractValue(LoHi
, 1, "hi");
11709 Lo
= Builder
.CreateZExt(Lo
, ValTy
, "lo64");
11710 Hi
= Builder
.CreateZExt(Hi
, ValTy
, "hi64");
11711 return Builder
.CreateOr(
11712 Lo
, Builder
.CreateShl(Hi
, ConstantInt::get(ValTy
, 64)), "val64");
11715 Type
*Tys
[] = { Addr
->getType() };
11716 Intrinsic::ID Int
=
11717 IsAcquire
? Intrinsic::aarch64_ldaxr
: Intrinsic::aarch64_ldxr
;
11718 Function
*Ldxr
= Intrinsic::getDeclaration(M
, Int
, Tys
);
11720 Type
*EltTy
= cast
<PointerType
>(Addr
->getType())->getElementType();
11722 const DataLayout
&DL
= M
->getDataLayout();
11723 IntegerType
*IntEltTy
= Builder
.getIntNTy(DL
.getTypeSizeInBits(EltTy
));
11724 Value
*Trunc
= Builder
.CreateTrunc(Builder
.CreateCall(Ldxr
, Addr
), IntEltTy
);
11726 return Builder
.CreateBitCast(Trunc
, EltTy
);
11729 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11730 IRBuilder
<> &Builder
) const {
11731 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11732 Builder
.CreateCall(Intrinsic::getDeclaration(M
, Intrinsic::aarch64_clrex
));
11735 Value
*AArch64TargetLowering::emitStoreConditional(IRBuilder
<> &Builder
,
11736 Value
*Val
, Value
*Addr
,
11737 AtomicOrdering Ord
) const {
11738 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11739 bool IsRelease
= isReleaseOrStronger(Ord
);
11741 // Since the intrinsics must have legal type, the i128 intrinsics take two
11742 // parameters: "i64, i64". We must marshal Val into the appropriate form
11743 // before the call.
11744 if (Val
->getType()->getPrimitiveSizeInBits() == 128) {
11745 Intrinsic::ID Int
=
11746 IsRelease
? Intrinsic::aarch64_stlxp
: Intrinsic::aarch64_stxp
;
11747 Function
*Stxr
= Intrinsic::getDeclaration(M
, Int
);
11748 Type
*Int64Ty
= Type::getInt64Ty(M
->getContext());
11750 Value
*Lo
= Builder
.CreateTrunc(Val
, Int64Ty
, "lo");
11751 Value
*Hi
= Builder
.CreateTrunc(Builder
.CreateLShr(Val
, 64), Int64Ty
, "hi");
11752 Addr
= Builder
.CreateBitCast(Addr
, Type::getInt8PtrTy(M
->getContext()));
11753 return Builder
.CreateCall(Stxr
, {Lo
, Hi
, Addr
});
11756 Intrinsic::ID Int
=
11757 IsRelease
? Intrinsic::aarch64_stlxr
: Intrinsic::aarch64_stxr
;
11758 Type
*Tys
[] = { Addr
->getType() };
11759 Function
*Stxr
= Intrinsic::getDeclaration(M
, Int
, Tys
);
11761 const DataLayout
&DL
= M
->getDataLayout();
11762 IntegerType
*IntValTy
= Builder
.getIntNTy(DL
.getTypeSizeInBits(Val
->getType()));
11763 Val
= Builder
.CreateBitCast(Val
, IntValTy
);
11765 return Builder
.CreateCall(Stxr
,
11766 {Builder
.CreateZExtOrBitCast(
11767 Val
, Stxr
->getFunctionType()->getParamType(0)),
11771 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11772 Type
*Ty
, CallingConv::ID CallConv
, bool isVarArg
) const {
11773 return Ty
->isArrayTy();
11776 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext
&,
11781 static Value
*UseTlsOffset(IRBuilder
<> &IRB
, unsigned Offset
) {
11782 Module
*M
= IRB
.GetInsertBlock()->getParent()->getParent();
11783 Function
*ThreadPointerFunc
=
11784 Intrinsic::getDeclaration(M
, Intrinsic::thread_pointer
);
11785 return IRB
.CreatePointerCast(
11786 IRB
.CreateConstGEP1_32(IRB
.getInt8Ty(), IRB
.CreateCall(ThreadPointerFunc
),
11788 IRB
.getInt8PtrTy()->getPointerTo(0));
11791 Value
*AArch64TargetLowering::getIRStackGuard(IRBuilder
<> &IRB
) const {
11792 // Android provides a fixed TLS slot for the stack cookie. See the definition
11793 // of TLS_SLOT_STACK_GUARD in
11794 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11795 if (Subtarget
->isTargetAndroid())
11796 return UseTlsOffset(IRB
, 0x28);
11798 // Fuchsia is similar.
11799 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
11800 if (Subtarget
->isTargetFuchsia())
11801 return UseTlsOffset(IRB
, -0x10);
11803 return TargetLowering::getIRStackGuard(IRB
);
11806 void AArch64TargetLowering::insertSSPDeclarations(Module
&M
) const {
11807 // MSVC CRT provides functionalities for stack protection.
11808 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment()) {
11809 // MSVC CRT has a global variable holding security cookie.
11810 M
.getOrInsertGlobal("__security_cookie",
11811 Type::getInt8PtrTy(M
.getContext()));
11813 // MSVC CRT has a function to validate security cookie.
11814 FunctionCallee SecurityCheckCookie
= M
.getOrInsertFunction(
11815 "__security_check_cookie", Type::getVoidTy(M
.getContext()),
11816 Type::getInt8PtrTy(M
.getContext()));
11817 if (Function
*F
= dyn_cast
<Function
>(SecurityCheckCookie
.getCallee())) {
11818 F
->setCallingConv(CallingConv::Win64
);
11819 F
->addAttribute(1, Attribute::AttrKind::InReg
);
11823 TargetLowering::insertSSPDeclarations(M
);
11826 Value
*AArch64TargetLowering::getSDagStackGuard(const Module
&M
) const {
11827 // MSVC CRT has a global variable holding security cookie.
11828 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment())
11829 return M
.getGlobalVariable("__security_cookie");
11830 return TargetLowering::getSDagStackGuard(M
);
11833 Function
*AArch64TargetLowering::getSSPStackGuardCheck(const Module
&M
) const {
11834 // MSVC CRT has a function to validate security cookie.
11835 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment())
11836 return M
.getFunction("__security_check_cookie");
11837 return TargetLowering::getSSPStackGuardCheck(M
);
11840 Value
*AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder
<> &IRB
) const {
11841 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11842 // definition of TLS_SLOT_SAFESTACK in
11843 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11844 if (Subtarget
->isTargetAndroid())
11845 return UseTlsOffset(IRB
, 0x48);
11847 // Fuchsia is similar.
11848 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
11849 if (Subtarget
->isTargetFuchsia())
11850 return UseTlsOffset(IRB
, -0x8);
11852 return TargetLowering::getSafeStackPointerLocation(IRB
);
11855 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11856 const Instruction
&AndI
) const {
11857 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11858 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11859 // may be beneficial to sink in other cases, but we would have to check that
11860 // the cmp would not get folded into the br to form a cbz for these to be
11862 ConstantInt
* Mask
= dyn_cast
<ConstantInt
>(AndI
.getOperand(1));
11865 return Mask
->getValue().isPowerOf2();
11868 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock
*Entry
) const {
11869 // Update IsSplitCSR in AArch64unctionInfo.
11870 AArch64FunctionInfo
*AFI
= Entry
->getParent()->getInfo
<AArch64FunctionInfo
>();
11871 AFI
->setIsSplitCSR(true);
11874 void AArch64TargetLowering::insertCopiesSplitCSR(
11875 MachineBasicBlock
*Entry
,
11876 const SmallVectorImpl
<MachineBasicBlock
*> &Exits
) const {
11877 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
11878 const MCPhysReg
*IStart
= TRI
->getCalleeSavedRegsViaCopy(Entry
->getParent());
11882 const TargetInstrInfo
*TII
= Subtarget
->getInstrInfo();
11883 MachineRegisterInfo
*MRI
= &Entry
->getParent()->getRegInfo();
11884 MachineBasicBlock::iterator MBBI
= Entry
->begin();
11885 for (const MCPhysReg
*I
= IStart
; *I
; ++I
) {
11886 const TargetRegisterClass
*RC
= nullptr;
11887 if (AArch64::GPR64RegClass
.contains(*I
))
11888 RC
= &AArch64::GPR64RegClass
;
11889 else if (AArch64::FPR64RegClass
.contains(*I
))
11890 RC
= &AArch64::FPR64RegClass
;
11892 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11894 unsigned NewVR
= MRI
->createVirtualRegister(RC
);
11895 // Create copy from CSR to a virtual register.
11896 // FIXME: this currently does not emit CFI pseudo-instructions, it works
11897 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11898 // nounwind. If we want to generalize this later, we may need to emit
11899 // CFI pseudo-instructions.
11900 assert(Entry
->getParent()->getFunction().hasFnAttribute(
11901 Attribute::NoUnwind
) &&
11902 "Function should be nounwind in insertCopiesSplitCSR!");
11903 Entry
->addLiveIn(*I
);
11904 BuildMI(*Entry
, MBBI
, DebugLoc(), TII
->get(TargetOpcode::COPY
), NewVR
)
11907 // Insert the copy-back instructions right before the terminator.
11908 for (auto *Exit
: Exits
)
11909 BuildMI(*Exit
, Exit
->getFirstTerminator(), DebugLoc(),
11910 TII
->get(TargetOpcode::COPY
), *I
)
11915 bool AArch64TargetLowering::isIntDivCheap(EVT VT
, AttributeList Attr
) const {
11916 // Integer division on AArch64 is expensive. However, when aggressively
11917 // optimizing for code size, we prefer to use a div instruction, as it is
11918 // usually smaller than the alternative sequence.
11919 // The exception to this is vector division. Since AArch64 doesn't have vector
11920 // integer division, leaving the division as-is is a loss even in terms of
11921 // size, because it will have to be scalarized, while the alternative code
11922 // sequence can be performed in vector form.
11924 Attr
.hasAttribute(AttributeList::FunctionIndex
, Attribute::MinSize
);
11925 return OptSize
&& !VT
.isVector();
11928 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT
) const {
11929 return Subtarget
->hasAggressiveFMA() && VT
.isFloatingPoint();
11933 AArch64TargetLowering::getVaListSizeInBits(const DataLayout
&DL
) const {
11934 if (Subtarget
->isTargetDarwin() || Subtarget
->isTargetWindows())
11935 return getPointerTy(DL
).getSizeInBits();
11937 return 3 * getPointerTy(DL
).getSizeInBits() + 2 * 32;
11940 void AArch64TargetLowering::finalizeLowering(MachineFunction
&MF
) const {
11941 MF
.getFrameInfo().computeMaxCallFrameSize(MF
);
11942 TargetLoweringBase::finalizeLowering(MF
);
11945 // Unlike X86, we let frame lowering assign offsets to all catch objects.
11946 bool AArch64TargetLowering::needsFixedCatchObjects() const {