1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AArch64TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "AArch64ISelLowering.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64PerfectShuffle.h"
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "AArch64TargetObjectFile.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetOptions.h"
36 #define DEBUG_TYPE "aarch64-lower"
38 STATISTIC(NumTailCalls, "Number of tail calls");
39 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
46 static cl::opt<AlignMode>
47 Align(cl::desc("Load/store alignment support"),
48 cl::Hidden, cl::init(NoStrictAlign),
50 clEnumValN(StrictAlign, "aarch64-strict-align",
51 "Disallow all unaligned memory accesses"),
52 clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
53 "Allow unaligned memory accesses"),
56 // Place holder until extr generation is tested fully.
58 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
59 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
63 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
64 cl::desc("Allow AArch64 SLI/SRI formation"),
67 //===----------------------------------------------------------------------===//
68 // AArch64 Lowering public interface.
69 //===----------------------------------------------------------------------===//
70 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
71 if (TT.isOSBinFormatMachO())
72 return new AArch64_MachoTargetObjectFile();
74 return new AArch64_ELFTargetObjectFile();
77 AArch64TargetLowering::AArch64TargetLowering(TargetMachine &TM)
78 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
79 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
81 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
82 // we have to make something up. Arbitrarily, choose ZeroOrOne.
83 setBooleanContents(ZeroOrOneBooleanContent);
84 // When comparing vectors the result sets the different elements in the
85 // vector to all-one or all-zero.
86 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88 // Set up the register classes.
89 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
90 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
92 if (Subtarget->hasFPARMv8()) {
93 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
94 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
95 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
96 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
99 if (Subtarget->hasNEON()) {
100 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
101 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
102 // Someone set us up the NEON.
103 addDRTypeForNEON(MVT::v2f32);
104 addDRTypeForNEON(MVT::v8i8);
105 addDRTypeForNEON(MVT::v4i16);
106 addDRTypeForNEON(MVT::v2i32);
107 addDRTypeForNEON(MVT::v1i64);
108 addDRTypeForNEON(MVT::v1f64);
110 addQRTypeForNEON(MVT::v4f32);
111 addQRTypeForNEON(MVT::v2f64);
112 addQRTypeForNEON(MVT::v16i8);
113 addQRTypeForNEON(MVT::v8i16);
114 addQRTypeForNEON(MVT::v4i32);
115 addQRTypeForNEON(MVT::v2i64);
118 // Compute derived properties from the register classes
119 computeRegisterProperties();
121 // Provide all sorts of operation actions
122 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
123 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
124 setOperationAction(ISD::SETCC, MVT::i32, Custom);
125 setOperationAction(ISD::SETCC, MVT::i64, Custom);
126 setOperationAction(ISD::SETCC, MVT::f32, Custom);
127 setOperationAction(ISD::SETCC, MVT::f64, Custom);
128 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
129 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
130 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
131 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
132 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
133 setOperationAction(ISD::SELECT, MVT::i32, Custom);
134 setOperationAction(ISD::SELECT, MVT::i64, Custom);
135 setOperationAction(ISD::SELECT, MVT::f32, Custom);
136 setOperationAction(ISD::SELECT, MVT::f64, Custom);
137 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
138 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
139 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
140 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
141 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
142 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
144 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
145 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
146 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
148 setOperationAction(ISD::FREM, MVT::f32, Expand);
149 setOperationAction(ISD::FREM, MVT::f64, Expand);
150 setOperationAction(ISD::FREM, MVT::f80, Expand);
152 // Custom lowering hooks are needed for XOR
153 // to fold it into CSINC/CSINV.
154 setOperationAction(ISD::XOR, MVT::i32, Custom);
155 setOperationAction(ISD::XOR, MVT::i64, Custom);
157 // Virtually no operation on f128 is legal, but LLVM can't expand them when
158 // there's a valid register class, so we need custom operations in most cases.
159 setOperationAction(ISD::FABS, MVT::f128, Expand);
160 setOperationAction(ISD::FADD, MVT::f128, Custom);
161 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
162 setOperationAction(ISD::FCOS, MVT::f128, Expand);
163 setOperationAction(ISD::FDIV, MVT::f128, Custom);
164 setOperationAction(ISD::FMA, MVT::f128, Expand);
165 setOperationAction(ISD::FMUL, MVT::f128, Custom);
166 setOperationAction(ISD::FNEG, MVT::f128, Expand);
167 setOperationAction(ISD::FPOW, MVT::f128, Expand);
168 setOperationAction(ISD::FREM, MVT::f128, Expand);
169 setOperationAction(ISD::FRINT, MVT::f128, Expand);
170 setOperationAction(ISD::FSIN, MVT::f128, Expand);
171 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
172 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
173 setOperationAction(ISD::FSUB, MVT::f128, Custom);
174 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
175 setOperationAction(ISD::SETCC, MVT::f128, Custom);
176 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
177 setOperationAction(ISD::SELECT, MVT::f128, Custom);
178 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
179 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
181 // Lowering for many of the conversions is actually specified by the non-f128
182 // type. The LowerXXX function will be trivial when f128 isn't involved.
183 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
184 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
185 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
186 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
187 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
188 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
189 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
190 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
191 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
192 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
193 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
194 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
195 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
196 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
198 // Variable arguments.
199 setOperationAction(ISD::VASTART, MVT::Other, Custom);
200 setOperationAction(ISD::VAARG, MVT::Other, Custom);
201 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
202 setOperationAction(ISD::VAEND, MVT::Other, Expand);
204 // Variable-sized objects.
205 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
206 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
207 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
209 // Exception handling.
210 // FIXME: These are guesses. Has this been defined yet?
211 setExceptionPointerRegister(AArch64::X0);
212 setExceptionSelectorRegister(AArch64::X1);
214 // Constant pool entries
215 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
218 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
220 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
221 setOperationAction(ISD::ADDC, MVT::i32, Custom);
222 setOperationAction(ISD::ADDE, MVT::i32, Custom);
223 setOperationAction(ISD::SUBC, MVT::i32, Custom);
224 setOperationAction(ISD::SUBE, MVT::i32, Custom);
225 setOperationAction(ISD::ADDC, MVT::i64, Custom);
226 setOperationAction(ISD::ADDE, MVT::i64, Custom);
227 setOperationAction(ISD::SUBC, MVT::i64, Custom);
228 setOperationAction(ISD::SUBE, MVT::i64, Custom);
230 // AArch64 lacks both left-rotate and popcount instructions.
231 setOperationAction(ISD::ROTL, MVT::i32, Expand);
232 setOperationAction(ISD::ROTL, MVT::i64, Expand);
234 // AArch64 doesn't have {U|S}MUL_LOHI.
235 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
236 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
239 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
240 // counterparts, which AArch64 supports directly.
241 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
242 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
243 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
244 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
246 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
247 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
249 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
250 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
251 setOperationAction(ISD::SREM, MVT::i32, Expand);
252 setOperationAction(ISD::SREM, MVT::i64, Expand);
253 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
254 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
255 setOperationAction(ISD::UREM, MVT::i32, Expand);
256 setOperationAction(ISD::UREM, MVT::i64, Expand);
258 // Custom lower Add/Sub/Mul with overflow.
259 setOperationAction(ISD::SADDO, MVT::i32, Custom);
260 setOperationAction(ISD::SADDO, MVT::i64, Custom);
261 setOperationAction(ISD::UADDO, MVT::i32, Custom);
262 setOperationAction(ISD::UADDO, MVT::i64, Custom);
263 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
264 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
265 setOperationAction(ISD::USUBO, MVT::i32, Custom);
266 setOperationAction(ISD::USUBO, MVT::i64, Custom);
267 setOperationAction(ISD::SMULO, MVT::i32, Custom);
268 setOperationAction(ISD::SMULO, MVT::i64, Custom);
269 setOperationAction(ISD::UMULO, MVT::i32, Custom);
270 setOperationAction(ISD::UMULO, MVT::i64, Custom);
272 setOperationAction(ISD::FSIN, MVT::f32, Expand);
273 setOperationAction(ISD::FSIN, MVT::f64, Expand);
274 setOperationAction(ISD::FCOS, MVT::f32, Expand);
275 setOperationAction(ISD::FCOS, MVT::f64, Expand);
276 setOperationAction(ISD::FPOW, MVT::f32, Expand);
277 setOperationAction(ISD::FPOW, MVT::f64, Expand);
278 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
279 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
281 // f16 is storage-only, so we promote operations to f32 if we know this is
282 // valid, and ignore them otherwise. The operations not mentioned here will
283 // fail to select, but this is not a major problem as no source language
284 // should be emitting native f16 operations yet.
285 setOperationAction(ISD::FADD, MVT::f16, Promote);
286 setOperationAction(ISD::FDIV, MVT::f16, Promote);
287 setOperationAction(ISD::FMUL, MVT::f16, Promote);
288 setOperationAction(ISD::FSUB, MVT::f16, Promote);
290 // AArch64 has implementations of a lot of rounding-like FP operations.
291 static MVT RoundingTypes[] = { MVT::f32, MVT::f64};
292 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
293 MVT Ty = RoundingTypes[I];
294 setOperationAction(ISD::FFLOOR, Ty, Legal);
295 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
296 setOperationAction(ISD::FCEIL, Ty, Legal);
297 setOperationAction(ISD::FRINT, Ty, Legal);
298 setOperationAction(ISD::FTRUNC, Ty, Legal);
299 setOperationAction(ISD::FROUND, Ty, Legal);
302 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
304 if (Subtarget->isTargetMachO()) {
305 // For iOS, we don't want to the normal expansion of a libcall to
306 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
308 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
309 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
311 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
312 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
315 // AArch64 does not have floating-point extending loads, i1 sign-extending
316 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
317 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
318 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
319 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
320 setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
321 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
322 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
323 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
324 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
325 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
326 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
327 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
328 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
330 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
331 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
333 // Indexed loads and stores are supported.
334 for (unsigned im = (unsigned)ISD::PRE_INC;
335 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
336 setIndexedLoadAction(im, MVT::i8, Legal);
337 setIndexedLoadAction(im, MVT::i16, Legal);
338 setIndexedLoadAction(im, MVT::i32, Legal);
339 setIndexedLoadAction(im, MVT::i64, Legal);
340 setIndexedLoadAction(im, MVT::f64, Legal);
341 setIndexedLoadAction(im, MVT::f32, Legal);
342 setIndexedStoreAction(im, MVT::i8, Legal);
343 setIndexedStoreAction(im, MVT::i16, Legal);
344 setIndexedStoreAction(im, MVT::i32, Legal);
345 setIndexedStoreAction(im, MVT::i64, Legal);
346 setIndexedStoreAction(im, MVT::f64, Legal);
347 setIndexedStoreAction(im, MVT::f32, Legal);
351 setOperationAction(ISD::TRAP, MVT::Other, Legal);
353 // We combine OR nodes for bitfield operations.
354 setTargetDAGCombine(ISD::OR);
356 // Vector add and sub nodes may conceal a high-half opportunity.
357 // Also, try to fold ADD into CSINC/CSINV..
358 setTargetDAGCombine(ISD::ADD);
359 setTargetDAGCombine(ISD::SUB);
361 setTargetDAGCombine(ISD::XOR);
362 setTargetDAGCombine(ISD::SINT_TO_FP);
363 setTargetDAGCombine(ISD::UINT_TO_FP);
365 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
367 setTargetDAGCombine(ISD::ANY_EXTEND);
368 setTargetDAGCombine(ISD::ZERO_EXTEND);
369 setTargetDAGCombine(ISD::SIGN_EXTEND);
370 setTargetDAGCombine(ISD::BITCAST);
371 setTargetDAGCombine(ISD::CONCAT_VECTORS);
372 setTargetDAGCombine(ISD::STORE);
374 setTargetDAGCombine(ISD::MUL);
376 setTargetDAGCombine(ISD::SELECT);
377 setTargetDAGCombine(ISD::VSELECT);
379 setTargetDAGCombine(ISD::INTRINSIC_VOID);
380 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
381 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
383 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
384 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
385 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
387 setStackPointerRegisterToSaveRestore(AArch64::SP);
389 setSchedulingPreference(Sched::Hybrid);
392 MaskAndBranchFoldingIsLegal = true;
394 setMinFunctionAlignment(2);
396 RequireStrictAlign = (Align == StrictAlign);
398 setHasExtractBitsInsn(true);
400 if (Subtarget->hasNEON()) {
401 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
402 // silliness like this:
403 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
404 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
405 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
406 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
407 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
408 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
409 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
410 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
411 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
412 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
413 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
414 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
415 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
416 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
417 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
418 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
419 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
420 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
421 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
422 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
423 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
424 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
425 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
426 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
427 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
429 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
430 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
431 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
432 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
433 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
435 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
437 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
438 // elements smaller than i32, so promote the input to i32 first.
439 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
440 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
441 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
442 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
443 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
444 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
445 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
446 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
447 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
449 // AArch64 doesn't have MUL.2d:
450 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
451 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
452 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
453 // Likewise, narrowing and extending vector loads/stores aren't handled
455 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
456 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
458 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
461 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
462 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
463 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
464 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
466 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
468 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
469 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
470 setTruncStoreAction((MVT::SimpleValueType)VT,
471 (MVT::SimpleValueType)InnerVT, Expand);
472 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
473 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
474 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
477 // AArch64 has implementations of a lot of rounding-like FP operations.
478 static MVT RoundingVecTypes[] = {MVT::v2f32, MVT::v4f32, MVT::v2f64 };
479 for (unsigned I = 0; I < array_lengthof(RoundingVecTypes); ++I) {
480 MVT Ty = RoundingVecTypes[I];
481 setOperationAction(ISD::FFLOOR, Ty, Legal);
482 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
483 setOperationAction(ISD::FCEIL, Ty, Legal);
484 setOperationAction(ISD::FRINT, Ty, Legal);
485 setOperationAction(ISD::FTRUNC, Ty, Legal);
486 setOperationAction(ISD::FROUND, Ty, Legal);
490 // Prefer likely predicted branches to selects on out-of-order cores.
491 if (Subtarget->isCortexA57())
492 PredictableSelectIsExpensive = true;
495 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
496 if (VT == MVT::v2f32) {
497 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
498 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
500 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
501 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
502 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
503 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
504 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
506 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
507 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
510 // Mark vector float intrinsics as expand.
511 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
512 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
513 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
514 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
515 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
516 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
517 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
518 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
519 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
520 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
523 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
524 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
525 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
526 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
527 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
528 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
529 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
530 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
531 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
532 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
533 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
534 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
536 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
537 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
538 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
539 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
541 // CNT supports only B element sizes.
542 if (VT != MVT::v8i8 && VT != MVT::v16i8)
543 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
545 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
546 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
547 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
548 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
549 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
551 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
552 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
554 if (Subtarget->isLittleEndian()) {
555 for (unsigned im = (unsigned)ISD::PRE_INC;
556 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
557 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
558 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
563 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
564 addRegisterClass(VT, &AArch64::FPR64RegClass);
565 addTypeForNEON(VT, MVT::v2i32);
568 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
569 addRegisterClass(VT, &AArch64::FPR128RegClass);
570 addTypeForNEON(VT, MVT::v4i32);
573 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
576 return VT.changeVectorElementTypeToInteger();
579 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
580 /// Mask are known to be either zero or one and return them in the
581 /// KnownZero/KnownOne bitsets.
582 void AArch64TargetLowering::computeKnownBitsForTargetNode(
583 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
584 const SelectionDAG &DAG, unsigned Depth) const {
585 switch (Op.getOpcode()) {
588 case AArch64ISD::CSEL: {
589 APInt KnownZero2, KnownOne2;
590 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
591 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
592 KnownZero &= KnownZero2;
593 KnownOne &= KnownOne2;
596 case ISD::INTRINSIC_W_CHAIN: {
597 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
598 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
601 case Intrinsic::aarch64_ldaxr:
602 case Intrinsic::aarch64_ldxr: {
603 unsigned BitWidth = KnownOne.getBitWidth();
604 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
605 unsigned MemBits = VT.getScalarType().getSizeInBits();
606 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
612 case ISD::INTRINSIC_WO_CHAIN:
613 case ISD::INTRINSIC_VOID: {
614 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
618 case Intrinsic::aarch64_neon_umaxv:
619 case Intrinsic::aarch64_neon_uminv: {
620 // Figure out the datatype of the vector operand. The UMINV instruction
621 // will zero extend the result, so we can mark as known zero all the
622 // bits larger than the element datatype. 32-bit or larget doesn't need
623 // this as those are legal types and will be handled by isel directly.
624 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
625 unsigned BitWidth = KnownZero.getBitWidth();
626 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
627 assert(BitWidth >= 8 && "Unexpected width!");
628 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
630 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
631 assert(BitWidth >= 16 && "Unexpected width!");
632 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
642 MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
646 unsigned AArch64TargetLowering::getMaximalGlobalOffset() const {
647 // FIXME: On AArch64, this depends on the type.
648 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
649 // and the offset has to be a multiple of the related size in bytes.
654 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
655 const TargetLibraryInfo *libInfo) const {
656 return AArch64::createFastISel(funcInfo, libInfo);
659 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
663 case AArch64ISD::CALL: return "AArch64ISD::CALL";
664 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
665 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
666 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
667 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
668 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
669 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
670 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
671 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
672 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
673 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
674 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
675 case AArch64ISD::TLSDESC_CALL: return "AArch64ISD::TLSDESC_CALL";
676 case AArch64ISD::ADC: return "AArch64ISD::ADC";
677 case AArch64ISD::SBC: return "AArch64ISD::SBC";
678 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
679 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
680 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
681 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
682 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
683 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
684 case AArch64ISD::FMIN: return "AArch64ISD::FMIN";
685 case AArch64ISD::FMAX: return "AArch64ISD::FMAX";
686 case AArch64ISD::DUP: return "AArch64ISD::DUP";
687 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
688 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
689 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
690 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
691 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
692 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
693 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
694 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
695 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
696 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
697 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
698 case AArch64ISD::BICi: return "AArch64ISD::BICi";
699 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
700 case AArch64ISD::BSL: return "AArch64ISD::BSL";
701 case AArch64ISD::NEG: return "AArch64ISD::NEG";
702 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
703 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
704 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
705 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
706 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
707 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
708 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
709 case AArch64ISD::REV16: return "AArch64ISD::REV16";
710 case AArch64ISD::REV32: return "AArch64ISD::REV32";
711 case AArch64ISD::REV64: return "AArch64ISD::REV64";
712 case AArch64ISD::EXT: return "AArch64ISD::EXT";
713 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
714 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
715 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
716 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
717 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
718 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
719 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
720 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
721 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
722 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
723 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
724 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
725 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
726 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
727 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
728 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
729 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
730 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
731 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
732 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
733 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
734 case AArch64ISD::NOT: return "AArch64ISD::NOT";
735 case AArch64ISD::BIT: return "AArch64ISD::BIT";
736 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
737 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
738 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
739 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
740 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
741 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
742 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
743 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
744 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
745 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
746 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
747 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
748 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
749 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
750 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
751 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
752 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
753 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
754 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
755 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
756 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
757 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
758 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
759 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
760 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
761 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
762 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
763 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
764 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
765 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
766 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
767 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
768 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
769 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
770 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
771 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
776 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
777 MachineBasicBlock *MBB) const {
778 // We materialise the F128CSEL pseudo-instruction as some control flow and a
782 // [... previous instrs leading to comparison ...]
788 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
790 const TargetInstrInfo *TII =
791 getTargetMachine().getSubtargetImpl()->getInstrInfo();
792 MachineFunction *MF = MBB->getParent();
793 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
794 DebugLoc DL = MI->getDebugLoc();
795 MachineFunction::iterator It = MBB;
798 unsigned DestReg = MI->getOperand(0).getReg();
799 unsigned IfTrueReg = MI->getOperand(1).getReg();
800 unsigned IfFalseReg = MI->getOperand(2).getReg();
801 unsigned CondCode = MI->getOperand(3).getImm();
802 bool NZCVKilled = MI->getOperand(4).isKill();
804 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
805 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
806 MF->insert(It, TrueBB);
807 MF->insert(It, EndBB);
809 // Transfer rest of current basic-block to EndBB
810 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
812 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
814 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
815 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
816 MBB->addSuccessor(TrueBB);
817 MBB->addSuccessor(EndBB);
819 // TrueBB falls through to the end.
820 TrueBB->addSuccessor(EndBB);
823 TrueBB->addLiveIn(AArch64::NZCV);
824 EndBB->addLiveIn(AArch64::NZCV);
827 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
833 MI->eraseFromParent();
838 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
839 MachineBasicBlock *BB) const {
840 switch (MI->getOpcode()) {
845 llvm_unreachable("Unexpected instruction for custom inserter!");
847 case AArch64::F128CSEL:
848 return EmitF128CSEL(MI, BB);
850 case TargetOpcode::STACKMAP:
851 case TargetOpcode::PATCHPOINT:
852 return emitPatchPoint(MI, BB);
856 //===----------------------------------------------------------------------===//
857 // AArch64 Lowering private implementation.
858 //===----------------------------------------------------------------------===//
860 //===----------------------------------------------------------------------===//
862 //===----------------------------------------------------------------------===//
864 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
866 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
869 llvm_unreachable("Unknown condition code!");
871 return AArch64CC::NE;
873 return AArch64CC::EQ;
875 return AArch64CC::GT;
877 return AArch64CC::GE;
879 return AArch64CC::LT;
881 return AArch64CC::LE;
883 return AArch64CC::HI;
885 return AArch64CC::HS;
887 return AArch64CC::LO;
889 return AArch64CC::LS;
893 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
894 static void changeFPCCToAArch64CC(ISD::CondCode CC,
895 AArch64CC::CondCode &CondCode,
896 AArch64CC::CondCode &CondCode2) {
897 CondCode2 = AArch64CC::AL;
900 llvm_unreachable("Unknown FP condition!");
903 CondCode = AArch64CC::EQ;
907 CondCode = AArch64CC::GT;
911 CondCode = AArch64CC::GE;
914 CondCode = AArch64CC::MI;
917 CondCode = AArch64CC::LS;
920 CondCode = AArch64CC::MI;
921 CondCode2 = AArch64CC::GT;
924 CondCode = AArch64CC::VC;
927 CondCode = AArch64CC::VS;
930 CondCode = AArch64CC::EQ;
931 CondCode2 = AArch64CC::VS;
934 CondCode = AArch64CC::HI;
937 CondCode = AArch64CC::PL;
941 CondCode = AArch64CC::LT;
945 CondCode = AArch64CC::LE;
949 CondCode = AArch64CC::NE;
954 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
955 /// CC usable with the vector instructions. Fewer operations are available
956 /// without a real NZCV register, so we have to use less efficient combinations
957 /// to get the same effect.
958 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
959 AArch64CC::CondCode &CondCode,
960 AArch64CC::CondCode &CondCode2,
965 // Mostly the scalar mappings work fine.
966 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
969 Invert = true; // Fallthrough
971 CondCode = AArch64CC::MI;
972 CondCode2 = AArch64CC::GE;
979 // All of the compare-mask comparisons are ordered, but we can switch
980 // between the two by a double inversion. E.g. ULE == !OGT.
982 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
987 static bool isLegalArithImmed(uint64_t C) {
988 // Matches AArch64DAGToDAGISel::SelectArithImmed().
989 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
992 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
993 SDLoc dl, SelectionDAG &DAG) {
994 EVT VT = LHS.getValueType();
996 if (VT.isFloatingPoint())
997 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
999 // The CMP instruction is just an alias for SUBS, and representing it as
1000 // SUBS means that it's possible to get CSE with subtract operations.
1001 // A later phase can perform the optimization of setting the destination
1002 // register to WZR/XZR if it ends up being unused.
1003 unsigned Opcode = AArch64ISD::SUBS;
1005 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1006 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1007 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1008 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1009 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1010 // can be set differently by this operation. It comes down to whether
1011 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1012 // everything is fine. If not then the optimization is wrong. Thus general
1013 // comparisons are only valid if op2 != 0.
1015 // So, finally, the only LLVM-native comparisons that don't mention C and V
1016 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1017 // the absence of information about op2.
1018 Opcode = AArch64ISD::ADDS;
1019 RHS = RHS.getOperand(1);
1020 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1021 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1022 !isUnsignedIntSetCC(CC)) {
1023 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1024 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1025 // of the signed comparisons.
1026 Opcode = AArch64ISD::ANDS;
1027 RHS = LHS.getOperand(1);
1028 LHS = LHS.getOperand(0);
1031 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1035 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1036 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1037 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1038 EVT VT = RHS.getValueType();
1039 uint64_t C = RHSC->getZExtValue();
1040 if (!isLegalArithImmed(C)) {
1041 // Constant does not fit, try adjusting it by one?
1047 if ((VT == MVT::i32 && C != 0x80000000 &&
1048 isLegalArithImmed((uint32_t)(C - 1))) ||
1049 (VT == MVT::i64 && C != 0x80000000ULL &&
1050 isLegalArithImmed(C - 1ULL))) {
1051 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1052 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1053 RHS = DAG.getConstant(C, VT);
1058 if ((VT == MVT::i32 && C != 0 &&
1059 isLegalArithImmed((uint32_t)(C - 1))) ||
1060 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1061 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1062 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1063 RHS = DAG.getConstant(C, VT);
1068 if ((VT == MVT::i32 && C != 0x7fffffff &&
1069 isLegalArithImmed((uint32_t)(C + 1))) ||
1070 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1071 isLegalArithImmed(C + 1ULL))) {
1072 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1073 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1074 RHS = DAG.getConstant(C, VT);
1079 if ((VT == MVT::i32 && C != 0xffffffff &&
1080 isLegalArithImmed((uint32_t)(C + 1))) ||
1081 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1082 isLegalArithImmed(C + 1ULL))) {
1083 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1084 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1085 RHS = DAG.getConstant(C, VT);
1092 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1093 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
1094 AArch64cc = DAG.getConstant(AArch64CC, MVT::i32);
1098 static std::pair<SDValue, SDValue>
1099 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1100 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1101 "Unsupported value type");
1102 SDValue Value, Overflow;
1104 SDValue LHS = Op.getOperand(0);
1105 SDValue RHS = Op.getOperand(1);
1107 switch (Op.getOpcode()) {
1109 llvm_unreachable("Unknown overflow instruction!");
1111 Opc = AArch64ISD::ADDS;
1115 Opc = AArch64ISD::ADDS;
1119 Opc = AArch64ISD::SUBS;
1123 Opc = AArch64ISD::SUBS;
1126 // Multiply needs a little bit extra work.
1130 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1131 if (Op.getValueType() == MVT::i32) {
1132 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1133 // For a 32 bit multiply with overflow check we want the instruction
1134 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1135 // need to generate the following pattern:
1136 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1137 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1138 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1139 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1140 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1141 DAG.getConstant(0, MVT::i64));
1142 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1143 // operation. We need to clear out the upper 32 bits, because we used a
1144 // widening multiply that wrote all 64 bits. In the end this should be a
1146 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1148 // The signed overflow check requires more than just a simple check for
1149 // any bit set in the upper 32 bits of the result. These bits could be
1150 // just the sign bits of a negative number. To perform the overflow
1151 // check we have to arithmetic shift right the 32nd bit of the result by
1152 // 31 bits. Then we compare the result to the upper 32 bits.
1153 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1154 DAG.getConstant(32, MVT::i64));
1155 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1156 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1157 DAG.getConstant(31, MVT::i64));
1158 // It is important that LowerBits is last, otherwise the arithmetic
1159 // shift will not be folded into the compare (SUBS).
1160 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1161 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1164 // The overflow check for unsigned multiply is easy. We only need to
1165 // check if any of the upper 32 bits are set. This can be done with a
1166 // CMP (shifted register). For that we need to generate the following
1168 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1169 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1170 DAG.getConstant(32, MVT::i64));
1171 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1173 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1174 UpperBits).getValue(1);
1178 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1179 // For the 64 bit multiply
1180 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1182 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1183 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1184 DAG.getConstant(63, MVT::i64));
1185 // It is important that LowerBits is last, otherwise the arithmetic
1186 // shift will not be folded into the compare (SUBS).
1187 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1188 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1191 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1192 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1194 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1195 UpperBits).getValue(1);
1202 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1204 // Emit the AArch64 operation with overflow check.
1205 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1206 Overflow = Value.getValue(1);
1208 return std::make_pair(Value, Overflow);
1211 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1212 RTLIB::Libcall Call) const {
1213 SmallVector<SDValue, 2> Ops;
1214 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1215 Ops.push_back(Op.getOperand(i));
1217 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1221 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1222 SDValue Sel = Op.getOperand(0);
1223 SDValue Other = Op.getOperand(1);
1225 // If neither operand is a SELECT_CC, give up.
1226 if (Sel.getOpcode() != ISD::SELECT_CC)
1227 std::swap(Sel, Other);
1228 if (Sel.getOpcode() != ISD::SELECT_CC)
1231 // The folding we want to perform is:
1232 // (xor x, (select_cc a, b, cc, 0, -1) )
1234 // (csel x, (xor x, -1), cc ...)
1236 // The latter will get matched to a CSINV instruction.
1238 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1239 SDValue LHS = Sel.getOperand(0);
1240 SDValue RHS = Sel.getOperand(1);
1241 SDValue TVal = Sel.getOperand(2);
1242 SDValue FVal = Sel.getOperand(3);
1245 // FIXME: This could be generalized to non-integer comparisons.
1246 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1249 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1250 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1252 // The the values aren't constants, this isn't the pattern we're looking for.
1253 if (!CFVal || !CTVal)
1256 // We can commute the SELECT_CC by inverting the condition. This
1257 // might be needed to make this fit into a CSINV pattern.
1258 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1259 std::swap(TVal, FVal);
1260 std::swap(CTVal, CFVal);
1261 CC = ISD::getSetCCInverse(CC, true);
1264 // If the constants line up, perform the transform!
1265 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1267 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1270 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1271 DAG.getConstant(-1ULL, Other.getValueType()));
1273 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1280 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1281 EVT VT = Op.getValueType();
1283 // Let legalize expand this if it isn't a legal type yet.
1284 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1287 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1290 bool ExtraOp = false;
1291 switch (Op.getOpcode()) {
1293 llvm_unreachable("Invalid code");
1295 Opc = AArch64ISD::ADDS;
1298 Opc = AArch64ISD::SUBS;
1301 Opc = AArch64ISD::ADCS;
1305 Opc = AArch64ISD::SBCS;
1311 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1312 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1316 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1317 // Let legalize expand this if it isn't a legal type yet.
1318 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1321 AArch64CC::CondCode CC;
1322 // The actual operation that sets the overflow or carry flag.
1323 SDValue Value, Overflow;
1324 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1326 // We use 0 and 1 as false and true values.
1327 SDValue TVal = DAG.getConstant(1, MVT::i32);
1328 SDValue FVal = DAG.getConstant(0, MVT::i32);
1330 // We use an inverted condition, because the conditional select is inverted
1331 // too. This will allow it to be selected to a single instruction:
1332 // CSINC Wd, WZR, WZR, invert(cond).
1333 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1334 Overflow = DAG.getNode(AArch64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal,
1337 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1338 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1341 // Prefetch operands are:
1342 // 1: Address to prefetch
1344 // 3: int locality (0 = no locality ... 3 = extreme locality)
1345 // 4: bool isDataCache
1346 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1348 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1349 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1350 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1352 bool IsStream = !Locality;
1353 // When the locality number is set
1355 // The front-end should have filtered out the out-of-range values
1356 assert(Locality <= 3 && "Prefetch locality out-of-range");
1357 // The locality degree is the opposite of the cache speed.
1358 // Put the number the other way around.
1359 // The encoding starts at 0 for level 1
1360 Locality = 3 - Locality;
1363 // built the mask value encoding the expected behavior.
1364 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1365 (!IsData << 3) | // IsDataCache bit
1366 (Locality << 1) | // Cache level bits
1367 (unsigned)IsStream; // Stream bit
1368 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1369 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1372 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1373 SelectionDAG &DAG) const {
1374 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1377 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1379 return LowerF128Call(Op, DAG, LC);
1382 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1383 SelectionDAG &DAG) const {
1384 if (Op.getOperand(0).getValueType() != MVT::f128) {
1385 // It's legal except when f128 is involved
1390 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1392 // FP_ROUND node has a second operand indicating whether it is known to be
1393 // precise. That doesn't take part in the LibCall so we can't directly use
1395 SDValue SrcVal = Op.getOperand(0);
1396 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1397 /*isSigned*/ false, SDLoc(Op)).first;
1400 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1401 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1402 // Any additional optimization in this function should be recorded
1403 // in the cost tables.
1404 EVT InVT = Op.getOperand(0).getValueType();
1405 EVT VT = Op.getValueType();
1407 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1410 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1412 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1415 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1417 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Op.getOperand(0));
1418 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1421 // Type changing conversions are illegal.
1425 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1426 SelectionDAG &DAG) const {
1427 if (Op.getOperand(0).getValueType().isVector())
1428 return LowerVectorFP_TO_INT(Op, DAG);
1430 if (Op.getOperand(0).getValueType() != MVT::f128) {
1431 // It's legal except when f128 is involved
1436 if (Op.getOpcode() == ISD::FP_TO_SINT)
1437 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1439 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1441 SmallVector<SDValue, 2> Ops;
1442 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1443 Ops.push_back(Op.getOperand(i));
1445 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1449 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1450 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1451 // Any additional optimization in this function should be recorded
1452 // in the cost tables.
1453 EVT VT = Op.getValueType();
1455 SDValue In = Op.getOperand(0);
1456 EVT InVT = In.getValueType();
1458 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1460 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1461 InVT.getVectorNumElements());
1462 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1463 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0));
1466 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1468 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1469 EVT CastVT = VT.changeVectorElementTypeToInteger();
1470 In = DAG.getNode(CastOpc, dl, CastVT, In);
1471 return DAG.getNode(Op.getOpcode(), dl, VT, In);
1477 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1478 SelectionDAG &DAG) const {
1479 if (Op.getValueType().isVector())
1480 return LowerVectorINT_TO_FP(Op, DAG);
1482 // i128 conversions are libcalls.
1483 if (Op.getOperand(0).getValueType() == MVT::i128)
1486 // Other conversions are legal, unless it's to the completely software-based
1488 if (Op.getValueType() != MVT::f128)
1492 if (Op.getOpcode() == ISD::SINT_TO_FP)
1493 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1495 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1497 return LowerF128Call(Op, DAG, LC);
1500 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1501 SelectionDAG &DAG) const {
1502 // For iOS, we want to call an alternative entry point: __sincos_stret,
1503 // which returns the values in two S / D registers.
1505 SDValue Arg = Op.getOperand(0);
1506 EVT ArgVT = Arg.getValueType();
1507 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1514 Entry.isSExt = false;
1515 Entry.isZExt = false;
1516 Args.push_back(Entry);
1518 const char *LibcallName =
1519 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1520 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1522 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1523 TargetLowering::CallLoweringInfo CLI(DAG);
1524 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1525 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1527 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1528 return CallResult.first;
1531 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1532 if (Op.getValueType() != MVT::f16)
1535 assert(Op.getOperand(0).getValueType() == MVT::i16);
1538 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1539 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1541 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1542 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
1547 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1548 SelectionDAG &DAG) const {
1549 switch (Op.getOpcode()) {
1551 llvm_unreachable("unimplemented operand");
1554 return LowerBITCAST(Op, DAG);
1555 case ISD::GlobalAddress:
1556 return LowerGlobalAddress(Op, DAG);
1557 case ISD::GlobalTLSAddress:
1558 return LowerGlobalTLSAddress(Op, DAG);
1560 return LowerSETCC(Op, DAG);
1562 return LowerBR_CC(Op, DAG);
1564 return LowerSELECT(Op, DAG);
1565 case ISD::SELECT_CC:
1566 return LowerSELECT_CC(Op, DAG);
1567 case ISD::JumpTable:
1568 return LowerJumpTable(Op, DAG);
1569 case ISD::ConstantPool:
1570 return LowerConstantPool(Op, DAG);
1571 case ISD::BlockAddress:
1572 return LowerBlockAddress(Op, DAG);
1574 return LowerVASTART(Op, DAG);
1576 return LowerVACOPY(Op, DAG);
1578 return LowerVAARG(Op, DAG);
1583 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1590 return LowerXALUO(Op, DAG);
1592 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1594 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1596 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1598 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1600 return LowerFP_ROUND(Op, DAG);
1601 case ISD::FP_EXTEND:
1602 return LowerFP_EXTEND(Op, DAG);
1603 case ISD::FRAMEADDR:
1604 return LowerFRAMEADDR(Op, DAG);
1605 case ISD::RETURNADDR:
1606 return LowerRETURNADDR(Op, DAG);
1607 case ISD::INSERT_VECTOR_ELT:
1608 return LowerINSERT_VECTOR_ELT(Op, DAG);
1609 case ISD::EXTRACT_VECTOR_ELT:
1610 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1611 case ISD::BUILD_VECTOR:
1612 return LowerBUILD_VECTOR(Op, DAG);
1613 case ISD::VECTOR_SHUFFLE:
1614 return LowerVECTOR_SHUFFLE(Op, DAG);
1615 case ISD::EXTRACT_SUBVECTOR:
1616 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1620 return LowerVectorSRA_SRL_SHL(Op, DAG);
1621 case ISD::SHL_PARTS:
1622 return LowerShiftLeftParts(Op, DAG);
1623 case ISD::SRL_PARTS:
1624 case ISD::SRA_PARTS:
1625 return LowerShiftRightParts(Op, DAG);
1627 return LowerCTPOP(Op, DAG);
1628 case ISD::FCOPYSIGN:
1629 return LowerFCOPYSIGN(Op, DAG);
1631 return LowerVectorAND(Op, DAG);
1633 return LowerVectorOR(Op, DAG);
1635 return LowerXOR(Op, DAG);
1637 return LowerPREFETCH(Op, DAG);
1638 case ISD::SINT_TO_FP:
1639 case ISD::UINT_TO_FP:
1640 return LowerINT_TO_FP(Op, DAG);
1641 case ISD::FP_TO_SINT:
1642 case ISD::FP_TO_UINT:
1643 return LowerFP_TO_INT(Op, DAG);
1645 return LowerFSINCOS(Op, DAG);
1649 /// getFunctionAlignment - Return the Log2 alignment of this function.
1650 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
1654 //===----------------------------------------------------------------------===//
1655 // Calling Convention Implementation
1656 //===----------------------------------------------------------------------===//
1658 #include "AArch64GenCallingConv.inc"
1660 /// Selects the correct CCAssignFn for a the given CallingConvention
1662 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1663 bool IsVarArg) const {
1666 llvm_unreachable("Unsupported calling convention.");
1667 case CallingConv::WebKit_JS:
1668 return CC_AArch64_WebKit_JS;
1669 case CallingConv::C:
1670 case CallingConv::Fast:
1671 if (!Subtarget->isTargetDarwin())
1672 return CC_AArch64_AAPCS;
1673 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
1677 SDValue AArch64TargetLowering::LowerFormalArguments(
1678 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1679 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1680 SmallVectorImpl<SDValue> &InVals) const {
1681 MachineFunction &MF = DAG.getMachineFunction();
1682 MachineFrameInfo *MFI = MF.getFrameInfo();
1684 // Assign locations to all of the incoming arguments.
1685 SmallVector<CCValAssign, 16> ArgLocs;
1686 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1689 // At this point, Ins[].VT may already be promoted to i32. To correctly
1690 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1691 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
1692 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1693 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1695 unsigned NumArgs = Ins.size();
1696 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1697 unsigned CurArgIdx = 0;
1698 for (unsigned i = 0; i != NumArgs; ++i) {
1699 MVT ValVT = Ins[i].VT;
1700 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1701 CurArgIdx = Ins[i].OrigArgIndex;
1703 // Get type of the original argument.
1704 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1705 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1706 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1707 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1709 else if (ActualMVT == MVT::i16)
1712 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1714 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1715 assert(!Res && "Call operand has unhandled type");
1718 assert(ArgLocs.size() == Ins.size());
1719 SmallVector<SDValue, 16> ArgValues;
1720 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1721 CCValAssign &VA = ArgLocs[i];
1723 if (Ins[i].Flags.isByVal()) {
1724 // Byval is used for HFAs in the PCS, but the system should work in a
1725 // non-compliant manner for larger structs.
1726 EVT PtrTy = getPointerTy();
1727 int Size = Ins[i].Flags.getByValSize();
1728 unsigned NumRegs = (Size + 7) / 8;
1730 // FIXME: This works on big-endian for composite byvals, which are the common
1731 // case. It should also work for fundamental types too.
1733 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1734 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1735 InVals.push_back(FrameIdxN);
1740 if (VA.isRegLoc()) {
1741 // Arguments stored in registers.
1742 EVT RegVT = VA.getLocVT();
1745 const TargetRegisterClass *RC;
1747 if (RegVT == MVT::i32)
1748 RC = &AArch64::GPR32RegClass;
1749 else if (RegVT == MVT::i64)
1750 RC = &AArch64::GPR64RegClass;
1751 else if (RegVT == MVT::f16)
1752 RC = &AArch64::FPR16RegClass;
1753 else if (RegVT == MVT::f32)
1754 RC = &AArch64::FPR32RegClass;
1755 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
1756 RC = &AArch64::FPR64RegClass;
1757 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
1758 RC = &AArch64::FPR128RegClass;
1760 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1762 // Transform the arguments in physical registers into virtual ones.
1763 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1764 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1766 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1767 // to 64 bits. Insert an assert[sz]ext to capture this, then
1768 // truncate to the right size.
1769 switch (VA.getLocInfo()) {
1771 llvm_unreachable("Unknown loc info!");
1772 case CCValAssign::Full:
1774 case CCValAssign::BCvt:
1775 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1777 case CCValAssign::AExt:
1778 case CCValAssign::SExt:
1779 case CCValAssign::ZExt:
1780 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
1781 // nodes after our lowering.
1782 assert(RegVT == Ins[i].VT && "incorrect register location selected");
1786 InVals.push_back(ArgValue);
1788 } else { // VA.isRegLoc()
1789 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1790 unsigned ArgOffset = VA.getLocMemOffset();
1791 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
1793 uint32_t BEAlign = 0;
1794 if (ArgSize < 8 && !Subtarget->isLittleEndian())
1795 BEAlign = 8 - ArgSize;
1797 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
1799 // Create load nodes to retrieve arguments from the stack.
1800 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1803 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1804 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1805 MVT MemVT = VA.getValVT();
1807 switch (VA.getLocInfo()) {
1810 case CCValAssign::BCvt:
1811 MemVT = VA.getLocVT();
1813 case CCValAssign::SExt:
1814 ExtType = ISD::SEXTLOAD;
1816 case CCValAssign::ZExt:
1817 ExtType = ISD::ZEXTLOAD;
1819 case CCValAssign::AExt:
1820 ExtType = ISD::EXTLOAD;
1824 ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
1825 MachinePointerInfo::getFixedStack(FI),
1826 MemVT, false, false, false, 0, nullptr);
1828 InVals.push_back(ArgValue);
1834 if (!Subtarget->isTargetDarwin()) {
1835 // The AAPCS variadic function ABI is identical to the non-variadic
1836 // one. As a result there may be more arguments in registers and we should
1837 // save them for future reference.
1838 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1841 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1842 // This will point to the next argument passed via stack.
1843 unsigned StackOffset = CCInfo.getNextStackOffset();
1844 // We currently pass all varargs at 8-byte alignment.
1845 StackOffset = ((StackOffset + 7) & ~7);
1846 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1849 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1850 unsigned StackArgSize = CCInfo.getNextStackOffset();
1851 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1852 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1853 // This is a non-standard ABI so by fiat I say we're allowed to make full
1854 // use of the stack area to be popped, which must be aligned to 16 bytes in
1856 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1858 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1859 // a multiple of 16.
1860 FuncInfo->setArgumentStackToRestore(StackArgSize);
1862 // This realignment carries over to the available bytes below. Our own
1863 // callers will guarantee the space is free by giving an aligned value to
1866 // Even if we're not expected to free up the space, it's useful to know how
1867 // much is there while considering tail calls (because we can reuse it).
1868 FuncInfo->setBytesInStackArgArea(StackArgSize);
1873 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1874 SelectionDAG &DAG, SDLoc DL,
1875 SDValue &Chain) const {
1876 MachineFunction &MF = DAG.getMachineFunction();
1877 MachineFrameInfo *MFI = MF.getFrameInfo();
1878 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1880 SmallVector<SDValue, 8> MemOps;
1882 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
1883 AArch64::X3, AArch64::X4, AArch64::X5,
1884 AArch64::X6, AArch64::X7 };
1885 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1886 unsigned FirstVariadicGPR =
1887 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1889 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1891 if (GPRSaveSize != 0) {
1892 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1894 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1896 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1897 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
1898 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1900 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1901 MachinePointerInfo::getStack(i * 8), false, false, 0);
1902 MemOps.push_back(Store);
1903 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1904 DAG.getConstant(8, getPointerTy()));
1907 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1908 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1910 if (Subtarget->hasFPARMv8()) {
1911 static const MCPhysReg FPRArgRegs[] = {
1912 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
1913 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
1914 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1915 unsigned FirstVariadicFPR =
1916 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1918 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1920 if (FPRSaveSize != 0) {
1921 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1923 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1925 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1926 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
1927 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
1930 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1931 MachinePointerInfo::getStack(i * 16), false, false, 0);
1932 MemOps.push_back(Store);
1933 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1934 DAG.getConstant(16, getPointerTy()));
1937 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1938 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1941 if (!MemOps.empty()) {
1942 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1946 /// LowerCallResult - Lower the result values of a call into the
1947 /// appropriate copies out of appropriate physical registers.
1948 SDValue AArch64TargetLowering::LowerCallResult(
1949 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1950 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1951 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1952 SDValue ThisVal) const {
1953 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
1954 ? RetCC_AArch64_WebKit_JS
1955 : RetCC_AArch64_AAPCS;
1956 // Assign locations to each value returned by this call.
1957 SmallVector<CCValAssign, 16> RVLocs;
1958 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1960 CCInfo.AnalyzeCallResult(Ins, RetCC);
1962 // Copy all of the result registers out of their specified physreg.
1963 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1964 CCValAssign VA = RVLocs[i];
1966 // Pass 'this' value directly from the argument to return value, to avoid
1967 // reg unit interference
1968 if (i == 0 && isThisReturn) {
1969 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1970 "unexpected return calling convention register assignment");
1971 InVals.push_back(ThisVal);
1976 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1977 Chain = Val.getValue(1);
1978 InFlag = Val.getValue(2);
1980 switch (VA.getLocInfo()) {
1982 llvm_unreachable("Unknown loc info!");
1983 case CCValAssign::Full:
1985 case CCValAssign::BCvt:
1986 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1990 InVals.push_back(Val);
1996 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
1997 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1998 bool isCalleeStructRet, bool isCallerStructRet,
1999 const SmallVectorImpl<ISD::OutputArg> &Outs,
2000 const SmallVectorImpl<SDValue> &OutVals,
2001 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2002 // For CallingConv::C this function knows whether the ABI needs
2003 // changing. That's not true for other conventions so they will have to opt in
2005 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2008 const MachineFunction &MF = DAG.getMachineFunction();
2009 const Function *CallerF = MF.getFunction();
2010 CallingConv::ID CallerCC = CallerF->getCallingConv();
2011 bool CCMatch = CallerCC == CalleeCC;
2013 // Byval parameters hand the function a pointer directly into the stack area
2014 // we want to reuse during a tail call. Working around this *is* possible (see
2015 // X86) but less efficient and uglier in LowerCall.
2016 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2017 e = CallerF->arg_end();
2019 if (i->hasByValAttr())
2022 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2023 if (IsTailCallConvention(CalleeCC) && CCMatch)
2028 // Externally-defined functions with weak linkage should not be
2029 // tail-called on AArch64 when the OS does not support dynamic
2030 // pre-emption of symbols, as the AAELF spec requires normal calls
2031 // to undefined weak functions to be replaced with a NOP or jump to the
2032 // next instruction. The behaviour of branch instructions in this
2033 // situation (as used for tail calls) is implementation-defined, so we
2034 // cannot rely on the linker replacing the tail call with a return.
2035 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2036 const GlobalValue *GV = G->getGlobal();
2037 if (GV->hasExternalWeakLinkage())
2041 // Now we search for cases where we can use a tail call without changing the
2042 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2045 // I want anyone implementing a new calling convention to think long and hard
2046 // about this assert.
2047 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2048 "Unexpected variadic calling convention");
2050 if (isVarArg && !Outs.empty()) {
2051 // At least two cases here: if caller is fastcc then we can't have any
2052 // memory arguments (we'd be expected to clean up the stack afterwards). If
2053 // caller is C then we could potentially use its argument area.
2055 // FIXME: for now we take the most conservative of these in both cases:
2056 // disallow all variadic memory operands.
2057 SmallVector<CCValAssign, 16> ArgLocs;
2058 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2061 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2062 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2063 if (!ArgLocs[i].isRegLoc())
2067 // If the calling conventions do not match, then we'd better make sure the
2068 // results are returned in the same way as what the caller expects.
2070 SmallVector<CCValAssign, 16> RVLocs1;
2071 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2073 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2075 SmallVector<CCValAssign, 16> RVLocs2;
2076 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2078 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2080 if (RVLocs1.size() != RVLocs2.size())
2082 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2083 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2085 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2087 if (RVLocs1[i].isRegLoc()) {
2088 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2091 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2097 // Nothing more to check if the callee is taking no arguments
2101 SmallVector<CCValAssign, 16> ArgLocs;
2102 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2105 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2107 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2109 // If the stack arguments for this call would fit into our own save area then
2110 // the call can be made tail.
2111 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2114 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2116 MachineFrameInfo *MFI,
2117 int ClobberedFI) const {
2118 SmallVector<SDValue, 8> ArgChains;
2119 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2120 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2122 // Include the original chain at the beginning of the list. When this is
2123 // used by target LowerCall hooks, this helps legalize find the
2124 // CALLSEQ_BEGIN node.
2125 ArgChains.push_back(Chain);
2127 // Add a chain value for each stack argument corresponding
2128 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2129 UE = DAG.getEntryNode().getNode()->use_end();
2131 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2132 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2133 if (FI->getIndex() < 0) {
2134 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2135 int64_t InLastByte = InFirstByte;
2136 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2138 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2139 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2140 ArgChains.push_back(SDValue(L, 1));
2143 // Build a tokenfactor for all the chains.
2144 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2147 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2148 bool TailCallOpt) const {
2149 return CallCC == CallingConv::Fast && TailCallOpt;
2152 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2153 return CallCC == CallingConv::Fast;
2156 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2157 /// and add input and output parameter nodes.
2159 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2160 SmallVectorImpl<SDValue> &InVals) const {
2161 SelectionDAG &DAG = CLI.DAG;
2163 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2164 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2165 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2166 SDValue Chain = CLI.Chain;
2167 SDValue Callee = CLI.Callee;
2168 bool &IsTailCall = CLI.IsTailCall;
2169 CallingConv::ID CallConv = CLI.CallConv;
2170 bool IsVarArg = CLI.IsVarArg;
2172 MachineFunction &MF = DAG.getMachineFunction();
2173 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2174 bool IsThisReturn = false;
2176 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2177 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2178 bool IsSibCall = false;
2181 // Check if it's really possible to do a tail call.
2182 IsTailCall = isEligibleForTailCallOptimization(
2183 Callee, CallConv, IsVarArg, IsStructRet,
2184 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2185 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2186 report_fatal_error("failed to perform tail call elimination on a call "
2187 "site marked musttail");
2189 // A sibling call is one where we're under the usual C ABI and not planning
2190 // to change that but can still do a tail call:
2191 if (!TailCallOpt && IsTailCall)
2198 // Analyze operands of the call, assigning locations to each operand.
2199 SmallVector<CCValAssign, 16> ArgLocs;
2200 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2204 // Handle fixed and variable vector arguments differently.
2205 // Variable vector arguments always go into memory.
2206 unsigned NumArgs = Outs.size();
2208 for (unsigned i = 0; i != NumArgs; ++i) {
2209 MVT ArgVT = Outs[i].VT;
2210 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2211 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2212 /*IsVarArg=*/ !Outs[i].IsFixed);
2213 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2214 assert(!Res && "Call operand has unhandled type");
2218 // At this point, Outs[].VT may already be promoted to i32. To correctly
2219 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2220 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2221 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2222 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2224 unsigned NumArgs = Outs.size();
2225 for (unsigned i = 0; i != NumArgs; ++i) {
2226 MVT ValVT = Outs[i].VT;
2227 // Get type of the original argument.
2228 EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2229 /*AllowUnknown*/ true);
2230 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2231 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2232 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2233 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2235 else if (ActualMVT == MVT::i16)
2238 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2239 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2240 assert(!Res && "Call operand has unhandled type");
2245 // Get a count of how many bytes are to be pushed on the stack.
2246 unsigned NumBytes = CCInfo.getNextStackOffset();
2249 // Since we're not changing the ABI to make this a tail call, the memory
2250 // operands are already available in the caller's incoming argument space.
2254 // FPDiff is the byte offset of the call's argument area from the callee's.
2255 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2256 // by this amount for a tail call. In a sibling call it must be 0 because the
2257 // caller will deallocate the entire stack and the callee still expects its
2258 // arguments to begin at SP+0. Completely unused for non-tail calls.
2261 if (IsTailCall && !IsSibCall) {
2262 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2264 // Since callee will pop argument stack as a tail call, we must keep the
2265 // popped size 16-byte aligned.
2266 NumBytes = RoundUpToAlignment(NumBytes, 16);
2268 // FPDiff will be negative if this tail call requires more space than we
2269 // would automatically have in our incoming argument space. Positive if we
2270 // can actually shrink the stack.
2271 FPDiff = NumReusableBytes - NumBytes;
2273 // The stack pointer must be 16-byte aligned at all times it's used for a
2274 // memory operation, which in practice means at *all* times and in
2275 // particular across call boundaries. Therefore our own arguments started at
2276 // a 16-byte aligned SP and the delta applied for the tail call should
2277 // satisfy the same constraint.
2278 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2281 // Adjust the stack pointer for the new arguments...
2282 // These operations are automatically eliminated by the prolog/epilog pass
2285 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2287 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2289 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2290 SmallVector<SDValue, 8> MemOpChains;
2292 // Walk the register/memloc assignments, inserting copies/loads.
2293 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2294 ++i, ++realArgIdx) {
2295 CCValAssign &VA = ArgLocs[i];
2296 SDValue Arg = OutVals[realArgIdx];
2297 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2299 // Promote the value if needed.
2300 switch (VA.getLocInfo()) {
2302 llvm_unreachable("Unknown loc info!");
2303 case CCValAssign::Full:
2305 case CCValAssign::SExt:
2306 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2308 case CCValAssign::ZExt:
2309 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2311 case CCValAssign::AExt:
2312 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2313 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2314 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2315 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2317 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2319 case CCValAssign::BCvt:
2320 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2322 case CCValAssign::FPExt:
2323 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2327 if (VA.isRegLoc()) {
2328 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2329 assert(VA.getLocVT() == MVT::i64 &&
2330 "unexpected calling convention register assignment");
2331 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2332 "unexpected use of 'returned'");
2333 IsThisReturn = true;
2335 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2337 assert(VA.isMemLoc());
2340 MachinePointerInfo DstInfo;
2342 // FIXME: This works on big-endian for composite byvals, which are the
2343 // common case. It should also work for fundamental types too.
2344 uint32_t BEAlign = 0;
2345 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2346 : VA.getValVT().getSizeInBits();
2347 OpSize = (OpSize + 7) / 8;
2348 if (!Subtarget->isLittleEndian() && !Flags.isByVal()) {
2350 BEAlign = 8 - OpSize;
2352 unsigned LocMemOffset = VA.getLocMemOffset();
2353 int32_t Offset = LocMemOffset + BEAlign;
2354 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2355 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2358 Offset = Offset + FPDiff;
2359 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2361 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2362 DstInfo = MachinePointerInfo::getFixedStack(FI);
2364 // Make sure any stack arguments overlapping with where we're storing
2365 // are loaded before this eventual operation. Otherwise they'll be
2367 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2369 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2371 DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2372 DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2375 if (Outs[i].Flags.isByVal()) {
2377 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2378 SDValue Cpy = DAG.getMemcpy(
2379 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2381 /*AlwaysInline = */ false, DstInfo, MachinePointerInfo());
2383 MemOpChains.push_back(Cpy);
2385 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2386 // promoted to a legal register type i32, we should truncate Arg back to
2388 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2389 VA.getValVT() == MVT::i16)
2390 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
2393 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2394 MemOpChains.push_back(Store);
2399 if (!MemOpChains.empty())
2400 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2402 // Build a sequence of copy-to-reg nodes chained together with token chain
2403 // and flag operands which copy the outgoing args into the appropriate regs.
2405 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2406 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2407 RegsToPass[i].second, InFlag);
2408 InFlag = Chain.getValue(1);
2411 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2412 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2413 // node so that legalize doesn't hack it.
2414 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2415 Subtarget->isTargetMachO()) {
2416 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2417 const GlobalValue *GV = G->getGlobal();
2418 bool InternalLinkage = GV->hasInternalLinkage();
2419 if (InternalLinkage)
2420 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2422 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2424 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2426 } else if (ExternalSymbolSDNode *S =
2427 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2428 const char *Sym = S->getSymbol();
2430 DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2431 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2433 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2434 const GlobalValue *GV = G->getGlobal();
2435 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2436 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2437 const char *Sym = S->getSymbol();
2438 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2441 // We don't usually want to end the call-sequence here because we would tidy
2442 // the frame up *after* the call, however in the ABI-changing tail-call case
2443 // we've carefully laid out the parameters so that when sp is reset they'll be
2444 // in the correct location.
2445 if (IsTailCall && !IsSibCall) {
2446 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2447 DAG.getIntPtrConstant(0, true), InFlag, DL);
2448 InFlag = Chain.getValue(1);
2451 std::vector<SDValue> Ops;
2452 Ops.push_back(Chain);
2453 Ops.push_back(Callee);
2456 // Each tail call may have to adjust the stack by a different amount, so
2457 // this information must travel along with the operation for eventual
2458 // consumption by emitEpilogue.
2459 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
2462 // Add argument registers to the end of the list so that they are known live
2464 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2465 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2466 RegsToPass[i].second.getValueType()));
2468 // Add a register mask operand representing the call-preserved registers.
2469 const uint32_t *Mask;
2470 const TargetRegisterInfo *TRI =
2471 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2472 const AArch64RegisterInfo *ARI =
2473 static_cast<const AArch64RegisterInfo *>(TRI);
2475 // For 'this' returns, use the X0-preserving mask if applicable
2476 Mask = ARI->getThisReturnPreservedMask(CallConv);
2478 IsThisReturn = false;
2479 Mask = ARI->getCallPreservedMask(CallConv);
2482 Mask = ARI->getCallPreservedMask(CallConv);
2484 assert(Mask && "Missing call preserved mask for calling convention");
2485 Ops.push_back(DAG.getRegisterMask(Mask));
2487 if (InFlag.getNode())
2488 Ops.push_back(InFlag);
2490 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2492 // If we're doing a tall call, use a TC_RETURN here rather than an
2493 // actual call instruction.
2495 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
2497 // Returns a chain and a flag for retval copy to use.
2498 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2499 InFlag = Chain.getValue(1);
2501 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2502 ? RoundUpToAlignment(NumBytes, 16)
2505 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2506 DAG.getIntPtrConstant(CalleePopBytes, true),
2509 InFlag = Chain.getValue(1);
2511 // Handle result values, copying them out of physregs into vregs that we
2513 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2514 InVals, IsThisReturn,
2515 IsThisReturn ? OutVals[0] : SDValue());
2518 bool AArch64TargetLowering::CanLowerReturn(
2519 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2520 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2521 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2522 ? RetCC_AArch64_WebKit_JS
2523 : RetCC_AArch64_AAPCS;
2524 SmallVector<CCValAssign, 16> RVLocs;
2525 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2526 return CCInfo.CheckReturn(Outs, RetCC);
2530 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2532 const SmallVectorImpl<ISD::OutputArg> &Outs,
2533 const SmallVectorImpl<SDValue> &OutVals,
2534 SDLoc DL, SelectionDAG &DAG) const {
2535 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2536 ? RetCC_AArch64_WebKit_JS
2537 : RetCC_AArch64_AAPCS;
2538 SmallVector<CCValAssign, 16> RVLocs;
2539 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2541 CCInfo.AnalyzeReturn(Outs, RetCC);
2543 // Copy the result values into the output registers.
2545 SmallVector<SDValue, 4> RetOps(1, Chain);
2546 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2547 ++i, ++realRVLocIdx) {
2548 CCValAssign &VA = RVLocs[i];
2549 assert(VA.isRegLoc() && "Can only return in registers!");
2550 SDValue Arg = OutVals[realRVLocIdx];
2552 switch (VA.getLocInfo()) {
2554 llvm_unreachable("Unknown loc info!");
2555 case CCValAssign::Full:
2556 if (Outs[i].ArgVT == MVT::i1) {
2557 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2558 // value. This is strictly redundant on Darwin (which uses "zeroext
2559 // i1"), but will be optimised out before ISel.
2560 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2561 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2564 case CCValAssign::BCvt:
2565 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2569 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2570 Flag = Chain.getValue(1);
2571 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2574 RetOps[0] = Chain; // Update chain.
2576 // Add the flag if we have it.
2578 RetOps.push_back(Flag);
2580 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2583 //===----------------------------------------------------------------------===//
2584 // Other Lowering Code
2585 //===----------------------------------------------------------------------===//
2587 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2588 SelectionDAG &DAG) const {
2589 EVT PtrVT = getPointerTy();
2591 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2592 unsigned char OpFlags =
2593 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2595 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2596 "unexpected offset in global node");
2598 // This also catched the large code model case for Darwin.
2599 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2600 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2601 // FIXME: Once remat is capable of dealing with instructions with register
2602 // operands, expand this into two nodes instead of using a wrapper node.
2603 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2606 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2607 const unsigned char MO_NC = AArch64II::MO_NC;
2609 AArch64ISD::WrapperLarge, DL, PtrVT,
2610 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
2611 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
2612 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
2613 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
2615 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2616 // the only correct model on Darwin.
2617 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2618 OpFlags | AArch64II::MO_PAGE);
2619 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2620 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2622 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2623 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2627 /// \brief Convert a TLS address reference into the correct sequence of loads
2628 /// and calls to compute the variable's address (for Darwin, currently) and
2629 /// return an SDValue containing the final node.
2631 /// Darwin only has one TLS scheme which must be capable of dealing with the
2632 /// fully general situation, in the worst case. This means:
2633 /// + "extern __thread" declaration.
2634 /// + Defined in a possibly unknown dynamic library.
2636 /// The general system is that each __thread variable has a [3 x i64] descriptor
2637 /// which contains information used by the runtime to calculate the address. The
2638 /// only part of this the compiler needs to know about is the first xword, which
2639 /// contains a function pointer that must be called with the address of the
2640 /// entire descriptor in "x0".
2642 /// Since this descriptor may be in a different unit, in general even the
2643 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2645 /// adrp x0, _var@TLVPPAGE
2646 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2647 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2648 /// ; the function pointer
2649 /// blr x1 ; Uses descriptor address in x0
2650 /// ; Address of _var is now in x0.
2652 /// If the address of _var's descriptor *is* known to the linker, then it can
2653 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2654 /// a slight efficiency gain.
2656 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2657 SelectionDAG &DAG) const {
2658 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2661 MVT PtrVT = getPointerTy();
2662 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2665 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2666 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2668 // The first entry in the descriptor is a function pointer that we must call
2669 // to obtain the address of the variable.
2670 SDValue Chain = DAG.getEntryNode();
2671 SDValue FuncTLVGet =
2672 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2673 false, true, true, 8);
2674 Chain = FuncTLVGet.getValue(1);
2676 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2677 MFI->setAdjustsStack(true);
2679 // TLS calls preserve all registers except those that absolutely must be
2680 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2682 const TargetRegisterInfo *TRI =
2683 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2684 const AArch64RegisterInfo *ARI =
2685 static_cast<const AArch64RegisterInfo *>(TRI);
2686 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2688 // Finally, we can make the call. This is just a degenerate version of a
2689 // normal AArch64 call node: x0 takes the address of the descriptor, and
2690 // returns the address of the variable in this thread.
2691 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
2693 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2694 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
2695 DAG.getRegisterMask(Mask), Chain.getValue(1));
2696 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
2699 /// When accessing thread-local variables under either the general-dynamic or
2700 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2701 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2702 /// is a function pointer to carry out the resolution. This function takes the
2703 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2704 /// other registers (except LR, NZCV) are preserved.
2706 /// Thus, the ideal call sequence on AArch64 is:
2708 /// adrp x0, :tlsdesc:thread_var
2709 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2710 /// add x0, x0, :tlsdesc_lo12:thread_var
2711 /// .tlsdesccall thread_var
2713 /// (TPIDR_EL0 offset now in x0).
2715 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2716 /// relocation to help the linker relax this sequence if it turns out to be too
2719 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2721 SDValue AArch64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2722 SDValue DescAddr, SDLoc DL,
2723 SelectionDAG &DAG) const {
2724 EVT PtrVT = getPointerTy();
2726 // The function we need to call is simply the first entry in the GOT for this
2727 // descriptor, load it in preparation.
2728 SDValue Func = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, SymAddr);
2730 // TLS calls preserve all registers except those that absolutely must be
2731 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2733 const TargetRegisterInfo *TRI =
2734 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2735 const AArch64RegisterInfo *ARI =
2736 static_cast<const AArch64RegisterInfo *>(TRI);
2737 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2739 // The function takes only one argument: the address of the descriptor itself
2741 SDValue Glue, Chain;
2742 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2743 Glue = Chain.getValue(1);
2745 // We're now ready to populate the argument list, as with a normal call:
2746 SmallVector<SDValue, 6> Ops;
2747 Ops.push_back(Chain);
2748 Ops.push_back(Func);
2749 Ops.push_back(SymAddr);
2750 Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2751 Ops.push_back(DAG.getRegisterMask(Mask));
2752 Ops.push_back(Glue);
2754 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2755 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALL, DL, NodeTys, Ops);
2756 Glue = Chain.getValue(1);
2758 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2762 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2763 SelectionDAG &DAG) const {
2764 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2765 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2766 "ELF TLS only supported in small memory model");
2767 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2769 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2772 EVT PtrVT = getPointerTy();
2774 const GlobalValue *GV = GA->getGlobal();
2776 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2778 if (Model == TLSModel::LocalExec) {
2779 SDValue HiVar = DAG.getTargetGlobalAddress(
2780 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
2781 SDValue LoVar = DAG.getTargetGlobalAddress(
2783 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
2785 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
2786 DAG.getTargetConstant(16, MVT::i32)),
2788 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2789 DAG.getTargetConstant(0, MVT::i32)),
2791 } else if (Model == TLSModel::InitialExec) {
2792 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2793 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
2794 } else if (Model == TLSModel::LocalDynamic) {
2795 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2796 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2797 // the beginning of the module's TLS region, followed by a DTPREL offset
2800 // These accesses will need deduplicating if there's more than one.
2801 AArch64FunctionInfo *MFI =
2802 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
2803 MFI->incNumLocalDynamicTLSAccesses();
2805 // Accesses used in this sequence go via the TLS descriptor which lives in
2806 // the GOT. Prepare an address we can use to handle this.
2807 SDValue HiDesc = DAG.getTargetExternalSymbol(
2808 "_TLS_MODULE_BASE_", PtrVT, AArch64II::MO_TLS | AArch64II::MO_PAGE);
2809 SDValue LoDesc = DAG.getTargetExternalSymbol(
2810 "_TLS_MODULE_BASE_", PtrVT,
2811 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2813 // First argument to the descriptor call is the address of the descriptor
2815 SDValue DescAddr = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, HiDesc);
2816 DescAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2818 // The call needs a relocation too for linker relaxation. It doesn't make
2819 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2821 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2824 // Now we can calculate the offset from TPIDR_EL0 to this module's
2825 // thread-local area.
2826 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2828 // Now use :dtprel_whatever: operations to calculate this variable's offset
2829 // in its thread-storage area.
2830 SDValue HiVar = DAG.getTargetGlobalAddress(
2831 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
2832 SDValue LoVar = DAG.getTargetGlobalAddress(
2833 GV, DL, MVT::i64, 0,
2834 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
2837 SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
2838 DAG.getTargetConstant(16, MVT::i32)),
2841 SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2842 DAG.getTargetConstant(0, MVT::i32)),
2845 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2846 } else if (Model == TLSModel::GeneralDynamic) {
2847 // Accesses used in this sequence go via the TLS descriptor which lives in
2848 // the GOT. Prepare an address we can use to handle this.
2849 SDValue HiDesc = DAG.getTargetGlobalAddress(
2850 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGE);
2851 SDValue LoDesc = DAG.getTargetGlobalAddress(
2853 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2855 // First argument to the descriptor call is the address of the descriptor
2857 SDValue DescAddr = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, HiDesc);
2858 DescAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2860 // The call needs a relocation too for linker relaxation. It doesn't make
2861 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2864 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2866 // Finally we can make a call to calculate the offset from tpidr_el0.
2867 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2869 llvm_unreachable("Unsupported ELF TLS access model");
2871 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2874 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2875 SelectionDAG &DAG) const {
2876 if (Subtarget->isTargetDarwin())
2877 return LowerDarwinGlobalTLSAddress(Op, DAG);
2878 else if (Subtarget->isTargetELF())
2879 return LowerELFGlobalTLSAddress(Op, DAG);
2881 llvm_unreachable("Unexpected platform trying to use TLS");
2883 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2884 SDValue Chain = Op.getOperand(0);
2885 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2886 SDValue LHS = Op.getOperand(2);
2887 SDValue RHS = Op.getOperand(3);
2888 SDValue Dest = Op.getOperand(4);
2891 // Handle f128 first, since lowering it will result in comparing the return
2892 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2893 // is expecting to deal with.
2894 if (LHS.getValueType() == MVT::f128) {
2895 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2897 // If softenSetCCOperands returned a scalar, we need to compare the result
2898 // against zero to select between true and false values.
2899 if (!RHS.getNode()) {
2900 RHS = DAG.getConstant(0, LHS.getValueType());
2905 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2907 unsigned Opc = LHS.getOpcode();
2908 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2909 cast<ConstantSDNode>(RHS)->isOne() &&
2910 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2911 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2912 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2913 "Unexpected condition code.");
2914 // Only lower legal XALUO ops.
2915 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2918 // The actual operation with overflow check.
2919 AArch64CC::CondCode OFCC;
2920 SDValue Value, Overflow;
2921 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
2923 if (CC == ISD::SETNE)
2924 OFCC = getInvertedCondCode(OFCC);
2925 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2927 return DAG.getNode(AArch64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2931 if (LHS.getValueType().isInteger()) {
2932 assert((LHS.getValueType() == RHS.getValueType()) &&
2933 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2935 // If the RHS of the comparison is zero, we can potentially fold this
2936 // to a specialized branch.
2937 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2938 if (RHSC && RHSC->getZExtValue() == 0) {
2939 if (CC == ISD::SETEQ) {
2940 // See if we can use a TBZ to fold in an AND as well.
2941 // TBZ has a smaller branch displacement than CBZ. If the offset is
2942 // out of bounds, a late MI-layer pass rewrites branches.
2943 // 403.gcc is an example that hits this case.
2944 if (LHS.getOpcode() == ISD::AND &&
2945 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2946 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2947 SDValue Test = LHS.getOperand(0);
2948 uint64_t Mask = LHS.getConstantOperandVal(1);
2949 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
2950 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2953 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2954 } else if (CC == ISD::SETNE) {
2955 // See if we can use a TBZ to fold in an AND as well.
2956 // TBZ has a smaller branch displacement than CBZ. If the offset is
2957 // out of bounds, a late MI-layer pass rewrites branches.
2958 // 403.gcc is an example that hits this case.
2959 if (LHS.getOpcode() == ISD::AND &&
2960 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2961 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2962 SDValue Test = LHS.getOperand(0);
2963 uint64_t Mask = LHS.getConstantOperandVal(1);
2964 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2965 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2968 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2969 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
2970 // Don't combine AND since emitComparison converts the AND to an ANDS
2971 // (a.k.a. TST) and the test in the test bit and branch instruction
2972 // becomes redundant. This would also increase register pressure.
2973 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
2974 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
2975 DAG.getConstant(Mask, MVT::i64), Dest);
2978 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
2979 LHS.getOpcode() != ISD::AND) {
2980 // Don't combine AND since emitComparison converts the AND to an ANDS
2981 // (a.k.a. TST) and the test in the test bit and branch instruction
2982 // becomes redundant. This would also increase register pressure.
2983 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
2984 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
2985 DAG.getConstant(Mask, MVT::i64), Dest);
2989 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2990 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2994 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2996 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
2997 // clean. Some of them require two branches to implement.
2998 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2999 AArch64CC::CondCode CC1, CC2;
3000 changeFPCCToAArch64CC(CC, CC1, CC2);
3001 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3003 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3004 if (CC2 != AArch64CC::AL) {
3005 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3006 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3013 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3014 SelectionDAG &DAG) const {
3015 EVT VT = Op.getValueType();
3018 SDValue In1 = Op.getOperand(0);
3019 SDValue In2 = Op.getOperand(1);
3020 EVT SrcVT = In2.getValueType();
3022 if (SrcVT == MVT::f32 && VT == MVT::f64)
3023 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3024 else if (SrcVT == MVT::f64 && VT == MVT::f32)
3025 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3027 // FIXME: Src type is different, bail out for now. Can VT really be a
3034 SDValue EltMask, VecVal1, VecVal2;
3035 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3038 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
3040 if (!VT.isVector()) {
3041 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3042 DAG.getUNDEF(VecVT), In1);
3043 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3044 DAG.getUNDEF(VecVT), In2);
3046 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3047 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3049 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3053 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3054 // immediate moves cannot materialize that in a single instruction for
3055 // 64-bit elements. Instead, materialize zero and then negate it.
3056 EltMask = DAG.getConstant(0, EltVT);
3058 if (!VT.isVector()) {
3059 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3060 DAG.getUNDEF(VecVT), In1);
3061 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3062 DAG.getUNDEF(VecVT), In2);
3064 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3065 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3068 llvm_unreachable("Invalid type for copysign!");
3071 std::vector<SDValue> BuildVectorOps;
3072 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
3073 BuildVectorOps.push_back(EltMask);
3075 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
3077 // If we couldn't materialize the mask above, then the mask vector will be
3078 // the zero vector, and we need to negate it here.
3079 if (VT == MVT::f64 || VT == MVT::v2f64) {
3080 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3081 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3082 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3086 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3089 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3090 else if (VT == MVT::f64)
3091 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3093 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3096 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3097 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
3098 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
3101 // While there is no integer popcount instruction, it can
3102 // be more efficiently lowered to the following sequence that uses
3103 // AdvSIMD registers/instructions as long as the copies to/from
3104 // the AdvSIMD registers are cheap.
3105 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3106 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3107 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3108 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3109 SDValue Val = Op.getOperand(0);
3111 EVT VT = Op.getValueType();
3112 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
3115 if (VT == MVT::i32) {
3116 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
3117 VecVal = DAG.getTargetInsertSubreg(AArch64::ssub, DL, MVT::v8i8, ZeroVec,
3120 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3123 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
3124 SDValue UaddLV = DAG.getNode(
3125 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3126 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, MVT::i32), CtPop);
3129 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3133 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3135 if (Op.getValueType().isVector())
3136 return LowerVSETCC(Op, DAG);
3138 SDValue LHS = Op.getOperand(0);
3139 SDValue RHS = Op.getOperand(1);
3140 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3143 // We chose ZeroOrOneBooleanContents, so use zero and one.
3144 EVT VT = Op.getValueType();
3145 SDValue TVal = DAG.getConstant(1, VT);
3146 SDValue FVal = DAG.getConstant(0, VT);
3148 // Handle f128 first, since one possible outcome is a normal integer
3149 // comparison which gets picked up by the next if statement.
3150 if (LHS.getValueType() == MVT::f128) {
3151 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3153 // If softenSetCCOperands returned a scalar, use it.
3154 if (!RHS.getNode()) {
3155 assert(LHS.getValueType() == Op.getValueType() &&
3156 "Unexpected setcc expansion!");
3161 if (LHS.getValueType().isInteger()) {
3164 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3166 // Note that we inverted the condition above, so we reverse the order of
3167 // the true and false operands here. This will allow the setcc to be
3168 // matched to a single CSINC instruction.
3169 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3172 // Now we know we're dealing with FP values.
3173 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3175 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3176 // and do the comparison.
3177 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3179 AArch64CC::CondCode CC1, CC2;
3180 changeFPCCToAArch64CC(CC, CC1, CC2);
3181 if (CC2 == AArch64CC::AL) {
3182 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3183 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3185 // Note that we inverted the condition above, so we reverse the order of
3186 // the true and false operands here. This will allow the setcc to be
3187 // matched to a single CSINC instruction.
3188 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3190 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3191 // totally clean. Some of them require two CSELs to implement. As is in
3192 // this case, we emit the first CSEL and then emit a second using the output
3193 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3195 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3196 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3198 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3200 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3201 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3205 /// A SELECT_CC operation is really some kind of max or min if both values being
3206 /// compared are, in some sense, equal to the results in either case. However,
3207 /// it is permissible to compare f32 values and produce directly extended f64
3210 /// Extending the comparison operands would also be allowed, but is less likely
3211 /// to happen in practice since their use is right here. Note that truncate
3212 /// operations would *not* be semantically equivalent.
3213 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3217 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3218 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3219 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3220 Result.getValueType() == MVT::f64) {
3222 APFloat CmpVal = CCmp->getValueAPF();
3223 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3224 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3227 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3230 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3231 SelectionDAG &DAG) const {
3232 SDValue CC = Op->getOperand(0);
3233 SDValue TVal = Op->getOperand(1);
3234 SDValue FVal = Op->getOperand(2);
3237 unsigned Opc = CC.getOpcode();
3238 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3240 if (CC.getResNo() == 1 &&
3241 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3242 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3243 // Only lower legal XALUO ops.
3244 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3247 AArch64CC::CondCode OFCC;
3248 SDValue Value, Overflow;
3249 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CC.getValue(0), DAG);
3250 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3252 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3256 if (CC.getOpcode() == ISD::SETCC)
3257 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3258 cast<CondCodeSDNode>(CC.getOperand(2))->get());
3260 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3264 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3265 SelectionDAG &DAG) const {
3266 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3267 SDValue LHS = Op.getOperand(0);
3268 SDValue RHS = Op.getOperand(1);
3269 SDValue TVal = Op.getOperand(2);
3270 SDValue FVal = Op.getOperand(3);
3273 // Handle f128 first, because it will result in a comparison of some RTLIB
3274 // call result against zero.
3275 if (LHS.getValueType() == MVT::f128) {
3276 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3278 // If softenSetCCOperands returned a scalar, we need to compare the result
3279 // against zero to select between true and false values.
3280 if (!RHS.getNode()) {
3281 RHS = DAG.getConstant(0, LHS.getValueType());
3286 // Handle integers first.
3287 if (LHS.getValueType().isInteger()) {
3288 assert((LHS.getValueType() == RHS.getValueType()) &&
3289 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3291 unsigned Opcode = AArch64ISD::CSEL;
3293 // If both the TVal and the FVal are constants, see if we can swap them in
3294 // order to for a CSINV or CSINC out of them.
3295 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3296 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3298 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3299 std::swap(TVal, FVal);
3300 std::swap(CTVal, CFVal);
3301 CC = ISD::getSetCCInverse(CC, true);
3302 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3303 std::swap(TVal, FVal);
3304 std::swap(CTVal, CFVal);
3305 CC = ISD::getSetCCInverse(CC, true);
3306 } else if (TVal.getOpcode() == ISD::XOR) {
3307 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3308 // with a CSINV rather than a CSEL.
3309 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3311 if (CVal && CVal->isAllOnesValue()) {
3312 std::swap(TVal, FVal);
3313 std::swap(CTVal, CFVal);
3314 CC = ISD::getSetCCInverse(CC, true);
3316 } else if (TVal.getOpcode() == ISD::SUB) {
3317 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3318 // that we can match with a CSNEG rather than a CSEL.
3319 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3321 if (CVal && CVal->isNullValue()) {
3322 std::swap(TVal, FVal);
3323 std::swap(CTVal, CFVal);
3324 CC = ISD::getSetCCInverse(CC, true);
3326 } else if (CTVal && CFVal) {
3327 const int64_t TrueVal = CTVal->getSExtValue();
3328 const int64_t FalseVal = CFVal->getSExtValue();
3331 // If both TVal and FVal are constants, see if FVal is the
3332 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3333 // instead of a CSEL in that case.
3334 if (TrueVal == ~FalseVal) {
3335 Opcode = AArch64ISD::CSINV;
3336 } else if (TrueVal == -FalseVal) {
3337 Opcode = AArch64ISD::CSNEG;
3338 } else if (TVal.getValueType() == MVT::i32) {
3339 // If our operands are only 32-bit wide, make sure we use 32-bit
3340 // arithmetic for the check whether we can use CSINC. This ensures that
3341 // the addition in the check will wrap around properly in case there is
3342 // an overflow (which would not be the case if we do the check with
3343 // 64-bit arithmetic).
3344 const uint32_t TrueVal32 = CTVal->getZExtValue();
3345 const uint32_t FalseVal32 = CFVal->getZExtValue();
3347 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3348 Opcode = AArch64ISD::CSINC;
3350 if (TrueVal32 > FalseVal32) {
3354 // 64-bit check whether we can use CSINC.
3355 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3356 Opcode = AArch64ISD::CSINC;
3358 if (TrueVal > FalseVal) {
3363 // Swap TVal and FVal if necessary.
3365 std::swap(TVal, FVal);
3366 std::swap(CTVal, CFVal);
3367 CC = ISD::getSetCCInverse(CC, true);
3370 if (Opcode != AArch64ISD::CSEL) {
3371 // Drop FVal since we can get its value by simply inverting/negating
3378 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3380 EVT VT = Op.getValueType();
3381 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3384 // Now we know we're dealing with FP values.
3385 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3386 assert(LHS.getValueType() == RHS.getValueType());
3387 EVT VT = Op.getValueType();
3389 // Try to match this select into a max/min operation, which have dedicated
3390 // opcode in the instruction set.
3391 // FIXME: This is not correct in the presence of NaNs, so we only enable this
3393 if (getTargetMachine().Options.NoNaNsFPMath) {
3394 SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3395 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3396 selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3397 CC = ISD::getSetCCSwappedOperands(CC);
3398 std::swap(MinMaxLHS, MinMaxRHS);
3401 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3402 selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3412 return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3420 return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3426 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3427 // and do the comparison.
3428 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3430 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3431 // clean. Some of them require two CSELs to implement.
3432 AArch64CC::CondCode CC1, CC2;
3433 changeFPCCToAArch64CC(CC, CC1, CC2);
3434 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3435 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3437 // If we need a second CSEL, emit it, using the output of the first as the
3438 // RHS. We're effectively OR'ing the two CC's together.
3439 if (CC2 != AArch64CC::AL) {
3440 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3441 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3444 // Otherwise, return the output of the first CSEL.
3448 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3449 SelectionDAG &DAG) const {
3450 // Jump table entries as PC relative offsets. No additional tweaking
3451 // is necessary here. Just get the address of the jump table.
3452 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3453 EVT PtrVT = getPointerTy();
3456 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3457 !Subtarget->isTargetMachO()) {
3458 const unsigned char MO_NC = AArch64II::MO_NC;
3460 AArch64ISD::WrapperLarge, DL, PtrVT,
3461 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3462 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3463 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3464 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3465 AArch64II::MO_G0 | MO_NC));
3469 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3470 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3471 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3472 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3473 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3476 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3477 SelectionDAG &DAG) const {
3478 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3479 EVT PtrVT = getPointerTy();
3482 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3483 // Use the GOT for the large code model on iOS.
3484 if (Subtarget->isTargetMachO()) {
3485 SDValue GotAddr = DAG.getTargetConstantPool(
3486 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3488 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3491 const unsigned char MO_NC = AArch64II::MO_NC;
3493 AArch64ISD::WrapperLarge, DL, PtrVT,
3494 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3495 CP->getOffset(), AArch64II::MO_G3),
3496 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3497 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3498 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3499 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3500 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3501 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3503 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3504 // ELF, the only valid one on Darwin.
3506 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3507 CP->getOffset(), AArch64II::MO_PAGE);
3508 SDValue Lo = DAG.getTargetConstantPool(
3509 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3510 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3512 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3513 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3517 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3518 SelectionDAG &DAG) const {
3519 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3520 EVT PtrVT = getPointerTy();
3522 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3523 !Subtarget->isTargetMachO()) {
3524 const unsigned char MO_NC = AArch64II::MO_NC;
3526 AArch64ISD::WrapperLarge, DL, PtrVT,
3527 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3528 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3529 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3530 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3532 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3533 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3535 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3536 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3540 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3541 SelectionDAG &DAG) const {
3542 AArch64FunctionInfo *FuncInfo =
3543 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3547 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3548 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3549 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3550 MachinePointerInfo(SV), false, false, 0);
3553 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3554 SelectionDAG &DAG) const {
3555 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3556 // Standard, section B.3.
3557 MachineFunction &MF = DAG.getMachineFunction();
3558 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3561 SDValue Chain = Op.getOperand(0);
3562 SDValue VAList = Op.getOperand(1);
3563 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3564 SmallVector<SDValue, 4> MemOps;
3566 // void *__stack at offset 0
3568 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3569 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3570 MachinePointerInfo(SV), false, false, 8));
3572 // void *__gr_top at offset 8
3573 int GPRSize = FuncInfo->getVarArgsGPRSize();
3575 SDValue GRTop, GRTopAddr;
3577 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3578 DAG.getConstant(8, getPointerTy()));
3580 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3581 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3582 DAG.getConstant(GPRSize, getPointerTy()));
3584 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3585 MachinePointerInfo(SV, 8), false, false, 8));
3588 // void *__vr_top at offset 16
3589 int FPRSize = FuncInfo->getVarArgsFPRSize();
3591 SDValue VRTop, VRTopAddr;
3592 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3593 DAG.getConstant(16, getPointerTy()));
3595 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3596 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3597 DAG.getConstant(FPRSize, getPointerTy()));
3599 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3600 MachinePointerInfo(SV, 16), false, false, 8));
3603 // int __gr_offs at offset 24
3604 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3605 DAG.getConstant(24, getPointerTy()));
3606 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3607 GROffsAddr, MachinePointerInfo(SV, 24), false,
3610 // int __vr_offs at offset 28
3611 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3612 DAG.getConstant(28, getPointerTy()));
3613 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3614 VROffsAddr, MachinePointerInfo(SV, 28), false,
3617 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3620 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3621 SelectionDAG &DAG) const {
3622 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3623 : LowerAAPCS_VASTART(Op, DAG);
3626 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3627 SelectionDAG &DAG) const {
3628 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3630 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3631 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3632 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3634 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3635 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3636 8, false, false, MachinePointerInfo(DestSV),
3637 MachinePointerInfo(SrcSV));
3640 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3641 assert(Subtarget->isTargetDarwin() &&
3642 "automatic va_arg instruction only works on Darwin");
3644 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3645 EVT VT = Op.getValueType();
3647 SDValue Chain = Op.getOperand(0);
3648 SDValue Addr = Op.getOperand(1);
3649 unsigned Align = Op.getConstantOperandVal(3);
3651 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3652 MachinePointerInfo(V), false, false, false, 0);
3653 Chain = VAList.getValue(1);
3656 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3657 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3658 DAG.getConstant(Align - 1, getPointerTy()));
3659 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3660 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3663 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3664 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3666 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3667 // up to 64 bits. At the very least, we have to increase the striding of the
3668 // vaargs list to match this, and for FP values we need to introduce
3669 // FP_ROUND nodes as well.
3670 if (VT.isInteger() && !VT.isVector())
3672 bool NeedFPTrunc = false;
3673 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3678 // Increment the pointer, VAList, to the next vaarg
3679 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3680 DAG.getConstant(ArgSize, getPointerTy()));
3681 // Store the incremented VAList to the legalized pointer
3682 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3685 // Load the actual argument out of the pointer VAList
3687 // Load the value as an f64.
3688 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3689 MachinePointerInfo(), false, false, false, 0);
3690 // Round the value down to an f32.
3691 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3692 DAG.getIntPtrConstant(1));
3693 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3694 // Merge the rounded value with the chain output of the load.
3695 return DAG.getMergeValues(Ops, DL);
3698 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3702 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
3703 SelectionDAG &DAG) const {
3704 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3705 MFI->setFrameAddressIsTaken(true);
3707 EVT VT = Op.getValueType();
3709 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3711 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
3713 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3714 MachinePointerInfo(), false, false, false, 0);
3718 // FIXME? Maybe this could be a TableGen attribute on some registers and
3719 // this table could be generated automatically from RegInfo.
3720 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
3722 unsigned Reg = StringSwitch<unsigned>(RegName)
3723 .Case("sp", AArch64::SP)
3727 report_fatal_error("Invalid register name global variable");
3730 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
3731 SelectionDAG &DAG) const {
3732 MachineFunction &MF = DAG.getMachineFunction();
3733 MachineFrameInfo *MFI = MF.getFrameInfo();
3734 MFI->setReturnAddressIsTaken(true);
3736 EVT VT = Op.getValueType();
3738 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3740 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3741 SDValue Offset = DAG.getConstant(8, getPointerTy());
3742 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3743 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3744 MachinePointerInfo(), false, false, false, 0);
3747 // Return LR, which contains the return address. Mark it an implicit live-in.
3748 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
3749 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3752 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3753 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3754 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
3755 SelectionDAG &DAG) const {
3756 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3757 EVT VT = Op.getValueType();
3758 unsigned VTBits = VT.getSizeInBits();
3760 SDValue ShOpLo = Op.getOperand(0);
3761 SDValue ShOpHi = Op.getOperand(1);
3762 SDValue ShAmt = Op.getOperand(2);
3764 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3766 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3768 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3769 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3770 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3771 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3772 DAG.getConstant(VTBits, MVT::i64));
3773 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3775 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3776 ISD::SETGE, dl, DAG);
3777 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
3779 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3780 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3782 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3784 // AArch64 shifts larger than the register width are wrapped rather than
3785 // clamped, so we can't just emit "hi >> x".
3786 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3787 SDValue TrueValHi = Opc == ISD::SRA
3788 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3789 DAG.getConstant(VTBits - 1, MVT::i64))
3790 : DAG.getConstant(0, VT);
3792 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3794 SDValue Ops[2] = { Lo, Hi };
3795 return DAG.getMergeValues(Ops, dl);
3798 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3799 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3800 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
3801 SelectionDAG &DAG) const {
3802 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3803 EVT VT = Op.getValueType();
3804 unsigned VTBits = VT.getSizeInBits();
3806 SDValue ShOpLo = Op.getOperand(0);
3807 SDValue ShOpHi = Op.getOperand(1);
3808 SDValue ShAmt = Op.getOperand(2);
3811 assert(Op.getOpcode() == ISD::SHL_PARTS);
3812 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3813 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3814 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3815 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3816 DAG.getConstant(VTBits, MVT::i64));
3817 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3818 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3820 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3822 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3823 ISD::SETGE, dl, DAG);
3824 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
3826 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3828 // AArch64 shifts of larger than register sizes are wrapped rather than
3829 // clamped, so we can't just emit "lo << a" if a is too big.
3830 SDValue TrueValLo = DAG.getConstant(0, VT);
3831 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3833 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3835 SDValue Ops[2] = { Lo, Hi };
3836 return DAG.getMergeValues(Ops, dl);
3839 bool AArch64TargetLowering::isOffsetFoldingLegal(
3840 const GlobalAddressSDNode *GA) const {
3841 // The AArch64 target doesn't support folding offsets into global addresses.
3845 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3846 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3847 // FIXME: We should be able to handle f128 as well with a clever lowering.
3848 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3852 return AArch64_AM::getFP64Imm(Imm) != -1;
3853 else if (VT == MVT::f32)
3854 return AArch64_AM::getFP32Imm(Imm) != -1;
3858 //===----------------------------------------------------------------------===//
3859 // AArch64 Optimization Hooks
3860 //===----------------------------------------------------------------------===//
3862 //===----------------------------------------------------------------------===//
3863 // AArch64 Inline Assembly Support
3864 //===----------------------------------------------------------------------===//
3866 // Table of Constraints
3867 // TODO: This is the current set of constraints supported by ARM for the
3868 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3870 // r - A general register
3871 // w - An FP/SIMD register of some size in the range v0-v31
3872 // x - An FP/SIMD register of some size in the range v0-v15
3873 // I - Constant that can be used with an ADD instruction
3874 // J - Constant that can be used with a SUB instruction
3875 // K - Constant that can be used with a 32-bit logical instruction
3876 // L - Constant that can be used with a 64-bit logical instruction
3877 // M - Constant that can be used as a 32-bit MOV immediate
3878 // N - Constant that can be used as a 64-bit MOV immediate
3879 // Q - A memory reference with base register and no offset
3880 // S - A symbolic address
3881 // Y - Floating point constant zero
3882 // Z - Integer constant zero
3884 // Note that general register operands will be output using their 64-bit x
3885 // register name, whatever the size of the variable, unless the asm operand
3886 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3887 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3890 /// getConstraintType - Given a constraint letter, return the type of
3891 /// constraint it is for this target.
3892 AArch64TargetLowering::ConstraintType
3893 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3894 if (Constraint.size() == 1) {
3895 switch (Constraint[0]) {
3902 return C_RegisterClass;
3903 // An address with a single base register. Due to the way we
3904 // currently handle addresses it is the same as 'r'.
3909 return TargetLowering::getConstraintType(Constraint);
3912 /// Examine constraint type and operand type and determine a weight value.
3913 /// This object must already have been set up with the operand type
3914 /// and the current alternative constraint selected.
3915 TargetLowering::ConstraintWeight
3916 AArch64TargetLowering::getSingleConstraintMatchWeight(
3917 AsmOperandInfo &info, const char *constraint) const {
3918 ConstraintWeight weight = CW_Invalid;
3919 Value *CallOperandVal = info.CallOperandVal;
3920 // If we don't have a value, we can't do a match,
3921 // but allow it at the lowest weight.
3922 if (!CallOperandVal)
3924 Type *type = CallOperandVal->getType();
3925 // Look at the constraint type.
3926 switch (*constraint) {
3928 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3932 if (type->isFloatingPointTy() || type->isVectorTy())
3933 weight = CW_Register;
3936 weight = CW_Constant;
3942 std::pair<unsigned, const TargetRegisterClass *>
3943 AArch64TargetLowering::getRegForInlineAsmConstraint(
3944 const std::string &Constraint, MVT VT) const {
3945 if (Constraint.size() == 1) {
3946 switch (Constraint[0]) {
3948 if (VT.getSizeInBits() == 64)
3949 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
3950 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
3953 return std::make_pair(0U, &AArch64::FPR32RegClass);
3954 if (VT.getSizeInBits() == 64)
3955 return std::make_pair(0U, &AArch64::FPR64RegClass);
3956 if (VT.getSizeInBits() == 128)
3957 return std::make_pair(0U, &AArch64::FPR128RegClass);
3959 // The instructions that this constraint is designed for can
3960 // only take 128-bit registers so just use that regclass.
3962 if (VT.getSizeInBits() == 128)
3963 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
3967 if (StringRef("{cc}").equals_lower(Constraint))
3968 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
3970 // Use the default implementation in TargetLowering to convert the register
3971 // constraint into a member of a register class.
3972 std::pair<unsigned, const TargetRegisterClass *> Res;
3973 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3975 // Not found as a standard register?
3977 unsigned Size = Constraint.size();
3978 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3979 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3980 const std::string Reg =
3981 std::string(&Constraint[2], &Constraint[Size - 1]);
3982 int RegNo = atoi(Reg.c_str());
3983 if (RegNo >= 0 && RegNo <= 31) {
3984 // v0 - v31 are aliases of q0 - q31.
3985 // By default we'll emit v0-v31 for this unless there's a modifier where
3986 // we'll emit the correct register as well.
3987 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
3988 Res.second = &AArch64::FPR128RegClass;
3996 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3997 /// vector. If it is invalid, don't add anything to Ops.
3998 void AArch64TargetLowering::LowerAsmOperandForConstraint(
3999 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4000 SelectionDAG &DAG) const {
4003 // Currently only support length 1 constraints.
4004 if (Constraint.length() != 1)
4007 char ConstraintLetter = Constraint[0];
4008 switch (ConstraintLetter) {
4012 // This set of constraints deal with valid constants for various instructions.
4013 // Validate and return a target constant for them if we can.
4015 // 'z' maps to xzr or wzr so it needs an input of 0.
4016 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4017 if (!C || C->getZExtValue() != 0)
4020 if (Op.getValueType() == MVT::i64)
4021 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4023 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4033 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4037 // Grab the value and do some validation.
4038 uint64_t CVal = C->getZExtValue();
4039 switch (ConstraintLetter) {
4040 // The I constraint applies only to simple ADD or SUB immediate operands:
4041 // i.e. 0 to 4095 with optional shift by 12
4042 // The J constraint applies only to ADD or SUB immediates that would be
4043 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4044 // instruction [or vice versa], in other words -1 to -4095 with optional
4045 // left shift by 12.
4047 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4051 uint64_t NVal = -C->getSExtValue();
4052 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4053 CVal = C->getSExtValue();
4058 // The K and L constraints apply *only* to logical immediates, including
4059 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4060 // been removed and MOV should be used). So these constraints have to
4061 // distinguish between bit patterns that are valid 32-bit or 64-bit
4062 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4063 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4066 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4070 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4073 // The M and N constraints are a superset of K and L respectively, for use
4074 // with the MOV (immediate) alias. As well as the logical immediates they
4075 // also match 32 or 64-bit immediates that can be loaded either using a
4076 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4077 // (M) or 64-bit 0x1234000000000000 (N) etc.
4078 // As a note some of this code is liberally stolen from the asm parser.
4080 if (!isUInt<32>(CVal))
4082 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4084 if ((CVal & 0xFFFF) == CVal)
4086 if ((CVal & 0xFFFF0000ULL) == CVal)
4088 uint64_t NCVal = ~(uint32_t)CVal;
4089 if ((NCVal & 0xFFFFULL) == NCVal)
4091 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4096 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4098 if ((CVal & 0xFFFFULL) == CVal)
4100 if ((CVal & 0xFFFF0000ULL) == CVal)
4102 if ((CVal & 0xFFFF00000000ULL) == CVal)
4104 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4106 uint64_t NCVal = ~CVal;
4107 if ((NCVal & 0xFFFFULL) == NCVal)
4109 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4111 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4113 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4121 // All assembler immediates are 64-bit integers.
4122 Result = DAG.getTargetConstant(CVal, MVT::i64);
4126 if (Result.getNode()) {
4127 Ops.push_back(Result);
4131 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4134 //===----------------------------------------------------------------------===//
4135 // AArch64 Advanced SIMD Support
4136 //===----------------------------------------------------------------------===//
4138 /// WidenVector - Given a value in the V64 register class, produce the
4139 /// equivalent value in the V128 register class.
4140 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4141 EVT VT = V64Reg.getValueType();
4142 unsigned NarrowSize = VT.getVectorNumElements();
4143 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4144 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4147 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4148 V64Reg, DAG.getConstant(0, MVT::i32));
4151 /// getExtFactor - Determine the adjustment factor for the position when
4152 /// generating an "extract from vector registers" instruction.
4153 static unsigned getExtFactor(SDValue &V) {
4154 EVT EltType = V.getValueType().getVectorElementType();
4155 return EltType.getSizeInBits() / 8;
4158 /// NarrowVector - Given a value in the V128 register class, produce the
4159 /// equivalent value in the V64 register class.
4160 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4161 EVT VT = V128Reg.getValueType();
4162 unsigned WideSize = VT.getVectorNumElements();
4163 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4164 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4167 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4170 // Gather data to see if the operation can be modelled as a
4171 // shuffle in combination with VEXTs.
4172 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4173 SelectionDAG &DAG) const {
4174 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4176 EVT VT = Op.getValueType();
4177 unsigned NumElts = VT.getVectorNumElements();
4179 struct ShuffleSourceInfo {
4184 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4185 // be compatible with the shuffle we intend to construct. As a result
4186 // ShuffleVec will be some sliding window into the original Vec.
4189 // Code should guarantee that element i in Vec starts at element "WindowBase
4190 // + i * WindowScale in ShuffleVec".
4194 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4195 ShuffleSourceInfo(SDValue Vec)
4196 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4200 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4202 SmallVector<ShuffleSourceInfo, 2> Sources;
4203 for (unsigned i = 0; i < NumElts; ++i) {
4204 SDValue V = Op.getOperand(i);
4205 if (V.getOpcode() == ISD::UNDEF)
4207 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4208 // A shuffle can only come from building a vector from various
4209 // elements of other vectors.
4213 // Add this element source to the list if it's not already there.
4214 SDValue SourceVec = V.getOperand(0);
4215 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4216 if (Source == Sources.end())
4217 Sources.push_back(ShuffleSourceInfo(SourceVec));
4219 // Update the minimum and maximum lane number seen.
4220 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4221 Source->MinElt = std::min(Source->MinElt, EltNo);
4222 Source->MaxElt = std::max(Source->MaxElt, EltNo);
4225 // Currently only do something sane when at most two source vectors
4227 if (Sources.size() > 2)
4230 // Find out the smallest element size among result and two sources, and use
4231 // it as element size to build the shuffle_vector.
4232 EVT SmallestEltTy = VT.getVectorElementType();
4233 for (auto &Source : Sources) {
4234 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4235 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4236 SmallestEltTy = SrcEltTy;
4239 unsigned ResMultiplier =
4240 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4241 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4242 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4244 // If the source vector is too wide or too narrow, we may nevertheless be able
4245 // to construct a compatible shuffle either by concatenating it with UNDEF or
4246 // extracting a suitable range of elements.
4247 for (auto &Src : Sources) {
4248 EVT SrcVT = Src.ShuffleVec.getValueType();
4250 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4253 // This stage of the search produces a source with the same element type as
4254 // the original, but with a total width matching the BUILD_VECTOR output.
4255 EVT EltVT = SrcVT.getVectorElementType();
4256 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
4257 VT.getSizeInBits() / EltVT.getSizeInBits());
4259 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4260 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4261 // We can pad out the smaller vector for free, so if it's part of a
4264 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4265 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4269 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4271 if (Src.MaxElt - Src.MinElt >= NumElts) {
4272 // Span too large for a VEXT to cope
4276 if (Src.MinElt >= NumElts) {
4277 // The extraction can just take the second half
4279 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4280 DAG.getIntPtrConstant(NumElts));
4281 Src.WindowBase = -NumElts;
4282 } else if (Src.MaxElt < NumElts) {
4283 // The extraction can just take the first half
4284 Src.ShuffleVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4285 Src.ShuffleVec, DAG.getIntPtrConstant(0));
4287 // An actual VEXT is needed
4288 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4289 Src.ShuffleVec, DAG.getIntPtrConstant(0));
4291 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4292 DAG.getIntPtrConstant(NumElts));
4293 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4295 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4296 VEXTSrc2, DAG.getConstant(Imm, MVT::i32));
4297 Src.WindowBase = -Src.MinElt;
4301 // Another possible incompatibility occurs from the vector element types. We
4302 // can fix this by bitcasting the source vectors to the same type we intend
4304 for (auto &Src : Sources) {
4305 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4306 if (SrcEltTy == SmallestEltTy)
4308 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4309 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4310 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4311 Src.WindowBase *= Src.WindowScale;
4314 // Final sanity check before we try to actually produce a shuffle.
4316 for (auto Src : Sources)
4317 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4320 // The stars all align, our next step is to produce the mask for the shuffle.
4321 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4322 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4323 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4324 SDValue Entry = Op.getOperand(i);
4325 if (Entry.getOpcode() == ISD::UNDEF)
4328 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4329 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4331 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4332 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4334 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4335 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4336 VT.getVectorElementType().getSizeInBits());
4337 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4339 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4340 // starting at the appropriate offset.
4341 int *LaneMask = &Mask[i * ResMultiplier];
4343 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4344 ExtractBase += NumElts * (Src - Sources.begin());
4345 for (int j = 0; j < LanesDefined; ++j)
4346 LaneMask[j] = ExtractBase + j;
4349 // Final check before we try to produce nonsense...
4350 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4353 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4354 for (unsigned i = 0; i < Sources.size(); ++i)
4355 ShuffleOps[i] = Sources[i].ShuffleVec;
4357 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4358 ShuffleOps[1], &Mask[0]);
4359 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4362 // check if an EXT instruction can handle the shuffle mask when the
4363 // vector sources of the shuffle are the same.
4364 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4365 unsigned NumElts = VT.getVectorNumElements();
4367 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4373 // If this is a VEXT shuffle, the immediate value is the index of the first
4374 // element. The other shuffle indices must be the successive elements after
4376 unsigned ExpectedElt = Imm;
4377 for (unsigned i = 1; i < NumElts; ++i) {
4378 // Increment the expected index. If it wraps around, just follow it
4379 // back to index zero and keep going.
4381 if (ExpectedElt == NumElts)
4385 continue; // ignore UNDEF indices
4386 if (ExpectedElt != static_cast<unsigned>(M[i]))
4393 // check if an EXT instruction can handle the shuffle mask when the
4394 // vector sources of the shuffle are different.
4395 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4397 // Look for the first non-undef element.
4398 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4399 [](int Elt) {return Elt >= 0;});
4401 // Benefit form APInt to handle overflow when calculating expected element.
4402 unsigned NumElts = VT.getVectorNumElements();
4403 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4404 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4405 // The following shuffle indices must be the successive elements after the
4406 // first real element.
4407 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4408 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4409 if (FirstWrongElt != M.end())
4412 // The index of an EXT is the first element if it is not UNDEF.
4413 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4414 // value of the first element. E.g.
4415 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4416 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4417 // ExpectedElt is the last mask index plus 1.
4418 Imm = ExpectedElt.getZExtValue();
4420 // There are two difference cases requiring to reverse input vectors.
4421 // For example, for vector <4 x i32> we have the following cases,
4422 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4423 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4424 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4425 // to reverse two input vectors.
4434 /// isREVMask - Check if a vector shuffle corresponds to a REV
4435 /// instruction with the specified blocksize. (The order of the elements
4436 /// within each block of the vector is reversed.)
4437 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4438 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4439 "Only possible block sizes for REV are: 16, 32, 64");
4441 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4445 unsigned NumElts = VT.getVectorNumElements();
4446 unsigned BlockElts = M[0] + 1;
4447 // If the first shuffle index is UNDEF, be optimistic.
4449 BlockElts = BlockSize / EltSz;
4451 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4454 for (unsigned i = 0; i < NumElts; ++i) {
4456 continue; // ignore UNDEF indices
4457 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4464 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4465 unsigned NumElts = VT.getVectorNumElements();
4466 WhichResult = (M[0] == 0 ? 0 : 1);
4467 unsigned Idx = WhichResult * NumElts / 2;
4468 for (unsigned i = 0; i != NumElts; i += 2) {
4469 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4470 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4478 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4479 unsigned NumElts = VT.getVectorNumElements();
4480 WhichResult = (M[0] == 0 ? 0 : 1);
4481 for (unsigned i = 0; i != NumElts; ++i) {
4483 continue; // ignore UNDEF indices
4484 if ((unsigned)M[i] != 2 * i + WhichResult)
4491 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4492 unsigned NumElts = VT.getVectorNumElements();
4493 WhichResult = (M[0] == 0 ? 0 : 1);
4494 for (unsigned i = 0; i < NumElts; i += 2) {
4495 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4496 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4502 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4503 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4504 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4505 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4506 unsigned NumElts = VT.getVectorNumElements();
4507 WhichResult = (M[0] == 0 ? 0 : 1);
4508 unsigned Idx = WhichResult * NumElts / 2;
4509 for (unsigned i = 0; i != NumElts; i += 2) {
4510 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4511 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4519 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4520 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4521 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4522 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4523 unsigned Half = VT.getVectorNumElements() / 2;
4524 WhichResult = (M[0] == 0 ? 0 : 1);
4525 for (unsigned j = 0; j != 2; ++j) {
4526 unsigned Idx = WhichResult;
4527 for (unsigned i = 0; i != Half; ++i) {
4528 int MIdx = M[i + j * Half];
4529 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4538 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4539 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4540 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4541 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4542 unsigned NumElts = VT.getVectorNumElements();
4543 WhichResult = (M[0] == 0 ? 0 : 1);
4544 for (unsigned i = 0; i < NumElts; i += 2) {
4545 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4546 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4552 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4553 bool &DstIsLeft, int &Anomaly) {
4554 if (M.size() != static_cast<size_t>(NumInputElements))
4557 int NumLHSMatch = 0, NumRHSMatch = 0;
4558 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4560 for (int i = 0; i < NumInputElements; ++i) {
4570 LastLHSMismatch = i;
4572 if (M[i] == i + NumInputElements)
4575 LastRHSMismatch = i;
4578 if (NumLHSMatch == NumInputElements - 1) {
4580 Anomaly = LastLHSMismatch;
4582 } else if (NumRHSMatch == NumInputElements - 1) {
4584 Anomaly = LastRHSMismatch;
4591 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4592 if (VT.getSizeInBits() != 128)
4595 unsigned NumElts = VT.getVectorNumElements();
4597 for (int I = 0, E = NumElts / 2; I != E; I++) {
4602 int Offset = NumElts / 2;
4603 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4604 if (Mask[I] != I + SplitLHS * Offset)
4611 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4613 EVT VT = Op.getValueType();
4614 SDValue V0 = Op.getOperand(0);
4615 SDValue V1 = Op.getOperand(1);
4616 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4618 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4619 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4622 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4624 if (!isConcatMask(Mask, VT, SplitV0))
4627 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4628 VT.getVectorNumElements() / 2);
4630 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4631 DAG.getConstant(0, MVT::i64));
4633 if (V1.getValueType().getSizeInBits() == 128) {
4634 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4635 DAG.getConstant(0, MVT::i64));
4637 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4640 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4641 /// the specified operations to build the shuffle.
4642 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4643 SDValue RHS, SelectionDAG &DAG,
4645 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4646 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4647 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4650 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4659 OP_VUZPL, // VUZP, left result
4660 OP_VUZPR, // VUZP, right result
4661 OP_VZIPL, // VZIP, left result
4662 OP_VZIPR, // VZIP, right result
4663 OP_VTRNL, // VTRN, left result
4664 OP_VTRNR // VTRN, right result
4667 if (OpNum == OP_COPY) {
4668 if (LHSID == (1 * 9 + 2) * 9 + 3)
4670 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4674 SDValue OpLHS, OpRHS;
4675 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4676 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4677 EVT VT = OpLHS.getValueType();
4681 llvm_unreachable("Unknown shuffle opcode!");
4683 // VREV divides the vector in half and swaps within the half.
4684 if (VT.getVectorElementType() == MVT::i32 ||
4685 VT.getVectorElementType() == MVT::f32)
4686 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
4687 // vrev <4 x i16> -> REV32
4688 if (VT.getVectorElementType() == MVT::i16)
4689 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
4690 // vrev <4 x i8> -> REV16
4691 assert(VT.getVectorElementType() == MVT::i8);
4692 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
4697 EVT EltTy = VT.getVectorElementType();
4699 if (EltTy == MVT::i8)
4700 Opcode = AArch64ISD::DUPLANE8;
4701 else if (EltTy == MVT::i16)
4702 Opcode = AArch64ISD::DUPLANE16;
4703 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4704 Opcode = AArch64ISD::DUPLANE32;
4705 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4706 Opcode = AArch64ISD::DUPLANE64;
4708 llvm_unreachable("Invalid vector element type?");
4710 if (VT.getSizeInBits() == 64)
4711 OpLHS = WidenVector(OpLHS, DAG);
4712 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4713 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4718 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4719 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
4720 DAG.getConstant(Imm, MVT::i32));
4723 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
4726 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
4729 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
4732 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
4735 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
4738 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
4743 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4744 SelectionDAG &DAG) {
4745 // Check to see if we can use the TBL instruction.
4746 SDValue V1 = Op.getOperand(0);
4747 SDValue V2 = Op.getOperand(1);
4750 EVT EltVT = Op.getValueType().getVectorElementType();
4751 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4753 SmallVector<SDValue, 8> TBLMask;
4754 for (int Val : ShuffleMask) {
4755 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4756 unsigned Offset = Byte + Val * BytesPerElt;
4757 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4761 MVT IndexVT = MVT::v8i8;
4762 unsigned IndexLen = 8;
4763 if (Op.getValueType().getSizeInBits() == 128) {
4764 IndexVT = MVT::v16i8;
4768 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4769 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4772 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4774 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4775 Shuffle = DAG.getNode(
4776 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4777 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
4778 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4779 makeArrayRef(TBLMask.data(), IndexLen)));
4781 if (IndexLen == 8) {
4782 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4783 Shuffle = DAG.getNode(
4784 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4785 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
4786 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4787 makeArrayRef(TBLMask.data(), IndexLen)));
4789 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4790 // cannot currently represent the register constraints on the input
4792 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4793 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4794 // &TBLMask[0], IndexLen));
4795 Shuffle = DAG.getNode(
4796 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4797 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4798 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4799 makeArrayRef(TBLMask.data(), IndexLen)));
4802 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4805 static unsigned getDUPLANEOp(EVT EltType) {
4806 if (EltType == MVT::i8)
4807 return AArch64ISD::DUPLANE8;
4808 if (EltType == MVT::i16)
4809 return AArch64ISD::DUPLANE16;
4810 if (EltType == MVT::i32 || EltType == MVT::f32)
4811 return AArch64ISD::DUPLANE32;
4812 if (EltType == MVT::i64 || EltType == MVT::f64)
4813 return AArch64ISD::DUPLANE64;
4815 llvm_unreachable("Invalid vector element type?");
4818 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4819 SelectionDAG &DAG) const {
4821 EVT VT = Op.getValueType();
4823 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4825 // Convert shuffles that are directly supported on NEON to target-specific
4826 // DAG nodes, instead of keeping them as shuffles and matching them again
4827 // during code selection. This is more efficient and avoids the possibility
4828 // of inconsistencies between legalization and selection.
4829 ArrayRef<int> ShuffleMask = SVN->getMask();
4831 SDValue V1 = Op.getOperand(0);
4832 SDValue V2 = Op.getOperand(1);
4834 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4835 V1.getValueType().getSimpleVT())) {
4836 int Lane = SVN->getSplatIndex();
4837 // If this is undef splat, generate it via "just" vdup, if possible.
4841 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4842 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
4844 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4845 // constant. If so, we can just reference the lane's definition directly.
4846 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4847 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4848 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
4850 // Otherwise, duplicate from the lane of the input vector.
4851 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4853 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4854 // to make a vector of the same size as this SHUFFLE. We can ignore the
4855 // extract entirely, and canonicalise the concat using WidenVector.
4856 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4857 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4858 V1 = V1.getOperand(0);
4859 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4860 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4861 Lane -= Idx * VT.getVectorNumElements() / 2;
4862 V1 = WidenVector(V1.getOperand(Idx), DAG);
4863 } else if (VT.getSizeInBits() == 64)
4864 V1 = WidenVector(V1, DAG);
4866 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4869 if (isREVMask(ShuffleMask, VT, 64))
4870 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
4871 if (isREVMask(ShuffleMask, VT, 32))
4872 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
4873 if (isREVMask(ShuffleMask, VT, 16))
4874 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
4876 bool ReverseEXT = false;
4878 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4881 Imm *= getExtFactor(V1);
4882 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
4883 DAG.getConstant(Imm, MVT::i32));
4884 } else if (V2->getOpcode() == ISD::UNDEF &&
4885 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4886 Imm *= getExtFactor(V1);
4887 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
4888 DAG.getConstant(Imm, MVT::i32));
4891 unsigned WhichResult;
4892 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4893 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
4894 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4896 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4897 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
4898 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4900 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4901 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
4902 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4905 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4906 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
4907 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4909 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4910 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
4911 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4913 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4914 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
4915 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4918 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4919 if (Concat.getNode())
4924 int NumInputElements = V1.getValueType().getVectorNumElements();
4925 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4926 SDValue DstVec = DstIsLeft ? V1 : V2;
4927 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4929 SDValue SrcVec = V1;
4930 int SrcLane = ShuffleMask[Anomaly];
4931 if (SrcLane >= NumInputElements) {
4933 SrcLane -= VT.getVectorNumElements();
4935 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4937 EVT ScalarVT = VT.getVectorElementType();
4938 if (ScalarVT.getSizeInBits() < 32)
4939 ScalarVT = MVT::i32;
4942 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4943 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4947 // If the shuffle is not directly supported and it has 4 elements, use
4948 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4949 unsigned NumElts = VT.getVectorNumElements();
4951 unsigned PFIndexes[4];
4952 for (unsigned i = 0; i != 4; ++i) {
4953 if (ShuffleMask[i] < 0)
4956 PFIndexes[i] = ShuffleMask[i];
4959 // Compute the index in the perfect shuffle table.
4960 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4961 PFIndexes[2] * 9 + PFIndexes[3];
4962 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4963 unsigned Cost = (PFEntry >> 30);
4966 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4969 return GenerateTBL(Op, ShuffleMask, DAG);
4972 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4974 EVT VT = BVN->getValueType(0);
4975 APInt SplatBits, SplatUndef;
4976 unsigned SplatBitSize;
4978 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4979 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4981 for (unsigned i = 0; i < NumSplats; ++i) {
4982 CnstBits <<= SplatBitSize;
4983 UndefBits <<= SplatBitSize;
4984 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4985 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4994 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
4995 SelectionDAG &DAG) const {
4996 BuildVectorSDNode *BVN =
4997 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4998 SDValue LHS = Op.getOperand(0);
5000 EVT VT = Op.getValueType();
5005 APInt CnstBits(VT.getSizeInBits(), 0);
5006 APInt UndefBits(VT.getSizeInBits(), 0);
5007 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5008 // We only have BIC vector immediate instruction, which is and-not.
5009 CnstBits = ~CnstBits;
5011 // We make use of a little bit of goto ickiness in order to avoid having to
5012 // duplicate the immediate matching logic for the undef toggled case.
5013 bool SecondTry = false;
5016 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5017 CnstBits = CnstBits.zextOrTrunc(64);
5018 uint64_t CnstVal = CnstBits.getZExtValue();
5020 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5021 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5022 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5023 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5024 DAG.getConstant(CnstVal, MVT::i32),
5025 DAG.getConstant(0, MVT::i32));
5026 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5029 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5030 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5031 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5032 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5033 DAG.getConstant(CnstVal, MVT::i32),
5034 DAG.getConstant(8, MVT::i32));
5035 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5038 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5039 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5040 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5041 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5042 DAG.getConstant(CnstVal, MVT::i32),
5043 DAG.getConstant(16, MVT::i32));
5044 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5047 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5048 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5049 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5050 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5051 DAG.getConstant(CnstVal, MVT::i32),
5052 DAG.getConstant(24, MVT::i32));
5053 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5056 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5057 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5058 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5059 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5060 DAG.getConstant(CnstVal, MVT::i32),
5061 DAG.getConstant(0, MVT::i32));
5062 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5065 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5066 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5067 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5068 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5069 DAG.getConstant(CnstVal, MVT::i32),
5070 DAG.getConstant(8, MVT::i32));
5071 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5078 CnstBits = ~UndefBits;
5082 // We can always fall back to a non-immediate AND.
5087 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5088 // consists of only the same constant int value, returned in reference arg
5090 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5091 uint64_t &ConstVal) {
5092 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5095 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5098 EVT VT = Bvec->getValueType(0);
5099 unsigned NumElts = VT.getVectorNumElements();
5100 for (unsigned i = 1; i < NumElts; ++i)
5101 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5103 ConstVal = FirstElt->getZExtValue();
5107 static unsigned getIntrinsicID(const SDNode *N) {
5108 unsigned Opcode = N->getOpcode();
5111 return Intrinsic::not_intrinsic;
5112 case ISD::INTRINSIC_WO_CHAIN: {
5113 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5114 if (IID < Intrinsic::num_intrinsics)
5116 return Intrinsic::not_intrinsic;
5121 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5122 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5123 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5124 // Also, logical shift right -> sri, with the same structure.
5125 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5126 EVT VT = N->getValueType(0);
5133 // Is the first op an AND?
5134 const SDValue And = N->getOperand(0);
5135 if (And.getOpcode() != ISD::AND)
5138 // Is the second op an shl or lshr?
5139 SDValue Shift = N->getOperand(1);
5140 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5141 // or AArch64ISD::VLSHR vector, #shift
5142 unsigned ShiftOpc = Shift.getOpcode();
5143 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5145 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5147 // Is the shift amount constant?
5148 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5152 // Is the and mask vector all constant?
5154 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5157 // Is C1 == ~C2, taking into account how much one can shift elements of a
5159 uint64_t C2 = C2node->getZExtValue();
5160 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5161 if (C2 > ElemSizeInBits)
5163 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5164 if ((C1 & ElemMask) != (~C2 & ElemMask))
5167 SDValue X = And.getOperand(0);
5168 SDValue Y = Shift.getOperand(0);
5171 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5173 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5174 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5176 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5177 DEBUG(N->dump(&DAG));
5178 DEBUG(dbgs() << "into: \n");
5179 DEBUG(ResultSLI->dump(&DAG));
5185 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5186 SelectionDAG &DAG) const {
5187 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5188 if (EnableAArch64SlrGeneration) {
5189 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5194 BuildVectorSDNode *BVN =
5195 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5196 SDValue LHS = Op.getOperand(1);
5198 EVT VT = Op.getValueType();
5200 // OR commutes, so try swapping the operands.
5202 LHS = Op.getOperand(0);
5203 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5208 APInt CnstBits(VT.getSizeInBits(), 0);
5209 APInt UndefBits(VT.getSizeInBits(), 0);
5210 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5211 // We make use of a little bit of goto ickiness in order to avoid having to
5212 // duplicate the immediate matching logic for the undef toggled case.
5213 bool SecondTry = false;
5216 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5217 CnstBits = CnstBits.zextOrTrunc(64);
5218 uint64_t CnstVal = CnstBits.getZExtValue();
5220 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5221 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5222 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5223 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5224 DAG.getConstant(CnstVal, MVT::i32),
5225 DAG.getConstant(0, MVT::i32));
5226 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5229 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5230 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5231 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5232 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5233 DAG.getConstant(CnstVal, MVT::i32),
5234 DAG.getConstant(8, MVT::i32));
5235 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5238 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5239 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5240 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5241 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5242 DAG.getConstant(CnstVal, MVT::i32),
5243 DAG.getConstant(16, MVT::i32));
5244 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5247 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5248 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5249 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5250 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5251 DAG.getConstant(CnstVal, MVT::i32),
5252 DAG.getConstant(24, MVT::i32));
5253 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5256 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5257 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5258 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5259 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5260 DAG.getConstant(CnstVal, MVT::i32),
5261 DAG.getConstant(0, MVT::i32));
5262 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5265 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5266 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5267 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5268 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5269 DAG.getConstant(CnstVal, MVT::i32),
5270 DAG.getConstant(8, MVT::i32));
5271 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5278 CnstBits = UndefBits;
5282 // We can always fall back to a non-immediate OR.
5287 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5288 // be truncated to fit element width.
5289 static SDValue NormalizeBuildVector(SDValue Op,
5290 SelectionDAG &DAG) {
5291 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5293 EVT VT = Op.getValueType();
5294 EVT EltTy= VT.getVectorElementType();
5296 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5299 SmallVector<SDValue, 16> Ops;
5300 for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5301 SDValue Lane = Op.getOperand(I);
5302 if (Lane.getOpcode() == ISD::Constant) {
5303 APInt LowBits(EltTy.getSizeInBits(),
5304 cast<ConstantSDNode>(Lane)->getZExtValue());
5305 Lane = DAG.getConstant(LowBits.getZExtValue(), MVT::i32);
5307 Ops.push_back(Lane);
5309 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5312 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5313 SelectionDAG &DAG) const {
5315 EVT VT = Op.getValueType();
5316 Op = NormalizeBuildVector(Op, DAG);
5317 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5319 APInt CnstBits(VT.getSizeInBits(), 0);
5320 APInt UndefBits(VT.getSizeInBits(), 0);
5321 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5322 // We make use of a little bit of goto ickiness in order to avoid having to
5323 // duplicate the immediate matching logic for the undef toggled case.
5324 bool SecondTry = false;
5327 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5328 CnstBits = CnstBits.zextOrTrunc(64);
5329 uint64_t CnstVal = CnstBits.getZExtValue();
5331 // Certain magic vector constants (used to express things like NOT
5332 // and NEG) are passed through unmodified. This allows codegen patterns
5333 // for these operations to match. Special-purpose patterns will lower
5334 // these immediates to MOVIs if it proves necessary.
5335 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5338 // The many faces of MOVI...
5339 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5340 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5341 if (VT.getSizeInBits() == 128) {
5342 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5343 DAG.getConstant(CnstVal, MVT::i32));
5344 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5347 // Support the V64 version via subregister insertion.
5348 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5349 DAG.getConstant(CnstVal, MVT::i32));
5350 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5353 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5354 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5355 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5356 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5357 DAG.getConstant(CnstVal, MVT::i32),
5358 DAG.getConstant(0, MVT::i32));
5359 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5362 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5363 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5364 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5365 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5366 DAG.getConstant(CnstVal, MVT::i32),
5367 DAG.getConstant(8, MVT::i32));
5368 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5371 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5372 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5373 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5374 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5375 DAG.getConstant(CnstVal, MVT::i32),
5376 DAG.getConstant(16, MVT::i32));
5377 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5380 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5381 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5382 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5383 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5384 DAG.getConstant(CnstVal, MVT::i32),
5385 DAG.getConstant(24, MVT::i32));
5386 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5389 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5390 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5391 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5392 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5393 DAG.getConstant(CnstVal, MVT::i32),
5394 DAG.getConstant(0, MVT::i32));
5395 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5398 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5399 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5400 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5401 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5402 DAG.getConstant(CnstVal, MVT::i32),
5403 DAG.getConstant(8, MVT::i32));
5404 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5407 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5408 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5409 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5410 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5411 DAG.getConstant(CnstVal, MVT::i32),
5412 DAG.getConstant(264, MVT::i32));
5413 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5416 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5417 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5418 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5419 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5420 DAG.getConstant(CnstVal, MVT::i32),
5421 DAG.getConstant(272, MVT::i32));
5422 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5425 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5426 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5427 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5428 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
5429 DAG.getConstant(CnstVal, MVT::i32));
5430 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5433 // The few faces of FMOV...
5434 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5435 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5436 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5437 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
5438 DAG.getConstant(CnstVal, MVT::i32));
5439 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5442 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5443 VT.getSizeInBits() == 128) {
5444 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5445 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
5446 DAG.getConstant(CnstVal, MVT::i32));
5447 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5450 // The many faces of MVNI...
5452 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5453 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5454 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5455 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5456 DAG.getConstant(CnstVal, MVT::i32),
5457 DAG.getConstant(0, MVT::i32));
5458 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5461 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5462 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5463 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5464 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5465 DAG.getConstant(CnstVal, MVT::i32),
5466 DAG.getConstant(8, MVT::i32));
5467 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5470 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5471 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5472 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5473 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5474 DAG.getConstant(CnstVal, MVT::i32),
5475 DAG.getConstant(16, MVT::i32));
5476 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5479 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5480 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5481 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5482 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5483 DAG.getConstant(CnstVal, MVT::i32),
5484 DAG.getConstant(24, MVT::i32));
5485 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5488 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5489 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5490 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5491 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5492 DAG.getConstant(CnstVal, MVT::i32),
5493 DAG.getConstant(0, MVT::i32));
5494 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5497 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5498 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5499 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5500 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5501 DAG.getConstant(CnstVal, MVT::i32),
5502 DAG.getConstant(8, MVT::i32));
5503 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5506 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5507 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5508 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5509 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5510 DAG.getConstant(CnstVal, MVT::i32),
5511 DAG.getConstant(264, MVT::i32));
5512 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5515 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5516 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5517 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5518 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5519 DAG.getConstant(CnstVal, MVT::i32),
5520 DAG.getConstant(272, MVT::i32));
5521 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5528 CnstBits = UndefBits;
5533 // Scan through the operands to find some interesting properties we can
5535 // 1) If only one value is used, we can use a DUP, or
5536 // 2) if only the low element is not undef, we can just insert that, or
5537 // 3) if only one constant value is used (w/ some non-constant lanes),
5538 // we can splat the constant value into the whole vector then fill
5539 // in the non-constant lanes.
5540 // 4) FIXME: If different constant values are used, but we can intelligently
5541 // select the values we'll be overwriting for the non-constant
5542 // lanes such that we can directly materialize the vector
5543 // some other way (MOVI, e.g.), we can be sneaky.
5544 unsigned NumElts = VT.getVectorNumElements();
5545 bool isOnlyLowElement = true;
5546 bool usesOnlyOneValue = true;
5547 bool usesOnlyOneConstantValue = true;
5548 bool isConstant = true;
5549 unsigned NumConstantLanes = 0;
5551 SDValue ConstantValue;
5552 for (unsigned i = 0; i < NumElts; ++i) {
5553 SDValue V = Op.getOperand(i);
5554 if (V.getOpcode() == ISD::UNDEF)
5557 isOnlyLowElement = false;
5558 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5561 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5563 if (!ConstantValue.getNode())
5565 else if (ConstantValue != V)
5566 usesOnlyOneConstantValue = false;
5569 if (!Value.getNode())
5571 else if (V != Value)
5572 usesOnlyOneValue = false;
5575 if (!Value.getNode())
5576 return DAG.getUNDEF(VT);
5578 if (isOnlyLowElement)
5579 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5581 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5582 // i32 and try again.
5583 if (usesOnlyOneValue) {
5585 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5586 Value.getValueType() != VT)
5587 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5589 // This is actually a DUPLANExx operation, which keeps everything vectory.
5591 // DUPLANE works on 128-bit vectors, widen it if necessary.
5592 SDValue Lane = Value.getOperand(1);
5593 Value = Value.getOperand(0);
5594 if (Value.getValueType().getSizeInBits() == 64)
5595 Value = WidenVector(Value, DAG);
5597 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5598 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5601 if (VT.getVectorElementType().isFloatingPoint()) {
5602 SmallVector<SDValue, 8> Ops;
5604 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5605 for (unsigned i = 0; i < NumElts; ++i)
5606 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5607 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5608 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5609 Val = LowerBUILD_VECTOR(Val, DAG);
5611 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5615 // If there was only one constant value used and for more than one lane,
5616 // start by splatting that value, then replace the non-constant lanes. This
5617 // is better than the default, which will perform a separate initialization
5619 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5620 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
5621 // Now insert the non-constant lanes.
5622 for (unsigned i = 0; i < NumElts; ++i) {
5623 SDValue V = Op.getOperand(i);
5624 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5625 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5626 // Note that type legalization likely mucked about with the VT of the
5627 // source operand, so we may have to convert it here before inserting.
5628 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5634 // If all elements are constants and the case above didn't get hit, fall back
5635 // to the default expansion, which will generate a load from the constant
5640 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5642 SDValue shuffle = ReconstructShuffle(Op, DAG);
5643 if (shuffle != SDValue())
5647 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5648 // know the default expansion would otherwise fall back on something even
5649 // worse. For a vector with one or two non-undef values, that's
5650 // scalar_to_vector for the elements followed by a shuffle (provided the
5651 // shuffle is valid for the target) and materialization element by element
5652 // on the stack followed by a load for everything else.
5653 if (!isConstant && !usesOnlyOneValue) {
5654 SDValue Vec = DAG.getUNDEF(VT);
5655 SDValue Op0 = Op.getOperand(0);
5656 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5658 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5659 // a) Avoid a RMW dependency on the full vector register, and
5660 // b) Allow the register coalescer to fold away the copy if the
5661 // value is already in an S or D register.
5662 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5663 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
5665 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5666 DAG.getTargetConstant(SubIdx, MVT::i32));
5667 Vec = SDValue(N, 0);
5670 for (; i < NumElts; ++i) {
5671 SDValue V = Op.getOperand(i);
5672 if (V.getOpcode() == ISD::UNDEF)
5674 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5675 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5680 // Just use the default expansion. We failed to find a better alternative.
5684 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5685 SelectionDAG &DAG) const {
5686 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5688 // Check for non-constant or out of range lane.
5689 EVT VT = Op.getOperand(0).getValueType();
5690 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
5691 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
5695 // Insertion/extraction are legal for V128 types.
5696 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5697 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5700 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5701 VT != MVT::v1i64 && VT != MVT::v2f32)
5704 // For V64 types, we perform insertion by expanding the value
5705 // to a V128 type and perform the insertion on that.
5707 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5708 EVT WideTy = WideVec.getValueType();
5710 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5711 Op.getOperand(1), Op.getOperand(2));
5712 // Re-narrow the resultant vector.
5713 return NarrowVector(Node, DAG);
5717 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5718 SelectionDAG &DAG) const {
5719 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5721 // Check for non-constant or out of range lane.
5722 EVT VT = Op.getOperand(0).getValueType();
5723 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5724 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
5728 // Insertion/extraction are legal for V128 types.
5729 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5730 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5733 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5734 VT != MVT::v1i64 && VT != MVT::v2f32)
5737 // For V64 types, we perform extraction by expanding the value
5738 // to a V128 type and perform the extraction on that.
5740 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5741 EVT WideTy = WideVec.getValueType();
5743 EVT ExtrTy = WideTy.getVectorElementType();
5744 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5747 // For extractions, we just return the result directly.
5748 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5752 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5753 SelectionDAG &DAG) const {
5754 EVT VT = Op.getOperand(0).getValueType();
5760 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5763 unsigned Val = Cst->getZExtValue();
5765 unsigned Size = Op.getValueType().getSizeInBits();
5769 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
5772 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
5775 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
5778 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
5781 llvm_unreachable("Unexpected vector type in extract_subvector!");
5784 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5786 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5792 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5794 if (VT.getVectorNumElements() == 4 &&
5795 (VT.is128BitVector() || VT.is64BitVector())) {
5796 unsigned PFIndexes[4];
5797 for (unsigned i = 0; i != 4; ++i) {
5801 PFIndexes[i] = M[i];
5804 // Compute the index in the perfect shuffle table.
5805 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5806 PFIndexes[2] * 9 + PFIndexes[3];
5807 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5808 unsigned Cost = (PFEntry >> 30);
5816 unsigned DummyUnsigned;
5818 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5819 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5820 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5821 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5822 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5823 isZIPMask(M, VT, DummyUnsigned) ||
5824 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5825 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5826 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5827 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5828 isConcatMask(M, VT, VT.getSizeInBits() == 128));
5831 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5832 /// operand of a vector shift operation, where all the elements of the
5833 /// build_vector must have the same constant integer value.
5834 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5835 // Ignore bit_converts.
5836 while (Op.getOpcode() == ISD::BITCAST)
5837 Op = Op.getOperand(0);
5838 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5839 APInt SplatBits, SplatUndef;
5840 unsigned SplatBitSize;
5842 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5843 HasAnyUndefs, ElementBits) ||
5844 SplatBitSize > ElementBits)
5846 Cnt = SplatBits.getSExtValue();
5850 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5851 /// operand of a vector shift left operation. That value must be in the range:
5852 /// 0 <= Value < ElementBits for a left shift; or
5853 /// 0 <= Value <= ElementBits for a long left shift.
5854 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5855 assert(VT.isVector() && "vector shift count is not a vector type");
5856 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5857 if (!getVShiftImm(Op, ElementBits, Cnt))
5859 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5862 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5863 /// operand of a vector shift right operation. For a shift opcode, the value
5864 /// is positive, but for an intrinsic the value count must be negative. The
5865 /// absolute value must be in the range:
5866 /// 1 <= |Value| <= ElementBits for a right shift; or
5867 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5868 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5870 assert(VT.isVector() && "vector shift count is not a vector type");
5871 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5872 if (!getVShiftImm(Op, ElementBits, Cnt))
5876 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5879 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5880 SelectionDAG &DAG) const {
5881 EVT VT = Op.getValueType();
5885 if (!Op.getOperand(1).getValueType().isVector())
5887 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5889 switch (Op.getOpcode()) {
5891 llvm_unreachable("unexpected shift opcode");
5894 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5895 return DAG.getNode(AArch64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5896 DAG.getConstant(Cnt, MVT::i32));
5897 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5898 DAG.getConstant(Intrinsic::aarch64_neon_ushl, MVT::i32),
5899 Op.getOperand(0), Op.getOperand(1));
5902 // Right shift immediate
5903 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5906 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
5907 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5908 DAG.getConstant(Cnt, MVT::i32));
5911 // Right shift register. Note, there is not a shift right register
5912 // instruction, but the shift left register instruction takes a signed
5913 // value, where negative numbers specify a right shift.
5914 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
5915 : Intrinsic::aarch64_neon_ushl;
5916 // negate the shift amount
5917 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
5918 SDValue NegShiftLeft =
5919 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5920 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5921 return NegShiftLeft;
5927 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5928 AArch64CC::CondCode CC, bool NoNans, EVT VT,
5929 SDLoc dl, SelectionDAG &DAG) {
5930 EVT SrcVT = LHS.getValueType();
5932 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5933 APInt CnstBits(VT.getSizeInBits(), 0);
5934 APInt UndefBits(VT.getSizeInBits(), 0);
5935 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5936 bool IsZero = IsCnst && (CnstBits == 0);
5938 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5942 case AArch64CC::NE: {
5945 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
5947 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
5948 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
5952 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
5953 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
5956 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
5957 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
5960 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
5961 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
5964 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
5965 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
5969 // If we ignore NaNs then we can use to the MI implementation.
5973 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
5974 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
5981 case AArch64CC::NE: {
5984 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
5986 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
5987 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
5991 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
5992 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
5995 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
5996 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
5999 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6000 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6003 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6004 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6006 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6008 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6011 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6012 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6014 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6016 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6020 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6021 SelectionDAG &DAG) const {
6022 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6023 SDValue LHS = Op.getOperand(0);
6024 SDValue RHS = Op.getOperand(1);
6027 if (LHS.getValueType().getVectorElementType().isInteger()) {
6028 assert(LHS.getValueType() == RHS.getValueType());
6029 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6030 return EmitVectorComparison(LHS, RHS, AArch64CC, false, Op.getValueType(),
6034 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6035 LHS.getValueType().getVectorElementType() == MVT::f64);
6037 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6038 // clean. Some of them require two branches to implement.
6039 AArch64CC::CondCode CC1, CC2;
6041 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6043 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6045 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
6049 if (CC2 != AArch64CC::AL) {
6051 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
6052 if (!Cmp2.getNode())
6055 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
6059 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6064 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6065 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6066 /// specified in the intrinsic calls.
6067 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6069 unsigned Intrinsic) const {
6070 switch (Intrinsic) {
6071 case Intrinsic::aarch64_neon_ld2:
6072 case Intrinsic::aarch64_neon_ld3:
6073 case Intrinsic::aarch64_neon_ld4:
6074 case Intrinsic::aarch64_neon_ld1x2:
6075 case Intrinsic::aarch64_neon_ld1x3:
6076 case Intrinsic::aarch64_neon_ld1x4:
6077 case Intrinsic::aarch64_neon_ld2lane:
6078 case Intrinsic::aarch64_neon_ld3lane:
6079 case Intrinsic::aarch64_neon_ld4lane:
6080 case Intrinsic::aarch64_neon_ld2r:
6081 case Intrinsic::aarch64_neon_ld3r:
6082 case Intrinsic::aarch64_neon_ld4r: {
6083 Info.opc = ISD::INTRINSIC_W_CHAIN;
6084 // Conservatively set memVT to the entire set of vectors loaded.
6085 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6086 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6087 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6090 Info.vol = false; // volatile loads with NEON intrinsics not supported
6091 Info.readMem = true;
6092 Info.writeMem = false;
6095 case Intrinsic::aarch64_neon_st2:
6096 case Intrinsic::aarch64_neon_st3:
6097 case Intrinsic::aarch64_neon_st4:
6098 case Intrinsic::aarch64_neon_st1x2:
6099 case Intrinsic::aarch64_neon_st1x3:
6100 case Intrinsic::aarch64_neon_st1x4:
6101 case Intrinsic::aarch64_neon_st2lane:
6102 case Intrinsic::aarch64_neon_st3lane:
6103 case Intrinsic::aarch64_neon_st4lane: {
6104 Info.opc = ISD::INTRINSIC_VOID;
6105 // Conservatively set memVT to the entire set of vectors stored.
6106 unsigned NumElts = 0;
6107 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6108 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6109 if (!ArgTy->isVectorTy())
6111 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6113 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6114 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6117 Info.vol = false; // volatile stores with NEON intrinsics not supported
6118 Info.readMem = false;
6119 Info.writeMem = true;
6122 case Intrinsic::aarch64_ldaxr:
6123 case Intrinsic::aarch64_ldxr: {
6124 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6125 Info.opc = ISD::INTRINSIC_W_CHAIN;
6126 Info.memVT = MVT::getVT(PtrTy->getElementType());
6127 Info.ptrVal = I.getArgOperand(0);
6129 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6131 Info.readMem = true;
6132 Info.writeMem = false;
6135 case Intrinsic::aarch64_stlxr:
6136 case Intrinsic::aarch64_stxr: {
6137 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6138 Info.opc = ISD::INTRINSIC_W_CHAIN;
6139 Info.memVT = MVT::getVT(PtrTy->getElementType());
6140 Info.ptrVal = I.getArgOperand(1);
6142 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6144 Info.readMem = false;
6145 Info.writeMem = true;
6148 case Intrinsic::aarch64_ldaxp:
6149 case Intrinsic::aarch64_ldxp: {
6150 Info.opc = ISD::INTRINSIC_W_CHAIN;
6151 Info.memVT = MVT::i128;
6152 Info.ptrVal = I.getArgOperand(0);
6156 Info.readMem = true;
6157 Info.writeMem = false;
6160 case Intrinsic::aarch64_stlxp:
6161 case Intrinsic::aarch64_stxp: {
6162 Info.opc = ISD::INTRINSIC_W_CHAIN;
6163 Info.memVT = MVT::i128;
6164 Info.ptrVal = I.getArgOperand(2);
6168 Info.readMem = false;
6169 Info.writeMem = true;
6179 // Truncations from 64-bit GPR to 32-bit GPR is free.
6180 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6181 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6183 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6184 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6185 return NumBits1 > NumBits2;
6187 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6188 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6190 unsigned NumBits1 = VT1.getSizeInBits();
6191 unsigned NumBits2 = VT2.getSizeInBits();
6192 return NumBits1 > NumBits2;
6195 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6197 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6198 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6200 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6201 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6202 return NumBits1 == 32 && NumBits2 == 64;
6204 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6205 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6207 unsigned NumBits1 = VT1.getSizeInBits();
6208 unsigned NumBits2 = VT2.getSizeInBits();
6209 return NumBits1 == 32 && NumBits2 == 64;
6212 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6213 EVT VT1 = Val.getValueType();
6214 if (isZExtFree(VT1, VT2)) {
6218 if (Val.getOpcode() != ISD::LOAD)
6221 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6222 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6223 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6224 VT1.getSizeInBits() <= 32);
6227 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6228 unsigned &RequiredAligment) const {
6229 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6231 // Cyclone supports unaligned accesses.
6232 RequiredAligment = 0;
6233 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6234 return NumBits == 32 || NumBits == 64;
6237 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6238 unsigned &RequiredAligment) const {
6239 if (!LoadedType.isSimple() ||
6240 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6242 // Cyclone supports unaligned accesses.
6243 RequiredAligment = 0;
6244 unsigned NumBits = LoadedType.getSizeInBits();
6245 return NumBits == 32 || NumBits == 64;
6248 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6249 unsigned AlignCheck) {
6250 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6251 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6254 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6255 unsigned SrcAlign, bool IsMemset,
6258 MachineFunction &MF) const {
6259 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6260 // instruction to materialize the v2i64 zero and one store (with restrictive
6261 // addressing mode). Just do two i64 store of zero-registers.
6263 const Function *F = MF.getFunction();
6264 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
6265 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
6266 Attribute::NoImplicitFloat) &&
6267 (memOpAlign(SrcAlign, DstAlign, 16) ||
6268 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
6271 return Size >= 8 ? MVT::i64 : MVT::i32;
6274 // 12-bit optionally shifted immediates are legal for adds.
6275 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6276 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6281 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6282 // immediates is the same as for an add or a sub.
6283 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6286 return isLegalAddImmediate(Immed);
6289 /// isLegalAddressingMode - Return true if the addressing mode represented
6290 /// by AM is legal for this target, for a load/store of the specified type.
6291 bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6293 // AArch64 has five basic addressing modes:
6295 // reg + 9-bit signed offset
6296 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6298 // reg + SIZE_IN_BYTES * reg
6300 // No global is ever allowed as a base.
6304 // No reg+reg+imm addressing.
6305 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6308 // check reg + imm case:
6309 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6310 uint64_t NumBytes = 0;
6311 if (Ty->isSized()) {
6312 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6313 NumBytes = NumBits / 8;
6314 if (!isPowerOf2_64(NumBits))
6319 int64_t Offset = AM.BaseOffs;
6321 // 9-bit signed offset
6322 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6325 // 12-bit unsigned offset
6326 unsigned shift = Log2_64(NumBytes);
6327 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6328 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6329 (Offset >> shift) << shift == Offset)
6334 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6336 if (!AM.Scale || AM.Scale == 1 ||
6337 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6342 int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6344 // Scaling factors are not free at all.
6345 // Operands | Rt Latency
6346 // -------------------------------------------
6348 // -------------------------------------------
6349 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6350 // Rt, [Xn, Wm, <extend> #imm] |
6351 if (isLegalAddressingMode(AM, Ty))
6352 // Scale represents reg2 * scale, thus account for 1 if
6353 // it is not equal to 0 or 1.
6354 return AM.Scale != 0 && AM.Scale != 1;
6358 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6359 VT = VT.getScalarType();
6364 switch (VT.getSimpleVT().SimpleTy) {
6376 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6377 // LR is a callee-save register, but we must treat it as clobbered by any call
6378 // site. Hence we include LR in the scratch registers, which are in turn added
6379 // as implicit-defs for stackmaps and patchpoints.
6380 static const MCPhysReg ScratchRegs[] = {
6381 AArch64::X16, AArch64::X17, AArch64::LR, 0
6387 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6388 EVT VT = N->getValueType(0);
6389 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6390 // it with shift to let it be lowered to UBFX.
6391 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6392 isa<ConstantSDNode>(N->getOperand(1))) {
6393 uint64_t TruncMask = N->getConstantOperandVal(1);
6394 if (isMask_64(TruncMask) &&
6395 N->getOperand(0).getOpcode() == ISD::SRL &&
6396 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6402 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6404 assert(Ty->isIntegerTy());
6406 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6410 int64_t Val = Imm.getSExtValue();
6411 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6414 if ((int64_t)Val < 0)
6417 Val &= (1LL << 32) - 1;
6419 unsigned LZ = countLeadingZeros((uint64_t)Val);
6420 unsigned Shift = (63 - LZ) / 16;
6421 // MOVZ is free so return true for one or fewer MOVK.
6422 return (Shift < 3) ? true : false;
6425 // Generate SUBS and CSEL for integer abs.
6426 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6427 EVT VT = N->getValueType(0);
6429 SDValue N0 = N->getOperand(0);
6430 SDValue N1 = N->getOperand(1);
6433 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6434 // and change it to SUB and CSEL.
6435 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6436 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6437 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6438 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6439 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6440 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6442 // Generate SUBS & CSEL.
6444 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6445 N0.getOperand(0), DAG.getConstant(0, VT));
6446 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6447 DAG.getConstant(AArch64CC::PL, MVT::i32),
6448 SDValue(Cmp.getNode(), 1));
6453 // performXorCombine - Attempts to handle integer ABS.
6454 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6455 TargetLowering::DAGCombinerInfo &DCI,
6456 const AArch64Subtarget *Subtarget) {
6457 if (DCI.isBeforeLegalizeOps())
6460 return performIntegerAbsCombine(N, DAG);
6464 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6466 std::vector<SDNode *> *Created) const {
6467 // fold (sdiv X, pow2)
6468 EVT VT = N->getValueType(0);
6469 if ((VT != MVT::i32 && VT != MVT::i64) ||
6470 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6474 SDValue N0 = N->getOperand(0);
6475 unsigned Lg2 = Divisor.countTrailingZeros();
6476 SDValue Zero = DAG.getConstant(0, VT);
6477 SDValue Pow2MinusOne = DAG.getConstant((1 << Lg2) - 1, VT);
6479 // Add (N0 < 0) ? Pow2 - 1 : 0;
6481 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6482 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6483 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6486 Created->push_back(Cmp.getNode());
6487 Created->push_back(Add.getNode());
6488 Created->push_back(CSel.getNode());
6493 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, MVT::i64));
6495 // If we're dividing by a positive value, we're done. Otherwise, we must
6496 // negate the result.
6497 if (Divisor.isNonNegative())
6501 Created->push_back(SRA.getNode());
6502 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), SRA);
6505 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6506 TargetLowering::DAGCombinerInfo &DCI,
6507 const AArch64Subtarget *Subtarget) {
6508 if (DCI.isBeforeLegalizeOps())
6511 // Multiplication of a power of two plus/minus one can be done more
6512 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6513 // future CPUs have a cheaper MADD instruction, this may need to be
6514 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6515 // 64-bit is 5 cycles, so this is always a win.
6516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6517 APInt Value = C->getAPIntValue();
6518 EVT VT = N->getValueType(0);
6519 if (Value.isNonNegative()) {
6520 // (mul x, 2^N + 1) => (add (shl x, N), x)
6521 APInt VM1 = Value - 1;
6522 if (VM1.isPowerOf2()) {
6523 SDValue ShiftedVal =
6524 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6525 DAG.getConstant(VM1.logBase2(), MVT::i64));
6526 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal,
6529 // (mul x, 2^N - 1) => (sub (shl x, N), x)
6530 APInt VP1 = Value + 1;
6531 if (VP1.isPowerOf2()) {
6532 SDValue ShiftedVal =
6533 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6534 DAG.getConstant(VP1.logBase2(), MVT::i64));
6535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal,
6539 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6540 APInt VNM1 = -Value - 1;
6541 if (VNM1.isPowerOf2()) {
6542 SDValue ShiftedVal =
6543 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6544 DAG.getConstant(VNM1.logBase2(), MVT::i64));
6546 DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6547 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), Add);
6549 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6550 APInt VNP1 = -Value + 1;
6551 if (VNP1.isPowerOf2()) {
6552 SDValue ShiftedVal =
6553 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6554 DAG.getConstant(VNP1.logBase2(), MVT::i64));
6555 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N->getOperand(0),
6563 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
6564 SelectionDAG &DAG) {
6565 // Take advantage of vector comparisons producing 0 or -1 in each lane to
6566 // optimize away operation when it's from a constant.
6568 // The general transformation is:
6569 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
6570 // AND(VECTOR_CMP(x,y), constant2)
6571 // constant2 = UNARYOP(constant)
6573 // Early exit if this isn't a vector operation, the operand of the
6574 // unary operation isn't a bitwise AND, or if the sizes of the operations
6576 EVT VT = N->getValueType(0);
6577 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
6578 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
6579 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
6582 // Now check that the other operand of the AND is a constant. We could
6583 // make the transformation for non-constant splats as well, but it's unclear
6584 // that would be a benefit as it would not eliminate any operations, just
6585 // perform one more step in scalar code before moving to the vector unit.
6586 if (BuildVectorSDNode *BV =
6587 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
6588 // Bail out if the vector isn't a constant.
6589 if (!BV->isConstant())
6592 // Everything checks out. Build up the new and improved node.
6594 EVT IntVT = BV->getValueType(0);
6595 // Create a new constant of the appropriate type for the transformed
6597 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
6598 // The AND node needs bitcasts to/from an integer vector type around it.
6599 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
6600 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
6601 N->getOperand(0)->getOperand(0), MaskConst);
6602 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
6609 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6610 // First try to optimize away the conversion when it's conditionally from
6611 // a constant. Vectors only.
6612 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
6613 if (Res != SDValue())
6616 EVT VT = N->getValueType(0);
6617 if (VT != MVT::f32 && VT != MVT::f64)
6620 // Only optimize when the source and destination types have the same width.
6621 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6624 // If the result of an integer load is only used by an integer-to-float
6625 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6626 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6627 SDValue N0 = N->getOperand(0);
6628 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6629 // Do not change the width of a volatile load.
6630 !cast<LoadSDNode>(N0)->isVolatile()) {
6631 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6632 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6633 LN0->getPointerInfo(), LN0->isVolatile(),
6634 LN0->isNonTemporal(), LN0->isInvariant(),
6635 LN0->getAlignment());
6637 // Make sure successors of the original load stay after it by updating them
6638 // to use the new Chain.
6639 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6642 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
6643 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6649 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6650 /// searches for and classifies those shifts.
6651 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6653 if (N.getOpcode() == ISD::SHL)
6655 else if (N.getOpcode() == ISD::SRL)
6660 if (!isa<ConstantSDNode>(N.getOperand(1)))
6663 ShiftAmount = N->getConstantOperandVal(1);
6664 Src = N->getOperand(0);
6668 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6669 /// registers viewed as a high/low pair. This function looks for the pattern:
6670 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6671 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6673 static SDValue tryCombineToEXTR(SDNode *N,
6674 TargetLowering::DAGCombinerInfo &DCI) {
6675 SelectionDAG &DAG = DCI.DAG;
6677 EVT VT = N->getValueType(0);
6679 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6681 if (VT != MVT::i32 && VT != MVT::i64)
6685 uint32_t ShiftLHS = 0;
6687 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6691 uint32_t ShiftRHS = 0;
6693 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6696 // If they're both trying to come from the high part of the register, they're
6697 // not really an EXTR.
6698 if (LHSFromHi == RHSFromHi)
6701 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6705 std::swap(LHS, RHS);
6706 std::swap(ShiftLHS, ShiftRHS);
6709 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
6710 DAG.getConstant(ShiftRHS, MVT::i64));
6713 static SDValue tryCombineToBSL(SDNode *N,
6714 TargetLowering::DAGCombinerInfo &DCI) {
6715 EVT VT = N->getValueType(0);
6716 SelectionDAG &DAG = DCI.DAG;
6722 SDValue N0 = N->getOperand(0);
6723 if (N0.getOpcode() != ISD::AND)
6726 SDValue N1 = N->getOperand(1);
6727 if (N1.getOpcode() != ISD::AND)
6730 // We only have to look for constant vectors here since the general, variable
6731 // case can be handled in TableGen.
6732 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6733 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6734 for (int i = 1; i >= 0; --i)
6735 for (int j = 1; j >= 0; --j) {
6736 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6737 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6741 bool FoundMatch = true;
6742 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6743 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6744 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6746 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6753 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6754 N0->getOperand(1 - i), N1->getOperand(1 - j));
6760 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6761 const AArch64Subtarget *Subtarget) {
6762 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6763 if (!EnableAArch64ExtrGeneration)
6765 SelectionDAG &DAG = DCI.DAG;
6766 EVT VT = N->getValueType(0);
6768 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6771 SDValue Res = tryCombineToEXTR(N, DCI);
6775 Res = tryCombineToBSL(N, DCI);
6782 static SDValue performBitcastCombine(SDNode *N,
6783 TargetLowering::DAGCombinerInfo &DCI,
6784 SelectionDAG &DAG) {
6785 // Wait 'til after everything is legalized to try this. That way we have
6786 // legal vector types and such.
6787 if (DCI.isBeforeLegalizeOps())
6790 // Remove extraneous bitcasts around an extract_subvector.
6792 // (v4i16 (bitconvert
6793 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6795 // (extract_subvector ((v8i16 ...), (i64 4)))
6797 // Only interested in 64-bit vectors as the ultimate result.
6798 EVT VT = N->getValueType(0);
6801 if (VT.getSimpleVT().getSizeInBits() != 64)
6803 // Is the operand an extract_subvector starting at the beginning or halfway
6804 // point of the vector? A low half may also come through as an
6805 // EXTRACT_SUBREG, so look for that, too.
6806 SDValue Op0 = N->getOperand(0);
6807 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6808 !(Op0->isMachineOpcode() &&
6809 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
6811 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6812 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6813 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6815 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
6816 if (idx != AArch64::dsub)
6818 // The dsub reference is equivalent to a lane zero subvector reference.
6821 // Look through the bitcast of the input to the extract.
6822 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6824 SDValue Source = Op0->getOperand(0)->getOperand(0);
6825 // If the source type has twice the number of elements as our destination
6826 // type, we know this is an extract of the high or low half of the vector.
6827 EVT SVT = Source->getValueType(0);
6828 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6831 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
6833 // Create the simplified form to just extract the low or high half of the
6834 // vector directly rather than bothering with the bitcasts.
6836 unsigned NumElements = VT.getVectorNumElements();
6838 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6839 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6841 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, MVT::i32);
6842 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6848 static SDValue performConcatVectorsCombine(SDNode *N,
6849 TargetLowering::DAGCombinerInfo &DCI,
6850 SelectionDAG &DAG) {
6851 // Wait 'til after everything is legalized to try this. That way we have
6852 // legal vector types and such.
6853 if (DCI.isBeforeLegalizeOps())
6857 EVT VT = N->getValueType(0);
6859 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6860 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6861 // canonicalise to that.
6862 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6863 assert(VT.getVectorElementType().getSizeInBits() == 64);
6864 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT,
6865 WidenVector(N->getOperand(0), DAG),
6866 DAG.getConstant(0, MVT::i64));
6869 // Canonicalise concat_vectors so that the right-hand vector has as few
6870 // bit-casts as possible before its real operation. The primary matching
6871 // destination for these operations will be the narrowing "2" instructions,
6872 // which depend on the operation being performed on this right-hand vector.
6874 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6876 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6878 SDValue Op1 = N->getOperand(1);
6879 if (Op1->getOpcode() != ISD::BITCAST)
6881 SDValue RHS = Op1->getOperand(0);
6882 MVT RHSTy = RHS.getValueType().getSimpleVT();
6883 // If the RHS is not a vector, this is not the pattern we're looking for.
6884 if (!RHSTy.isVector())
6887 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
6889 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6890 RHSTy.getVectorNumElements() * 2);
6892 ISD::BITCAST, dl, VT,
6893 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6894 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6897 static SDValue tryCombineFixedPointConvert(SDNode *N,
6898 TargetLowering::DAGCombinerInfo &DCI,
6899 SelectionDAG &DAG) {
6900 // Wait 'til after everything is legalized to try this. That way we have
6901 // legal vector types and such.
6902 if (DCI.isBeforeLegalizeOps())
6904 // Transform a scalar conversion of a value from a lane extract into a
6905 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6906 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6907 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6909 // The second form interacts better with instruction selection and the
6910 // register allocator to avoid cross-class register copies that aren't
6911 // coalescable due to a lane reference.
6913 // Check the operand and see if it originates from a lane extract.
6914 SDValue Op1 = N->getOperand(1);
6915 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6916 // Yep, no additional predication needed. Perform the transform.
6917 SDValue IID = N->getOperand(0);
6918 SDValue Shift = N->getOperand(2);
6919 SDValue Vec = Op1.getOperand(0);
6920 SDValue Lane = Op1.getOperand(1);
6921 EVT ResTy = N->getValueType(0);
6925 // The vector width should be 128 bits by the time we get here, even
6926 // if it started as 64 bits (the extract_vector handling will have
6928 assert(Vec.getValueType().getSizeInBits() == 128 &&
6929 "unexpected vector size on extract_vector_elt!");
6930 if (Vec.getValueType() == MVT::v4i32)
6931 VecResTy = MVT::v4f32;
6932 else if (Vec.getValueType() == MVT::v2i64)
6933 VecResTy = MVT::v2f64;
6935 llvm_unreachable("unexpected vector type!");
6938 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6944 // AArch64 high-vector "long" operations are formed by performing the non-high
6945 // version on an extract_subvector of each operand which gets the high half:
6947 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6949 // However, there are cases which don't have an extract_high explicitly, but
6950 // have another operation that can be made compatible with one for free. For
6953 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6955 // This routine does the actual conversion of such DUPs, once outer routines
6956 // have determined that everything else is in order.
6957 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6958 // We can handle most types of duplicate, but the lane ones have an extra
6959 // operand saying *which* lane, so we need to know.
6961 switch (N.getOpcode()) {
6962 case AArch64ISD::DUP:
6965 case AArch64ISD::DUPLANE8:
6966 case AArch64ISD::DUPLANE16:
6967 case AArch64ISD::DUPLANE32:
6968 case AArch64ISD::DUPLANE64:
6975 MVT NarrowTy = N.getSimpleValueType();
6976 if (!NarrowTy.is64BitVector())
6979 MVT ElementTy = NarrowTy.getVectorElementType();
6980 unsigned NumElems = NarrowTy.getVectorNumElements();
6981 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6985 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6988 NewDUP = DAG.getNode(AArch64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6990 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6991 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6994 static bool isEssentiallyExtractSubvector(SDValue N) {
6995 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6998 return N.getOpcode() == ISD::BITCAST &&
6999 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7002 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7003 struct GenericSetCCInfo {
7004 const SDValue *Opnd0;
7005 const SDValue *Opnd1;
7009 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7010 struct AArch64SetCCInfo {
7012 AArch64CC::CondCode CC;
7015 /// \brief Helper structure to keep track of SetCC information.
7017 GenericSetCCInfo Generic;
7018 AArch64SetCCInfo AArch64;
7021 /// \brief Helper structure to be able to read SetCC information. If set to
7022 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7023 /// GenericSetCCInfo.
7024 struct SetCCInfoAndKind {
7029 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7031 /// AArch64 lowered one.
7032 /// \p SetCCInfo is filled accordingly.
7033 /// \post SetCCInfo is meanginfull only when this function returns true.
7034 /// \return True when Op is a kind of SET_CC operation.
7035 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7036 // If this is a setcc, this is straight forward.
7037 if (Op.getOpcode() == ISD::SETCC) {
7038 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7039 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7040 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7041 SetCCInfo.IsAArch64 = false;
7044 // Otherwise, check if this is a matching csel instruction.
7048 if (Op.getOpcode() != AArch64ISD::CSEL)
7050 // Set the information about the operands.
7051 // TODO: we want the operands of the Cmp not the csel
7052 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7053 SetCCInfo.IsAArch64 = true;
7054 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7055 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7057 // Check that the operands matches the constraints:
7058 // (1) Both operands must be constants.
7059 // (2) One must be 1 and the other must be 0.
7060 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7061 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7064 if (!TValue || !FValue)
7068 if (!TValue->isOne()) {
7069 // Update the comparison when we are interested in !cc.
7070 std::swap(TValue, FValue);
7071 SetCCInfo.Info.AArch64.CC =
7072 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7074 return TValue->isOne() && FValue->isNullValue();
7077 // Returns true if Op is setcc or zext of setcc.
7078 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7079 if (isSetCC(Op, Info))
7081 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7082 isSetCC(Op->getOperand(0), Info));
7085 // The folding we want to perform is:
7086 // (add x, [zext] (setcc cc ...) )
7088 // (csel x, (add x, 1), !cc ...)
7090 // The latter will get matched to a CSINC instruction.
7091 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7092 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7093 SDValue LHS = Op->getOperand(0);
7094 SDValue RHS = Op->getOperand(1);
7095 SetCCInfoAndKind InfoAndKind;
7097 // If neither operand is a SET_CC, give up.
7098 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7099 std::swap(LHS, RHS);
7100 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7104 // FIXME: This could be generatized to work for FP comparisons.
7105 EVT CmpVT = InfoAndKind.IsAArch64
7106 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7107 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7108 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7114 if (InfoAndKind.IsAArch64) {
7115 CCVal = DAG.getConstant(
7116 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), MVT::i32);
7117 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7119 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7120 *InfoAndKind.Info.Generic.Opnd1,
7121 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7124 EVT VT = Op->getValueType(0);
7125 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
7126 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7129 // The basic add/sub long vector instructions have variants with "2" on the end
7130 // which act on the high-half of their inputs. They are normally matched by
7133 // (add (zeroext (extract_high LHS)),
7134 // (zeroext (extract_high RHS)))
7135 // -> uaddl2 vD, vN, vM
7137 // However, if one of the extracts is something like a duplicate, this
7138 // instruction can still be used profitably. This function puts the DAG into a
7139 // more appropriate form for those patterns to trigger.
7140 static SDValue performAddSubLongCombine(SDNode *N,
7141 TargetLowering::DAGCombinerInfo &DCI,
7142 SelectionDAG &DAG) {
7143 if (DCI.isBeforeLegalizeOps())
7146 MVT VT = N->getSimpleValueType(0);
7147 if (!VT.is128BitVector()) {
7148 if (N->getOpcode() == ISD::ADD)
7149 return performSetccAddFolding(N, DAG);
7153 // Make sure both branches are extended in the same way.
7154 SDValue LHS = N->getOperand(0);
7155 SDValue RHS = N->getOperand(1);
7156 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7157 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7158 LHS.getOpcode() != RHS.getOpcode())
7161 unsigned ExtType = LHS.getOpcode();
7163 // It's not worth doing if at least one of the inputs isn't already an
7164 // extract, but we don't know which it'll be so we have to try both.
7165 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7166 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7170 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7171 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7172 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7176 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7179 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7182 // Massage DAGs which we can use the high-half "long" operations on into
7183 // something isel will recognize better. E.g.
7185 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7186 // (aarch64_neon_umull (extract_high (v2i64 vec)))
7187 // (extract_high (v2i64 (dup128 scalar)))))
7189 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7190 TargetLowering::DAGCombinerInfo &DCI,
7191 SelectionDAG &DAG) {
7192 if (DCI.isBeforeLegalizeOps())
7195 SDValue LHS = N->getOperand(1);
7196 SDValue RHS = N->getOperand(2);
7197 assert(LHS.getValueType().is64BitVector() &&
7198 RHS.getValueType().is64BitVector() &&
7199 "unexpected shape for long operation");
7201 // Either node could be a DUP, but it's not worth doing both of them (you'd
7202 // just as well use the non-high version) so look for a corresponding extract
7203 // operation on the other "wing".
7204 if (isEssentiallyExtractSubvector(LHS)) {
7205 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7208 } else if (isEssentiallyExtractSubvector(RHS)) {
7209 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7214 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7215 N->getOperand(0), LHS, RHS);
7218 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7219 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7220 unsigned ElemBits = ElemTy.getSizeInBits();
7222 int64_t ShiftAmount;
7223 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7224 APInt SplatValue, SplatUndef;
7225 unsigned SplatBitSize;
7227 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7228 HasAnyUndefs, ElemBits) ||
7229 SplatBitSize != ElemBits)
7232 ShiftAmount = SplatValue.getSExtValue();
7233 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7234 ShiftAmount = CVN->getSExtValue();
7242 llvm_unreachable("Unknown shift intrinsic");
7243 case Intrinsic::aarch64_neon_sqshl:
7244 Opcode = AArch64ISD::SQSHL_I;
7245 IsRightShift = false;
7247 case Intrinsic::aarch64_neon_uqshl:
7248 Opcode = AArch64ISD::UQSHL_I;
7249 IsRightShift = false;
7251 case Intrinsic::aarch64_neon_srshl:
7252 Opcode = AArch64ISD::SRSHR_I;
7253 IsRightShift = true;
7255 case Intrinsic::aarch64_neon_urshl:
7256 Opcode = AArch64ISD::URSHR_I;
7257 IsRightShift = true;
7259 case Intrinsic::aarch64_neon_sqshlu:
7260 Opcode = AArch64ISD::SQSHLU_I;
7261 IsRightShift = false;
7265 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
7266 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7267 DAG.getConstant(-ShiftAmount, MVT::i32));
7268 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits)
7269 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7270 DAG.getConstant(ShiftAmount, MVT::i32));
7275 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
7276 // the intrinsics must be legal and take an i32, this means there's almost
7277 // certainly going to be a zext in the DAG which we can eliminate.
7278 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7279 SDValue AndN = N->getOperand(2);
7280 if (AndN.getOpcode() != ISD::AND)
7283 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7284 if (!CMask || CMask->getZExtValue() != Mask)
7287 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7288 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7291 static SDValue performIntrinsicCombine(SDNode *N,
7292 TargetLowering::DAGCombinerInfo &DCI,
7293 const AArch64Subtarget *Subtarget) {
7294 SelectionDAG &DAG = DCI.DAG;
7295 unsigned IID = getIntrinsicID(N);
7299 case Intrinsic::aarch64_neon_vcvtfxs2fp:
7300 case Intrinsic::aarch64_neon_vcvtfxu2fp:
7301 return tryCombineFixedPointConvert(N, DCI, DAG);
7303 case Intrinsic::aarch64_neon_fmax:
7304 return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7305 N->getOperand(1), N->getOperand(2));
7306 case Intrinsic::aarch64_neon_fmin:
7307 return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7308 N->getOperand(1), N->getOperand(2));
7309 case Intrinsic::aarch64_neon_smull:
7310 case Intrinsic::aarch64_neon_umull:
7311 case Intrinsic::aarch64_neon_pmull:
7312 case Intrinsic::aarch64_neon_sqdmull:
7313 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7314 case Intrinsic::aarch64_neon_sqshl:
7315 case Intrinsic::aarch64_neon_uqshl:
7316 case Intrinsic::aarch64_neon_sqshlu:
7317 case Intrinsic::aarch64_neon_srshl:
7318 case Intrinsic::aarch64_neon_urshl:
7319 return tryCombineShiftImm(IID, N, DAG);
7320 case Intrinsic::aarch64_crc32b:
7321 case Intrinsic::aarch64_crc32cb:
7322 return tryCombineCRC32(0xff, N, DAG);
7323 case Intrinsic::aarch64_crc32h:
7324 case Intrinsic::aarch64_crc32ch:
7325 return tryCombineCRC32(0xffff, N, DAG);
7330 static SDValue performExtendCombine(SDNode *N,
7331 TargetLowering::DAGCombinerInfo &DCI,
7332 SelectionDAG &DAG) {
7333 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7334 // we can convert that DUP into another extract_high (of a bigger DUP), which
7335 // helps the backend to decide that an sabdl2 would be useful, saving a real
7336 // extract_high operation.
7337 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7338 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7339 SDNode *ABDNode = N->getOperand(0).getNode();
7340 unsigned IID = getIntrinsicID(ABDNode);
7341 if (IID == Intrinsic::aarch64_neon_sabd ||
7342 IID == Intrinsic::aarch64_neon_uabd) {
7343 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7344 if (!NewABD.getNode())
7347 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7352 // This is effectively a custom type legalization for AArch64.
7354 // Type legalization will split an extend of a small, legal, type to a larger
7355 // illegal type by first splitting the destination type, often creating
7356 // illegal source types, which then get legalized in isel-confusing ways,
7357 // leading to really terrible codegen. E.g.,
7358 // %result = v8i32 sext v8i8 %value
7360 // %losrc = extract_subreg %value, ...
7361 // %hisrc = extract_subreg %value, ...
7362 // %lo = v4i32 sext v4i8 %losrc
7363 // %hi = v4i32 sext v4i8 %hisrc
7364 // Things go rapidly downhill from there.
7366 // For AArch64, the [sz]ext vector instructions can only go up one element
7367 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7368 // take two instructions.
7370 // This implies that the most efficient way to do the extend from v8i8
7371 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7372 // the normal splitting to happen for the v8i16->v8i32.
7374 // This is pre-legalization to catch some cases where the default
7375 // type legalization will create ill-tempered code.
7376 if (!DCI.isBeforeLegalizeOps())
7379 // We're only interested in cleaning things up for non-legal vector types
7380 // here. If both the source and destination are legal, things will just
7381 // work naturally without any fiddling.
7382 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7383 EVT ResVT = N->getValueType(0);
7384 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7386 // If the vector type isn't a simple VT, it's beyond the scope of what
7387 // we're worried about here. Let legalization do its thing and hope for
7389 if (!ResVT.isSimple())
7392 SDValue Src = N->getOperand(0);
7393 MVT SrcVT = Src->getValueType(0).getSimpleVT();
7394 // If the source VT is a 64-bit vector, we can play games and get the
7395 // better results we want.
7396 if (SrcVT.getSizeInBits() != 64)
7399 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7400 unsigned ElementCount = SrcVT.getVectorNumElements();
7401 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7403 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7405 // Now split the rest of the operation into two halves, each with a 64
7409 unsigned NumElements = ResVT.getVectorNumElements();
7410 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7411 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7412 ResVT.getVectorElementType(), NumElements / 2);
7414 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7415 LoVT.getVectorNumElements());
7416 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7417 DAG.getIntPtrConstant(0));
7418 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7419 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
7420 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7421 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7423 // Now combine the parts back together so we still have a single result
7424 // like the combiner expects.
7425 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7428 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7429 /// value. The load store optimizer pass will merge them to store pair stores.
7430 /// This has better performance than a splat of the scalar followed by a split
7431 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7432 /// followed by an ext.b and two stores.
7433 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7434 SDValue StVal = St->getValue();
7435 EVT VT = StVal.getValueType();
7437 // Don't replace floating point stores, they possibly won't be transformed to
7438 // stp because of the store pair suppress pass.
7439 if (VT.isFloatingPoint())
7442 // Check for insert vector elements.
7443 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7446 // We can express a splat as store pair(s) for 2 or 4 elements.
7447 unsigned NumVecElts = VT.getVectorNumElements();
7448 if (NumVecElts != 4 && NumVecElts != 2)
7450 SDValue SplatVal = StVal.getOperand(1);
7451 unsigned RemainInsertElts = NumVecElts - 1;
7453 // Check that this is a splat.
7454 while (--RemainInsertElts) {
7455 SDValue NextInsertElt = StVal.getOperand(0);
7456 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7458 if (NextInsertElt.getOperand(1) != SplatVal)
7460 StVal = NextInsertElt;
7462 unsigned OrigAlignment = St->getAlignment();
7463 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7464 unsigned Alignment = std::min(OrigAlignment, EltOffset);
7466 // Create scalar stores. This is at least as good as the code sequence for a
7467 // split unaligned store wich is a dup.s, ext.b, and two stores.
7468 // Most of the time the three stores should be replaced by store pair
7469 // instructions (stp).
7471 SDValue BasePtr = St->getBasePtr();
7473 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7474 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7476 unsigned Offset = EltOffset;
7477 while (--NumVecElts) {
7478 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7479 DAG.getConstant(Offset, MVT::i64));
7480 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7481 St->getPointerInfo(), St->isVolatile(),
7482 St->isNonTemporal(), Alignment);
7483 Offset += EltOffset;
7488 static SDValue performSTORECombine(SDNode *N,
7489 TargetLowering::DAGCombinerInfo &DCI,
7491 const AArch64Subtarget *Subtarget) {
7492 if (!DCI.isBeforeLegalize())
7495 StoreSDNode *S = cast<StoreSDNode>(N);
7496 if (S->isVolatile())
7499 // Cyclone has bad performance on unaligned 16B stores when crossing line and
7500 // page boundries. We want to split such stores.
7501 if (!Subtarget->isCyclone())
7504 // Don't split at Oz.
7505 MachineFunction &MF = DAG.getMachineFunction();
7506 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7507 AttributeSet::FunctionIndex, Attribute::MinSize);
7511 SDValue StVal = S->getValue();
7512 EVT VT = StVal.getValueType();
7514 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7515 // those up regresses performance on micro-benchmarks and olden/bh.
7516 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7519 // Split unaligned 16B stores. They are terrible for performance.
7520 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7521 // extensions can use this to mark that it does not want splitting to happen
7522 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7523 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7524 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7525 S->getAlignment() <= 2)
7528 // If we get a splat of a scalar convert this vector store to a store of
7529 // scalars. They will be merged into store pairs thereby removing two
7531 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7532 if (ReplacedSplat != SDValue())
7533 return ReplacedSplat;
7536 unsigned NumElts = VT.getVectorNumElements() / 2;
7537 // Split VT into two.
7539 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7540 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7541 DAG.getIntPtrConstant(0));
7542 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7543 DAG.getIntPtrConstant(NumElts));
7544 SDValue BasePtr = S->getBasePtr();
7546 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7547 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7548 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7549 DAG.getConstant(8, MVT::i64));
7550 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7551 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7555 /// Target-specific DAG combine function for post-increment LD1 (lane) and
7556 /// post-increment LD1R.
7557 static SDValue performPostLD1Combine(SDNode *N,
7558 TargetLowering::DAGCombinerInfo &DCI,
7560 if (DCI.isBeforeLegalizeOps())
7563 SelectionDAG &DAG = DCI.DAG;
7564 EVT VT = N->getValueType(0);
7566 unsigned LoadIdx = IsLaneOp ? 1 : 0;
7567 SDNode *LD = N->getOperand(LoadIdx).getNode();
7568 // If it is not LOAD, can not do such combine.
7569 if (LD->getOpcode() != ISD::LOAD)
7572 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
7573 EVT MemVT = LoadSDN->getMemoryVT();
7574 // Check if memory operand is the same type as the vector element.
7575 if (MemVT != VT.getVectorElementType())
7578 // Check if there are other uses. If so, do not combine as it will introduce
7580 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
7582 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
7588 SDValue Addr = LD->getOperand(1);
7589 SDValue Vector = N->getOperand(0);
7590 // Search for a use of the address operand that is an increment.
7591 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
7592 Addr.getNode()->use_end(); UI != UE; ++UI) {
7594 if (User->getOpcode() != ISD::ADD
7595 || UI.getUse().getResNo() != Addr.getResNo())
7598 // Check that the add is independent of the load. Otherwise, folding it
7599 // would create a cycle.
7600 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
7602 // Also check that add is not used in the vector operand. This would also
7604 if (User->isPredecessorOf(Vector.getNode()))
7607 // If the increment is a constant, it must match the memory ref size.
7608 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7609 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7610 uint32_t IncVal = CInc->getZExtValue();
7611 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
7612 if (IncVal != NumBytes)
7614 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7617 SmallVector<SDValue, 8> Ops;
7618 Ops.push_back(LD->getOperand(0)); // Chain
7620 Ops.push_back(Vector); // The vector to be inserted
7621 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
7623 Ops.push_back(Addr);
7626 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
7627 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, 3));
7628 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
7629 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
7631 LoadSDN->getMemOperand());
7634 std::vector<SDValue> NewResults;
7635 NewResults.push_back(SDValue(LD, 0)); // The result of load
7636 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
7637 DCI.CombineTo(LD, NewResults);
7638 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
7639 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
7646 /// Target-specific DAG combine function for NEON load/store intrinsics
7647 /// to merge base address updates.
7648 static SDValue performNEONPostLDSTCombine(SDNode *N,
7649 TargetLowering::DAGCombinerInfo &DCI,
7650 SelectionDAG &DAG) {
7651 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7654 unsigned AddrOpIdx = N->getNumOperands() - 1;
7655 SDValue Addr = N->getOperand(AddrOpIdx);
7657 // Search for a use of the address operand that is an increment.
7658 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7659 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7661 if (User->getOpcode() != ISD::ADD ||
7662 UI.getUse().getResNo() != Addr.getResNo())
7665 // Check that the add is independent of the load/store. Otherwise, folding
7666 // it would create a cycle.
7667 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7670 // Find the new opcode for the updating load/store.
7671 bool IsStore = false;
7672 bool IsLaneOp = false;
7673 bool IsDupOp = false;
7674 unsigned NewOpc = 0;
7675 unsigned NumVecs = 0;
7676 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7678 default: llvm_unreachable("unexpected intrinsic for Neon base update");
7679 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
7681 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
7683 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
7685 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
7686 NumVecs = 2; IsStore = true; break;
7687 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
7688 NumVecs = 3; IsStore = true; break;
7689 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
7690 NumVecs = 4; IsStore = true; break;
7691 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
7693 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
7695 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
7697 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
7698 NumVecs = 2; IsStore = true; break;
7699 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
7700 NumVecs = 3; IsStore = true; break;
7701 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
7702 NumVecs = 4; IsStore = true; break;
7703 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
7704 NumVecs = 2; IsDupOp = true; break;
7705 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
7706 NumVecs = 3; IsDupOp = true; break;
7707 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
7708 NumVecs = 4; IsDupOp = true; break;
7709 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
7710 NumVecs = 2; IsLaneOp = true; break;
7711 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
7712 NumVecs = 3; IsLaneOp = true; break;
7713 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
7714 NumVecs = 4; IsLaneOp = true; break;
7715 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
7716 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
7717 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
7718 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
7719 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
7720 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
7725 VecTy = N->getOperand(2).getValueType();
7727 VecTy = N->getValueType(0);
7729 // If the increment is a constant, it must match the memory ref size.
7730 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7731 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7732 uint32_t IncVal = CInc->getZExtValue();
7733 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7734 if (IsLaneOp || IsDupOp)
7735 NumBytes /= VecTy.getVectorNumElements();
7736 if (IncVal != NumBytes)
7738 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7740 SmallVector<SDValue, 8> Ops;
7741 Ops.push_back(N->getOperand(0)); // Incoming chain
7742 // Load lane and store have vector list as input.
7743 if (IsLaneOp || IsStore)
7744 for (unsigned i = 2; i < AddrOpIdx; ++i)
7745 Ops.push_back(N->getOperand(i));
7746 Ops.push_back(Addr); // Base register
7751 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
7753 for (n = 0; n < NumResultVecs; ++n)
7755 Tys[n++] = MVT::i64; // Type of write back register
7756 Tys[n] = MVT::Other; // Type of the chain
7757 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs + 2));
7759 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7760 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
7761 MemInt->getMemoryVT(),
7762 MemInt->getMemOperand());
7765 std::vector<SDValue> NewResults;
7766 for (unsigned i = 0; i < NumResultVecs; ++i) {
7767 NewResults.push_back(SDValue(UpdN.getNode(), i));
7769 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
7770 DCI.CombineTo(N, NewResults);
7771 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7778 // Optimize compare with zero and branch.
7779 static SDValue performBRCONDCombine(SDNode *N,
7780 TargetLowering::DAGCombinerInfo &DCI,
7781 SelectionDAG &DAG) {
7782 SDValue Chain = N->getOperand(0);
7783 SDValue Dest = N->getOperand(1);
7784 SDValue CCVal = N->getOperand(2);
7785 SDValue Cmp = N->getOperand(3);
7787 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7788 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7789 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
7792 unsigned CmpOpc = Cmp.getOpcode();
7793 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
7796 // Only attempt folding if there is only one use of the flag and no use of the
7798 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7801 SDValue LHS = Cmp.getOperand(0);
7802 SDValue RHS = Cmp.getOperand(1);
7804 assert(LHS.getValueType() == RHS.getValueType() &&
7805 "Expected the value type to be the same for both operands!");
7806 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7809 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7810 std::swap(LHS, RHS);
7812 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7815 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7816 LHS.getOpcode() == ISD::SRL)
7819 // Fold the compare into the branch instruction.
7821 if (CC == AArch64CC::EQ)
7822 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7824 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7826 // Do not add new nodes to DAG combiner worklist.
7827 DCI.CombineTo(N, BR, false);
7832 // vselect (v1i1 setcc) ->
7833 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
7834 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7835 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7837 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7838 SDValue N0 = N->getOperand(0);
7839 EVT CCVT = N0.getValueType();
7841 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7842 CCVT.getVectorElementType() != MVT::i1)
7845 EVT ResVT = N->getValueType(0);
7846 EVT CmpVT = N0.getOperand(0).getValueType();
7847 // Only combine when the result type is of the same size as the compared
7849 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7852 SDValue IfTrue = N->getOperand(1);
7853 SDValue IfFalse = N->getOperand(2);
7855 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7856 N0.getOperand(0), N0.getOperand(1),
7857 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7858 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7862 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
7863 /// the compare-mask instructions rather than going via NZCV, even if LHS and
7864 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
7865 /// with a vector one followed by a DUP shuffle on the result.
7866 static SDValue performSelectCombine(SDNode *N, SelectionDAG &DAG) {
7867 SDValue N0 = N->getOperand(0);
7868 EVT ResVT = N->getValueType(0);
7870 if (!N->getOperand(1).getValueType().isVector())
7873 if (N0.getOpcode() != ISD::SETCC || N0.getValueType() != MVT::i1)
7878 EVT SrcVT = N0.getOperand(0).getValueType();
7879 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT,
7880 ResVT.getSizeInBits() / SrcVT.getSizeInBits());
7881 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
7883 // First perform a vector comparison, where lane 0 is the one we're interested
7886 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
7888 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
7889 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
7891 // Now duplicate the comparison mask we want across all other lanes.
7892 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
7893 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
7894 Mask = DAG.getNode(ISD::BITCAST, DL, ResVT.changeVectorElementTypeToInteger(),
7897 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
7900 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
7901 DAGCombinerInfo &DCI) const {
7902 SelectionDAG &DAG = DCI.DAG;
7903 switch (N->getOpcode()) {
7908 return performAddSubLongCombine(N, DCI, DAG);
7910 return performXorCombine(N, DAG, DCI, Subtarget);
7912 return performMulCombine(N, DAG, DCI, Subtarget);
7913 case ISD::SINT_TO_FP:
7914 case ISD::UINT_TO_FP:
7915 return performIntToFpCombine(N, DAG);
7917 return performORCombine(N, DCI, Subtarget);
7918 case ISD::INTRINSIC_WO_CHAIN:
7919 return performIntrinsicCombine(N, DCI, Subtarget);
7920 case ISD::ANY_EXTEND:
7921 case ISD::ZERO_EXTEND:
7922 case ISD::SIGN_EXTEND:
7923 return performExtendCombine(N, DCI, DAG);
7925 return performBitcastCombine(N, DCI, DAG);
7926 case ISD::CONCAT_VECTORS:
7927 return performConcatVectorsCombine(N, DCI, DAG);
7929 return performSelectCombine(N, DAG);
7931 return performVSelectCombine(N, DCI.DAG);
7933 return performSTORECombine(N, DCI, DAG, Subtarget);
7934 case AArch64ISD::BRCOND:
7935 return performBRCONDCombine(N, DCI, DAG);
7936 case AArch64ISD::DUP:
7937 return performPostLD1Combine(N, DCI, false);
7938 case ISD::INSERT_VECTOR_ELT:
7939 return performPostLD1Combine(N, DCI, true);
7940 case ISD::INTRINSIC_VOID:
7941 case ISD::INTRINSIC_W_CHAIN:
7942 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7943 case Intrinsic::aarch64_neon_ld2:
7944 case Intrinsic::aarch64_neon_ld3:
7945 case Intrinsic::aarch64_neon_ld4:
7946 case Intrinsic::aarch64_neon_ld1x2:
7947 case Intrinsic::aarch64_neon_ld1x3:
7948 case Intrinsic::aarch64_neon_ld1x4:
7949 case Intrinsic::aarch64_neon_ld2lane:
7950 case Intrinsic::aarch64_neon_ld3lane:
7951 case Intrinsic::aarch64_neon_ld4lane:
7952 case Intrinsic::aarch64_neon_ld2r:
7953 case Intrinsic::aarch64_neon_ld3r:
7954 case Intrinsic::aarch64_neon_ld4r:
7955 case Intrinsic::aarch64_neon_st2:
7956 case Intrinsic::aarch64_neon_st3:
7957 case Intrinsic::aarch64_neon_st4:
7958 case Intrinsic::aarch64_neon_st1x2:
7959 case Intrinsic::aarch64_neon_st1x3:
7960 case Intrinsic::aarch64_neon_st1x4:
7961 case Intrinsic::aarch64_neon_st2lane:
7962 case Intrinsic::aarch64_neon_st3lane:
7963 case Intrinsic::aarch64_neon_st4lane:
7964 return performNEONPostLDSTCombine(N, DCI, DAG);
7972 // Check if the return value is used as only a return value, as otherwise
7973 // we can't perform a tail-call. In particular, we need to check for
7974 // target ISD nodes that are returns and any other "odd" constructs
7975 // that the generic analysis code won't necessarily catch.
7976 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
7977 SDValue &Chain) const {
7978 if (N->getNumValues() != 1)
7980 if (!N->hasNUsesOfValue(1, 0))
7983 SDValue TCChain = Chain;
7984 SDNode *Copy = *N->use_begin();
7985 if (Copy->getOpcode() == ISD::CopyToReg) {
7986 // If the copy has a glue operand, we conservatively assume it isn't safe to
7987 // perform a tail call.
7988 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7991 TCChain = Copy->getOperand(0);
7992 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7995 bool HasRet = false;
7996 for (SDNode *Node : Copy->uses()) {
7997 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
8009 // Return whether the an instruction can potentially be optimized to a tail
8010 // call. This will cause the optimizers to attempt to move, or duplicate,
8011 // return instructions to help enable tail call optimizations for this
8013 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
8014 if (!CI->isTailCall())
8020 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
8022 ISD::MemIndexedMode &AM,
8024 SelectionDAG &DAG) const {
8025 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8028 Base = Op->getOperand(0);
8029 // All of the indexed addressing mode instructions take a signed
8030 // 9 bit immediate offset.
8031 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8032 int64_t RHSC = (int64_t)RHS->getZExtValue();
8033 if (RHSC >= 256 || RHSC <= -256)
8035 IsInc = (Op->getOpcode() == ISD::ADD);
8036 Offset = Op->getOperand(1);
8042 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8044 ISD::MemIndexedMode &AM,
8045 SelectionDAG &DAG) const {
8048 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8049 VT = LD->getMemoryVT();
8050 Ptr = LD->getBasePtr();
8051 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8052 VT = ST->getMemoryVT();
8053 Ptr = ST->getBasePtr();
8058 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8060 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8064 bool AArch64TargetLowering::getPostIndexedAddressParts(
8065 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8066 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8069 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8070 VT = LD->getMemoryVT();
8071 Ptr = LD->getBasePtr();
8072 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8073 VT = ST->getMemoryVT();
8074 Ptr = ST->getBasePtr();
8079 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8081 // Post-indexing updates the base, so it's not a valid transform
8082 // if that's not the same as the load's pointer.
8085 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8089 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8090 SelectionDAG &DAG) {
8091 if (N->getValueType(0) != MVT::i16)
8095 SDValue Op = N->getOperand(0);
8096 assert(Op.getValueType() == MVT::f16 &&
8097 "Inconsistent bitcast? Only 16-bit types should be i16 or f16");
8099 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8100 DAG.getUNDEF(MVT::i32), Op,
8101 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
8103 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8104 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8107 void AArch64TargetLowering::ReplaceNodeResults(
8108 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8109 switch (N->getOpcode()) {
8111 llvm_unreachable("Don't know how to custom expand this");
8113 ReplaceBITCASTResults(N, Results, DAG);
8115 case ISD::FP_TO_UINT:
8116 case ISD::FP_TO_SINT:
8117 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8118 // Let normal code take care of it by not adding anything to Results.
8123 bool AArch64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
8124 // Loads and stores less than 128-bits are already atomic; ones above that
8125 // are doomed anyway, so defer to the default libcall and blame the OS when
8127 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
8128 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
8129 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
8130 return LI->getType()->getPrimitiveSizeInBits() == 128;
8132 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
8133 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
8136 bool AArch64TargetLowering::useLoadStackGuardNode() const {
8140 TargetLoweringBase::LegalizeTypeAction
8141 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8142 MVT SVT = VT.getSimpleVT();
8143 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
8144 // v4i16, v2i32 instead of to promote.
8145 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8146 || SVT == MVT::v1f32)
8147 return TypeWidenVector;
8149 return TargetLoweringBase::getPreferredVectorAction(VT);
8152 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
8153 AtomicOrdering Ord) const {
8154 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8155 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
8157 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
8159 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
8160 // intrinsic must return {i64, i64} and we have to recombine them into a
8161 // single i128 here.
8162 if (ValTy->getPrimitiveSizeInBits() == 128) {
8164 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
8165 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
8167 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8168 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
8170 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
8171 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
8172 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
8173 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
8174 return Builder.CreateOr(
8175 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
8178 Type *Tys[] = { Addr->getType() };
8180 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
8181 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
8183 return Builder.CreateTruncOrBitCast(
8184 Builder.CreateCall(Ldxr, Addr),
8185 cast<PointerType>(Addr->getType())->getElementType());
8188 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
8189 Value *Val, Value *Addr,
8190 AtomicOrdering Ord) const {
8191 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8193 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
8195 // Since the intrinsics must have legal type, the i128 intrinsics take two
8196 // parameters: "i64, i64". We must marshal Val into the appropriate form
8198 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
8200 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
8201 Function *Stxr = Intrinsic::getDeclaration(M, Int);
8202 Type *Int64Ty = Type::getInt64Ty(M->getContext());
8204 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
8205 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
8206 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8207 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
8211 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
8212 Type *Tys[] = { Addr->getType() };
8213 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
8215 return Builder.CreateCall2(
8216 Stxr, Builder.CreateZExtOrBitCast(
8217 Val, Stxr->getFunctionType()->getParamType(0)),