1 //===-- ARM64ISelLowering.cpp - ARM64 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 ARM64TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARM64ISelLowering.h"
15 #include "ARM64PerfectShuffle.h"
16 #include "ARM64Subtarget.h"
17 #include "ARM64CallingConv.h"
18 #include "ARM64MachineFunctionInfo.h"
19 #include "ARM64TargetMachine.h"
20 #include "ARM64TargetObjectFile.h"
21 #include "MCTargetDesc/ARM64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetOptions.h"
37 #define DEBUG_TYPE "arm64-lower"
39 STATISTIC(NumTailCalls, "Number of tail calls");
40 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42 // This option should go away when tail calls fully work.
44 EnableARM64TailCalls("arm64-tail-calls", cl::Hidden,
45 cl::desc("Generate ARM64 tail calls (TEMPORARY OPTION)."),
53 static cl::opt<AlignMode>
54 Align(cl::desc("Load/store alignment support"),
55 cl::Hidden, cl::init(NoStrictAlign),
57 clEnumValN(StrictAlign, "arm64-strict-align",
58 "Disallow all unaligned memory accesses"),
59 clEnumValN(NoStrictAlign, "arm64-no-strict-align",
60 "Allow unaligned memory accesses"),
63 // Place holder until extr generation is tested fully.
65 EnableARM64ExtrGeneration("arm64-extr-generation", cl::Hidden,
66 cl::desc("Allow ARM64 (or (shift)(shift))->extract"),
70 EnableARM64SlrGeneration("arm64-shift-insert-generation", cl::Hidden,
71 cl::desc("Allow ARM64 SLI/SRI formation"),
74 //===----------------------------------------------------------------------===//
75 // ARM64 Lowering public interface.
76 //===----------------------------------------------------------------------===//
77 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
78 if (TM.getSubtarget<ARM64Subtarget>().isTargetDarwin())
79 return new ARM64_MachoTargetObjectFile();
81 return new ARM64_ELFTargetObjectFile();
84 ARM64TargetLowering::ARM64TargetLowering(ARM64TargetMachine &TM)
85 : TargetLowering(TM, createTLOF(TM)) {
86 Subtarget = &TM.getSubtarget<ARM64Subtarget>();
88 // ARM64 doesn't have comparisons which set GPRs or setcc instructions, so
89 // we have to make something up. Arbitrarily, choose ZeroOrOne.
90 setBooleanContents(ZeroOrOneBooleanContent);
91 // When comparing vectors the result sets the different elements in the
92 // vector to all-one or all-zero.
93 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
95 // Set up the register classes.
96 addRegisterClass(MVT::i32, &ARM64::GPR32allRegClass);
97 addRegisterClass(MVT::i64, &ARM64::GPR64allRegClass);
99 if (Subtarget->hasFPARMv8()) {
100 addRegisterClass(MVT::f16, &ARM64::FPR16RegClass);
101 addRegisterClass(MVT::f32, &ARM64::FPR32RegClass);
102 addRegisterClass(MVT::f64, &ARM64::FPR64RegClass);
103 addRegisterClass(MVT::f128, &ARM64::FPR128RegClass);
106 if (Subtarget->hasNEON()) {
107 addRegisterClass(MVT::v16i8, &ARM64::FPR8RegClass);
108 addRegisterClass(MVT::v8i16, &ARM64::FPR16RegClass);
109 // Someone set us up the NEON.
110 addDRTypeForNEON(MVT::v2f32);
111 addDRTypeForNEON(MVT::v8i8);
112 addDRTypeForNEON(MVT::v4i16);
113 addDRTypeForNEON(MVT::v2i32);
114 addDRTypeForNEON(MVT::v1i64);
115 addDRTypeForNEON(MVT::v1f64);
117 addQRTypeForNEON(MVT::v4f32);
118 addQRTypeForNEON(MVT::v2f64);
119 addQRTypeForNEON(MVT::v16i8);
120 addQRTypeForNEON(MVT::v8i16);
121 addQRTypeForNEON(MVT::v4i32);
122 addQRTypeForNEON(MVT::v2i64);
125 // Compute derived properties from the register classes
126 computeRegisterProperties();
128 // Provide all sorts of operation actions
129 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
130 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
131 setOperationAction(ISD::SETCC, MVT::i32, Custom);
132 setOperationAction(ISD::SETCC, MVT::i64, Custom);
133 setOperationAction(ISD::SETCC, MVT::f32, Custom);
134 setOperationAction(ISD::SETCC, MVT::f64, Custom);
135 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
136 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
137 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
138 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
139 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
140 setOperationAction(ISD::SELECT, MVT::i32, Custom);
141 setOperationAction(ISD::SELECT, MVT::i64, Custom);
142 setOperationAction(ISD::SELECT, MVT::f32, Custom);
143 setOperationAction(ISD::SELECT, MVT::f64, Custom);
144 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
145 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
146 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
147 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
148 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
149 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
151 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
152 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
153 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
155 setOperationAction(ISD::FREM, MVT::f32, Expand);
156 setOperationAction(ISD::FREM, MVT::f64, Expand);
157 setOperationAction(ISD::FREM, MVT::f80, Expand);
159 // Custom lowering hooks are needed for XOR
160 // to fold it into CSINC/CSINV.
161 setOperationAction(ISD::XOR, MVT::i32, Custom);
162 setOperationAction(ISD::XOR, MVT::i64, Custom);
164 // Virtually no operation on f128 is legal, but LLVM can't expand them when
165 // there's a valid register class, so we need custom operations in most cases.
166 setOperationAction(ISD::FABS, MVT::f128, Expand);
167 setOperationAction(ISD::FADD, MVT::f128, Custom);
168 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
169 setOperationAction(ISD::FCOS, MVT::f128, Expand);
170 setOperationAction(ISD::FDIV, MVT::f128, Custom);
171 setOperationAction(ISD::FMA, MVT::f128, Expand);
172 setOperationAction(ISD::FMUL, MVT::f128, Custom);
173 setOperationAction(ISD::FNEG, MVT::f128, Expand);
174 setOperationAction(ISD::FPOW, MVT::f128, Expand);
175 setOperationAction(ISD::FREM, MVT::f128, Expand);
176 setOperationAction(ISD::FRINT, MVT::f128, Expand);
177 setOperationAction(ISD::FSIN, MVT::f128, Expand);
178 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
179 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
180 setOperationAction(ISD::FSUB, MVT::f128, Custom);
181 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
182 setOperationAction(ISD::SETCC, MVT::f128, Custom);
183 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
184 setOperationAction(ISD::SELECT, MVT::f128, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
186 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
188 // Lowering for many of the conversions is actually specified by the non-f128
189 // type. The LowerXXX function will be trivial when f128 isn't involved.
190 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
191 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
192 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
193 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
194 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
195 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
196 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
197 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
198 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
199 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
200 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
201 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
202 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
203 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
205 // Variable arguments.
206 setOperationAction(ISD::VASTART, MVT::Other, Custom);
207 setOperationAction(ISD::VAARG, MVT::Other, Custom);
208 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
209 setOperationAction(ISD::VAEND, MVT::Other, Expand);
211 // Variable-sized objects.
212 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
213 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
214 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
216 // Exception handling.
217 // FIXME: These are guesses. Has this been defined yet?
218 setExceptionPointerRegister(ARM64::X0);
219 setExceptionSelectorRegister(ARM64::X1);
221 // Constant pool entries
222 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
225 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
227 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
228 setOperationAction(ISD::ADDC, MVT::i32, Custom);
229 setOperationAction(ISD::ADDE, MVT::i32, Custom);
230 setOperationAction(ISD::SUBC, MVT::i32, Custom);
231 setOperationAction(ISD::SUBE, MVT::i32, Custom);
232 setOperationAction(ISD::ADDC, MVT::i64, Custom);
233 setOperationAction(ISD::ADDE, MVT::i64, Custom);
234 setOperationAction(ISD::SUBC, MVT::i64, Custom);
235 setOperationAction(ISD::SUBE, MVT::i64, Custom);
237 // ARM64 lacks both left-rotate and popcount instructions.
238 setOperationAction(ISD::ROTL, MVT::i32, Expand);
239 setOperationAction(ISD::ROTL, MVT::i64, Expand);
241 // ARM64 doesn't have {U|S}MUL_LOHI.
242 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
243 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
246 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
247 // counterparts, which ARM64 supports directly.
248 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
249 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
250 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
251 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
253 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
254 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
256 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
257 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
258 setOperationAction(ISD::SREM, MVT::i32, Expand);
259 setOperationAction(ISD::SREM, MVT::i64, Expand);
260 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
261 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
262 setOperationAction(ISD::UREM, MVT::i32, Expand);
263 setOperationAction(ISD::UREM, MVT::i64, Expand);
265 // Custom lower Add/Sub/Mul with overflow.
266 setOperationAction(ISD::SADDO, MVT::i32, Custom);
267 setOperationAction(ISD::SADDO, MVT::i64, Custom);
268 setOperationAction(ISD::UADDO, MVT::i32, Custom);
269 setOperationAction(ISD::UADDO, MVT::i64, Custom);
270 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
271 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
272 setOperationAction(ISD::USUBO, MVT::i32, Custom);
273 setOperationAction(ISD::USUBO, MVT::i64, Custom);
274 setOperationAction(ISD::SMULO, MVT::i32, Custom);
275 setOperationAction(ISD::SMULO, MVT::i64, Custom);
276 setOperationAction(ISD::UMULO, MVT::i32, Custom);
277 setOperationAction(ISD::UMULO, MVT::i64, Custom);
279 setOperationAction(ISD::FSIN, MVT::f32, Expand);
280 setOperationAction(ISD::FSIN, MVT::f64, Expand);
281 setOperationAction(ISD::FCOS, MVT::f32, Expand);
282 setOperationAction(ISD::FCOS, MVT::f64, Expand);
283 setOperationAction(ISD::FPOW, MVT::f32, Expand);
284 setOperationAction(ISD::FPOW, MVT::f64, Expand);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
288 // ARM64 has implementations of a lot of rounding-like FP operations.
289 static MVT RoundingTypes[] = { MVT::f32, MVT::f64};
290 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
291 MVT Ty = RoundingTypes[I];
292 setOperationAction(ISD::FFLOOR, Ty, Legal);
293 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
294 setOperationAction(ISD::FCEIL, Ty, Legal);
295 setOperationAction(ISD::FRINT, Ty, Legal);
296 setOperationAction(ISD::FTRUNC, Ty, Legal);
297 setOperationAction(ISD::FROUND, Ty, Legal);
300 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
302 if (Subtarget->isTargetMachO()) {
303 // For iOS, we don't want to the normal expansion of a libcall to
304 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
306 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
307 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
309 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
310 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
313 // ARM64 does not have floating-point extending loads, i1 sign-extending load,
314 // floating-point truncating stores, or v2i32->v2i16 truncating store.
315 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
316 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
317 setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
318 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
319 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
320 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
321 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
322 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
323 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
324 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
325 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
326 // Indexed loads and stores are supported.
327 for (unsigned im = (unsigned)ISD::PRE_INC;
328 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
329 setIndexedLoadAction(im, MVT::i8, Legal);
330 setIndexedLoadAction(im, MVT::i16, Legal);
331 setIndexedLoadAction(im, MVT::i32, Legal);
332 setIndexedLoadAction(im, MVT::i64, Legal);
333 setIndexedLoadAction(im, MVT::f64, Legal);
334 setIndexedLoadAction(im, MVT::f32, Legal);
335 setIndexedStoreAction(im, MVT::i8, Legal);
336 setIndexedStoreAction(im, MVT::i16, Legal);
337 setIndexedStoreAction(im, MVT::i32, Legal);
338 setIndexedStoreAction(im, MVT::i64, Legal);
339 setIndexedStoreAction(im, MVT::f64, Legal);
340 setIndexedStoreAction(im, MVT::f32, Legal);
344 setOperationAction(ISD::TRAP, MVT::Other, Legal);
346 // We combine OR nodes for bitfield operations.
347 setTargetDAGCombine(ISD::OR);
349 // Vector add and sub nodes may conceal a high-half opportunity.
350 // Also, try to fold ADD into CSINC/CSINV..
351 setTargetDAGCombine(ISD::ADD);
352 setTargetDAGCombine(ISD::SUB);
354 setTargetDAGCombine(ISD::XOR);
355 setTargetDAGCombine(ISD::SINT_TO_FP);
356 setTargetDAGCombine(ISD::UINT_TO_FP);
358 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
360 setTargetDAGCombine(ISD::ANY_EXTEND);
361 setTargetDAGCombine(ISD::ZERO_EXTEND);
362 setTargetDAGCombine(ISD::SIGN_EXTEND);
363 setTargetDAGCombine(ISD::BITCAST);
364 setTargetDAGCombine(ISD::CONCAT_VECTORS);
365 setTargetDAGCombine(ISD::STORE);
367 setTargetDAGCombine(ISD::MUL);
369 setTargetDAGCombine(ISD::VSELECT);
371 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
372 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
373 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
375 setStackPointerRegisterToSaveRestore(ARM64::SP);
377 setSchedulingPreference(Sched::Hybrid);
380 MaskAndBranchFoldingIsLegal = true;
382 setMinFunctionAlignment(2);
384 RequireStrictAlign = (Align == StrictAlign);
386 setHasExtractBitsInsn(true);
388 if (Subtarget->hasNEON()) {
389 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
390 // silliness like this:
391 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
392 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
393 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
394 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
395 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
396 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
397 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
398 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
399 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
400 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
401 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
402 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
403 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
404 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
405 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
406 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
407 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
408 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
409 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
410 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
411 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
412 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
413 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
414 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
415 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
417 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
418 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
419 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
420 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
421 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
423 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
425 // ARM64 doesn't have a direct vector ->f32 conversion instructions for
426 // elements smaller than i32, so promote the input to i32 first.
427 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
428 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
429 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
430 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
431 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
432 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
433 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
434 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
435 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
437 // ARM64 doesn't have MUL.2d:
438 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
439 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
440 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
441 // Likewise, narrowing and extending vector loads/stores aren't handled
443 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
446 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
449 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
450 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
451 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
452 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
454 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
455 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
456 setTruncStoreAction((MVT::SimpleValueType)VT,
457 (MVT::SimpleValueType)InnerVT, Expand);
458 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
459 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
460 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
463 // ARM64 has implementations of a lot of rounding-like FP operations.
464 static MVT RoundingVecTypes[] = {MVT::v2f32, MVT::v4f32, MVT::v2f64 };
465 for (unsigned I = 0; I < array_lengthof(RoundingVecTypes); ++I) {
466 MVT Ty = RoundingVecTypes[I];
467 setOperationAction(ISD::FFLOOR, Ty, Legal);
468 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
469 setOperationAction(ISD::FCEIL, Ty, Legal);
470 setOperationAction(ISD::FRINT, Ty, Legal);
471 setOperationAction(ISD::FTRUNC, Ty, Legal);
472 setOperationAction(ISD::FROUND, Ty, Legal);
477 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
478 if (VT == MVT::v2f32) {
479 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
480 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
482 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
483 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
484 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
485 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
486 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
488 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
489 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
492 // Mark vector float intrinsics as expand.
493 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
494 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
495 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
496 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
497 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
498 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
499 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
500 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
501 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
502 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
505 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
506 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
507 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
508 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
509 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
510 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
511 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
512 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
513 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
514 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
515 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
516 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
518 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
519 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
520 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
521 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
523 // CNT supports only B element sizes.
524 if (VT != MVT::v8i8 && VT != MVT::v16i8)
525 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
527 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
528 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
529 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
530 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
531 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
533 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
534 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
536 if (Subtarget->isLittleEndian()) {
537 for (unsigned im = (unsigned)ISD::PRE_INC;
538 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
539 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
540 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
545 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
546 addRegisterClass(VT, &ARM64::FPR64RegClass);
547 addTypeForNEON(VT, MVT::v2i32);
550 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
551 addRegisterClass(VT, &ARM64::FPR128RegClass);
552 addTypeForNEON(VT, MVT::v4i32);
555 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
558 return VT.changeVectorElementTypeToInteger();
561 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
562 /// Mask are known to be either zero or one and return them in the
563 /// KnownZero/KnownOne bitsets.
564 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
565 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
566 const SelectionDAG &DAG, unsigned Depth) const {
567 switch (Op.getOpcode()) {
570 case ARM64ISD::CSEL: {
571 APInt KnownZero2, KnownOne2;
572 DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
573 DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
574 KnownZero &= KnownZero2;
575 KnownOne &= KnownOne2;
578 case ISD::INTRINSIC_W_CHAIN: {
579 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
580 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
583 case Intrinsic::arm64_ldaxr:
584 case Intrinsic::arm64_ldxr: {
585 unsigned BitWidth = KnownOne.getBitWidth();
586 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
587 unsigned MemBits = VT.getScalarType().getSizeInBits();
588 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
594 case ISD::INTRINSIC_WO_CHAIN:
595 case ISD::INTRINSIC_VOID: {
596 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
600 case Intrinsic::arm64_neon_umaxv:
601 case Intrinsic::arm64_neon_uminv: {
602 // Figure out the datatype of the vector operand. The UMINV instruction
603 // will zero extend the result, so we can mark as known zero all the
604 // bits larger than the element datatype. 32-bit or larget doesn't need
605 // this as those are legal types and will be handled by isel directly.
606 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
607 unsigned BitWidth = KnownZero.getBitWidth();
608 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
609 assert(BitWidth >= 8 && "Unexpected width!");
610 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
612 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
613 assert(BitWidth >= 16 && "Unexpected width!");
614 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
624 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
628 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
629 // FIXME: On ARM64, this depends on the type.
630 // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
631 // and the offset has to be a multiple of the related size in bytes.
636 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
637 const TargetLibraryInfo *libInfo) const {
638 return ARM64::createFastISel(funcInfo, libInfo);
641 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
645 case ARM64ISD::CALL: return "ARM64ISD::CALL";
646 case ARM64ISD::ADRP: return "ARM64ISD::ADRP";
647 case ARM64ISD::ADDlow: return "ARM64ISD::ADDlow";
648 case ARM64ISD::LOADgot: return "ARM64ISD::LOADgot";
649 case ARM64ISD::RET_FLAG: return "ARM64ISD::RET_FLAG";
650 case ARM64ISD::BRCOND: return "ARM64ISD::BRCOND";
651 case ARM64ISD::CSEL: return "ARM64ISD::CSEL";
652 case ARM64ISD::FCSEL: return "ARM64ISD::FCSEL";
653 case ARM64ISD::CSINV: return "ARM64ISD::CSINV";
654 case ARM64ISD::CSNEG: return "ARM64ISD::CSNEG";
655 case ARM64ISD::CSINC: return "ARM64ISD::CSINC";
656 case ARM64ISD::THREAD_POINTER: return "ARM64ISD::THREAD_POINTER";
657 case ARM64ISD::TLSDESC_CALL: return "ARM64ISD::TLSDESC_CALL";
658 case ARM64ISD::ADC: return "ARM64ISD::ADC";
659 case ARM64ISD::SBC: return "ARM64ISD::SBC";
660 case ARM64ISD::ADDS: return "ARM64ISD::ADDS";
661 case ARM64ISD::SUBS: return "ARM64ISD::SUBS";
662 case ARM64ISD::ADCS: return "ARM64ISD::ADCS";
663 case ARM64ISD::SBCS: return "ARM64ISD::SBCS";
664 case ARM64ISD::ANDS: return "ARM64ISD::ANDS";
665 case ARM64ISD::FCMP: return "ARM64ISD::FCMP";
666 case ARM64ISD::FMIN: return "ARM64ISD::FMIN";
667 case ARM64ISD::FMAX: return "ARM64ISD::FMAX";
668 case ARM64ISD::DUP: return "ARM64ISD::DUP";
669 case ARM64ISD::DUPLANE8: return "ARM64ISD::DUPLANE8";
670 case ARM64ISD::DUPLANE16: return "ARM64ISD::DUPLANE16";
671 case ARM64ISD::DUPLANE32: return "ARM64ISD::DUPLANE32";
672 case ARM64ISD::DUPLANE64: return "ARM64ISD::DUPLANE64";
673 case ARM64ISD::MOVI: return "ARM64ISD::MOVI";
674 case ARM64ISD::MOVIshift: return "ARM64ISD::MOVIshift";
675 case ARM64ISD::MOVIedit: return "ARM64ISD::MOVIedit";
676 case ARM64ISD::MOVImsl: return "ARM64ISD::MOVImsl";
677 case ARM64ISD::FMOV: return "ARM64ISD::FMOV";
678 case ARM64ISD::MVNIshift: return "ARM64ISD::MVNIshift";
679 case ARM64ISD::MVNImsl: return "ARM64ISD::MVNImsl";
680 case ARM64ISD::BICi: return "ARM64ISD::BICi";
681 case ARM64ISD::ORRi: return "ARM64ISD::ORRi";
682 case ARM64ISD::BSL: return "ARM64ISD::BSL";
683 case ARM64ISD::NEG: return "ARM64ISD::NEG";
684 case ARM64ISD::EXTR: return "ARM64ISD::EXTR";
685 case ARM64ISD::ZIP1: return "ARM64ISD::ZIP1";
686 case ARM64ISD::ZIP2: return "ARM64ISD::ZIP2";
687 case ARM64ISD::UZP1: return "ARM64ISD::UZP1";
688 case ARM64ISD::UZP2: return "ARM64ISD::UZP2";
689 case ARM64ISD::TRN1: return "ARM64ISD::TRN1";
690 case ARM64ISD::TRN2: return "ARM64ISD::TRN2";
691 case ARM64ISD::REV16: return "ARM64ISD::REV16";
692 case ARM64ISD::REV32: return "ARM64ISD::REV32";
693 case ARM64ISD::REV64: return "ARM64ISD::REV64";
694 case ARM64ISD::EXT: return "ARM64ISD::EXT";
695 case ARM64ISD::VSHL: return "ARM64ISD::VSHL";
696 case ARM64ISD::VLSHR: return "ARM64ISD::VLSHR";
697 case ARM64ISD::VASHR: return "ARM64ISD::VASHR";
698 case ARM64ISD::CMEQ: return "ARM64ISD::CMEQ";
699 case ARM64ISD::CMGE: return "ARM64ISD::CMGE";
700 case ARM64ISD::CMGT: return "ARM64ISD::CMGT";
701 case ARM64ISD::CMHI: return "ARM64ISD::CMHI";
702 case ARM64ISD::CMHS: return "ARM64ISD::CMHS";
703 case ARM64ISD::FCMEQ: return "ARM64ISD::FCMEQ";
704 case ARM64ISD::FCMGE: return "ARM64ISD::FCMGE";
705 case ARM64ISD::FCMGT: return "ARM64ISD::FCMGT";
706 case ARM64ISD::CMEQz: return "ARM64ISD::CMEQz";
707 case ARM64ISD::CMGEz: return "ARM64ISD::CMGEz";
708 case ARM64ISD::CMGTz: return "ARM64ISD::CMGTz";
709 case ARM64ISD::CMLEz: return "ARM64ISD::CMLEz";
710 case ARM64ISD::CMLTz: return "ARM64ISD::CMLTz";
711 case ARM64ISD::FCMEQz: return "ARM64ISD::FCMEQz";
712 case ARM64ISD::FCMGEz: return "ARM64ISD::FCMGEz";
713 case ARM64ISD::FCMGTz: return "ARM64ISD::FCMGTz";
714 case ARM64ISD::FCMLEz: return "ARM64ISD::FCMLEz";
715 case ARM64ISD::FCMLTz: return "ARM64ISD::FCMLTz";
716 case ARM64ISD::NOT: return "ARM64ISD::NOT";
717 case ARM64ISD::BIT: return "ARM64ISD::BIT";
718 case ARM64ISD::CBZ: return "ARM64ISD::CBZ";
719 case ARM64ISD::CBNZ: return "ARM64ISD::CBNZ";
720 case ARM64ISD::TBZ: return "ARM64ISD::TBZ";
721 case ARM64ISD::TBNZ: return "ARM64ISD::TBNZ";
722 case ARM64ISD::TC_RETURN: return "ARM64ISD::TC_RETURN";
723 case ARM64ISD::SITOF: return "ARM64ISD::SITOF";
724 case ARM64ISD::UITOF: return "ARM64ISD::UITOF";
725 case ARM64ISD::SQSHL_I: return "ARM64ISD::SQSHL_I";
726 case ARM64ISD::UQSHL_I: return "ARM64ISD::UQSHL_I";
727 case ARM64ISD::SRSHR_I: return "ARM64ISD::SRSHR_I";
728 case ARM64ISD::URSHR_I: return "ARM64ISD::URSHR_I";
729 case ARM64ISD::SQSHLU_I: return "ARM64ISD::SQSHLU_I";
730 case ARM64ISD::WrapperLarge: return "ARM64ISD::WrapperLarge";
735 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
736 MachineBasicBlock *MBB) const {
737 // We materialise the F128CSEL pseudo-instruction as some control flow and a
741 // [... previous instrs leading to comparison ...]
747 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
749 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
750 MachineFunction *MF = MBB->getParent();
751 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
752 DebugLoc DL = MI->getDebugLoc();
753 MachineFunction::iterator It = MBB;
756 unsigned DestReg = MI->getOperand(0).getReg();
757 unsigned IfTrueReg = MI->getOperand(1).getReg();
758 unsigned IfFalseReg = MI->getOperand(2).getReg();
759 unsigned CondCode = MI->getOperand(3).getImm();
760 bool NZCVKilled = MI->getOperand(4).isKill();
762 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
763 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
764 MF->insert(It, TrueBB);
765 MF->insert(It, EndBB);
767 // Transfer rest of current basic-block to EndBB
768 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
770 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
772 BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
773 BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
774 MBB->addSuccessor(TrueBB);
775 MBB->addSuccessor(EndBB);
777 // TrueBB falls through to the end.
778 TrueBB->addSuccessor(EndBB);
781 TrueBB->addLiveIn(ARM64::NZCV);
782 EndBB->addLiveIn(ARM64::NZCV);
785 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
791 MI->eraseFromParent();
796 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
797 MachineBasicBlock *BB) const {
798 switch (MI->getOpcode()) {
803 assert(0 && "Unexpected instruction for custom inserter!");
806 case ARM64::F128CSEL:
807 return EmitF128CSEL(MI, BB);
809 case TargetOpcode::STACKMAP:
810 case TargetOpcode::PATCHPOINT:
811 return emitPatchPoint(MI, BB);
813 llvm_unreachable("Unexpected instruction for custom inserter!");
816 //===----------------------------------------------------------------------===//
817 // ARM64 Lowering private implementation.
818 //===----------------------------------------------------------------------===//
820 //===----------------------------------------------------------------------===//
822 //===----------------------------------------------------------------------===//
824 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
825 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
828 llvm_unreachable("Unknown condition code!");
852 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
853 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
854 ARM64CC::CondCode &CondCode2) {
855 CondCode2 = ARM64CC::AL;
858 llvm_unreachable("Unknown FP condition!");
861 CondCode = ARM64CC::EQ;
865 CondCode = ARM64CC::GT;
869 CondCode = ARM64CC::GE;
872 CondCode = ARM64CC::MI;
875 CondCode = ARM64CC::LS;
878 CondCode = ARM64CC::MI;
879 CondCode2 = ARM64CC::GT;
882 CondCode = ARM64CC::VC;
885 CondCode = ARM64CC::VS;
888 CondCode = ARM64CC::EQ;
889 CondCode2 = ARM64CC::VS;
892 CondCode = ARM64CC::HI;
895 CondCode = ARM64CC::PL;
899 CondCode = ARM64CC::LT;
903 CondCode = ARM64CC::LE;
907 CondCode = ARM64CC::NE;
912 /// changeVectorFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC
913 /// usable with the vector instructions. Fewer operations are available without
914 /// a real NZCV register, so we have to use less efficient combinations to get
916 static void changeVectorFPCCToARM64CC(ISD::CondCode CC,
917 ARM64CC::CondCode &CondCode,
918 ARM64CC::CondCode &CondCode2,
923 // Mostly the scalar mappings work fine.
924 changeFPCCToARM64CC(CC, CondCode, CondCode2);
927 Invert = true; // Fallthrough
929 CondCode = ARM64CC::MI;
930 CondCode2 = ARM64CC::GE;
937 // All of the compare-mask comparisons are ordered, but we can switch
938 // between the two by a double inversion. E.g. ULE == !OGT.
940 changeFPCCToARM64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
945 static bool isLegalArithImmed(uint64_t C) {
946 // Matches ARM64DAGToDAGISel::SelectArithImmed().
947 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
950 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
951 SDLoc dl, SelectionDAG &DAG) {
952 EVT VT = LHS.getValueType();
954 if (VT.isFloatingPoint())
955 return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
957 // The CMP instruction is just an alias for SUBS, and representing it as
958 // SUBS means that it's possible to get CSE with subtract operations.
959 // A later phase can perform the optimization of setting the destination
960 // register to WZR/XZR if it ends up being unused.
961 unsigned Opcode = ARM64ISD::SUBS;
963 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
964 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
965 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
966 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
967 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
968 // can be set differently by this operation. It comes down to whether
969 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
970 // everything is fine. If not then the optimization is wrong. Thus general
971 // comparisons are only valid if op2 != 0.
973 // So, finally, the only LLVM-native comparisons that don't mention C and V
974 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
975 // the absence of information about op2.
976 Opcode = ARM64ISD::ADDS;
977 RHS = RHS.getOperand(1);
978 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
979 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
980 !isUnsignedIntSetCC(CC)) {
981 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
982 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
983 // of the signed comparisons.
984 Opcode = ARM64ISD::ANDS;
985 RHS = LHS.getOperand(1);
986 LHS = LHS.getOperand(0);
989 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
993 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
994 SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
995 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
996 EVT VT = RHS.getValueType();
997 uint64_t C = RHSC->getZExtValue();
998 if (!isLegalArithImmed(C)) {
999 // Constant does not fit, try adjusting it by one?
1005 if ((VT == MVT::i32 && C != 0x80000000 &&
1006 isLegalArithImmed((uint32_t)(C - 1))) ||
1007 (VT == MVT::i64 && C != 0x80000000ULL &&
1008 isLegalArithImmed(C - 1ULL))) {
1009 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1010 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1011 RHS = DAG.getConstant(C, VT);
1016 if ((VT == MVT::i32 && C != 0 &&
1017 isLegalArithImmed((uint32_t)(C - 1))) ||
1018 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1019 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1020 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1021 RHS = DAG.getConstant(C, VT);
1026 if ((VT == MVT::i32 && C != 0x7fffffff &&
1027 isLegalArithImmed((uint32_t)(C + 1))) ||
1028 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1029 isLegalArithImmed(C + 1ULL))) {
1030 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1031 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1032 RHS = DAG.getConstant(C, VT);
1037 if ((VT == MVT::i32 && C != 0xffffffff &&
1038 isLegalArithImmed((uint32_t)(C + 1))) ||
1039 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1040 isLegalArithImmed(C + 1ULL))) {
1041 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1042 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1043 RHS = DAG.getConstant(C, VT);
1050 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1051 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
1052 ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1056 static std::pair<SDValue, SDValue>
1057 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1058 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1059 "Unsupported value type");
1060 SDValue Value, Overflow;
1062 SDValue LHS = Op.getOperand(0);
1063 SDValue RHS = Op.getOperand(1);
1065 switch (Op.getOpcode()) {
1067 llvm_unreachable("Unknown overflow instruction!");
1069 Opc = ARM64ISD::ADDS;
1073 Opc = ARM64ISD::ADDS;
1077 Opc = ARM64ISD::SUBS;
1081 Opc = ARM64ISD::SUBS;
1084 // Multiply needs a little bit extra work.
1088 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1089 if (Op.getValueType() == MVT::i32) {
1090 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1091 // For a 32 bit multiply with overflow check we want the instruction
1092 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1093 // need to generate the following pattern:
1094 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1095 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1096 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1097 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1098 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1099 DAG.getConstant(0, MVT::i64));
1100 // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1101 // operation. We need to clear out the upper 32 bits, because we used a
1102 // widening multiply that wrote all 64 bits. In the end this should be a
1104 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1106 // The signed overflow check requires more than just a simple check for
1107 // any bit set in the upper 32 bits of the result. These bits could be
1108 // just the sign bits of a negative number. To perform the overflow
1109 // check we have to arithmetic shift right the 32nd bit of the result by
1110 // 31 bits. Then we compare the result to the upper 32 bits.
1111 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1112 DAG.getConstant(32, MVT::i64));
1113 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1114 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1115 DAG.getConstant(31, MVT::i64));
1116 // It is important that LowerBits is last, otherwise the arithmetic
1117 // shift will not be folded into the compare (SUBS).
1118 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1119 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1122 // The overflow check for unsigned multiply is easy. We only need to
1123 // check if any of the upper 32 bits are set. This can be done with a
1124 // CMP (shifted register). For that we need to generate the following
1126 // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1127 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1128 DAG.getConstant(32, MVT::i64));
1129 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1131 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1132 UpperBits).getValue(1);
1136 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1137 // For the 64 bit multiply
1138 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1140 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1141 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1142 DAG.getConstant(63, MVT::i64));
1143 // It is important that LowerBits is last, otherwise the arithmetic
1144 // shift will not be folded into the compare (SUBS).
1145 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1146 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1149 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1150 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1152 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1153 UpperBits).getValue(1);
1160 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1162 // Emit the ARM64 operation with overflow check.
1163 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1164 Overflow = Value.getValue(1);
1166 return std::make_pair(Value, Overflow);
1169 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1170 RTLIB::Libcall Call) const {
1171 SmallVector<SDValue, 2> Ops;
1172 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1173 Ops.push_back(Op.getOperand(i));
1175 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1179 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1180 SDValue Sel = Op.getOperand(0);
1181 SDValue Other = Op.getOperand(1);
1183 // If neither operand is a SELECT_CC, give up.
1184 if (Sel.getOpcode() != ISD::SELECT_CC)
1185 std::swap(Sel, Other);
1186 if (Sel.getOpcode() != ISD::SELECT_CC)
1189 // The folding we want to perform is:
1190 // (xor x, (select_cc a, b, cc, 0, -1) )
1192 // (csel x, (xor x, -1), cc ...)
1194 // The latter will get matched to a CSINV instruction.
1196 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1197 SDValue LHS = Sel.getOperand(0);
1198 SDValue RHS = Sel.getOperand(1);
1199 SDValue TVal = Sel.getOperand(2);
1200 SDValue FVal = Sel.getOperand(3);
1203 // FIXME: This could be generalized to non-integer comparisons.
1204 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1207 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1208 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1210 // The the values aren't constants, this isn't the pattern we're looking for.
1211 if (!CFVal || !CTVal)
1214 // We can commute the SELECT_CC by inverting the condition. This
1215 // might be needed to make this fit into a CSINV pattern.
1216 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1217 std::swap(TVal, FVal);
1218 std::swap(CTVal, CFVal);
1219 CC = ISD::getSetCCInverse(CC, true);
1222 // If the constants line up, perform the transform!
1223 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1225 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1228 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1229 DAG.getConstant(-1ULL, Other.getValueType()));
1231 return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1238 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1239 EVT VT = Op.getValueType();
1241 // Let legalize expand this if it isn't a legal type yet.
1242 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1245 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1248 bool ExtraOp = false;
1249 switch (Op.getOpcode()) {
1251 assert(0 && "Invalid code");
1253 Opc = ARM64ISD::ADDS;
1256 Opc = ARM64ISD::SUBS;
1259 Opc = ARM64ISD::ADCS;
1263 Opc = ARM64ISD::SBCS;
1269 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1270 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1274 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1275 // Let legalize expand this if it isn't a legal type yet.
1276 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1279 ARM64CC::CondCode CC;
1280 // The actual operation that sets the overflow or carry flag.
1281 SDValue Value, Overflow;
1282 std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1284 // We use 0 and 1 as false and true values.
1285 SDValue TVal = DAG.getConstant(1, MVT::i32);
1286 SDValue FVal = DAG.getConstant(0, MVT::i32);
1288 // We use an inverted condition, because the conditional select is inverted
1289 // too. This will allow it to be selected to a single instruction:
1290 // CSINC Wd, WZR, WZR, invert(cond).
1291 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1292 Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1295 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1296 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1299 // Prefetch operands are:
1300 // 1: Address to prefetch
1302 // 3: int locality (0 = no locality ... 3 = extreme locality)
1303 // 4: bool isDataCache
1304 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1306 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1307 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1308 // The data thing is not used.
1309 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1311 bool IsStream = !Locality;
1312 // When the locality number is set
1314 // The front-end should have filtered out the out-of-range values
1315 assert(Locality <= 3 && "Prefetch locality out-of-range");
1316 // The locality degree is the opposite of the cache speed.
1317 // Put the number the other way around.
1318 // The encoding starts at 0 for level 1
1319 Locality = 3 - Locality;
1322 // built the mask value encoding the expected behavior.
1323 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1324 (Locality << 1) | // Cache level bits
1325 (unsigned)IsStream; // Stream bit
1326 return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1327 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1330 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1331 SelectionDAG &DAG) const {
1332 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1335 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1337 return LowerF128Call(Op, DAG, LC);
1340 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1341 SelectionDAG &DAG) const {
1342 if (Op.getOperand(0).getValueType() != MVT::f128) {
1343 // It's legal except when f128 is involved
1348 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1350 // FP_ROUND node has a second operand indicating whether it is known to be
1351 // precise. That doesn't take part in the LibCall so we can't directly use
1353 SDValue SrcVal = Op.getOperand(0);
1354 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1355 /*isSigned*/ false, SDLoc(Op)).first;
1358 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1359 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1360 // Any additional optimization in this function should be recorded
1361 // in the cost tables.
1362 EVT InVT = Op.getOperand(0).getValueType();
1363 EVT VT = Op.getValueType();
1365 // FP_TO_XINT conversion from the same type are legal.
1366 if (VT.getSizeInBits() == InVT.getSizeInBits())
1369 if (InVT == MVT::v2f64 || InVT == MVT::v4f32) {
1372 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1374 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1375 } else if (InVT == MVT::v2f32) {
1377 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Op.getOperand(0));
1378 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1381 // Type changing conversions are illegal.
1385 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1386 SelectionDAG &DAG) const {
1387 if (Op.getOperand(0).getValueType().isVector())
1388 return LowerVectorFP_TO_INT(Op, DAG);
1390 if (Op.getOperand(0).getValueType() != MVT::f128) {
1391 // It's legal except when f128 is involved
1396 if (Op.getOpcode() == ISD::FP_TO_SINT)
1397 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1399 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1401 SmallVector<SDValue, 2> Ops;
1402 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1403 Ops.push_back(Op.getOperand(i));
1405 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1409 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1410 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1411 // Any additional optimization in this function should be recorded
1412 // in the cost tables.
1413 EVT VT = Op.getValueType();
1415 SDValue In = Op.getOperand(0);
1416 EVT InVT = In.getValueType();
1418 // v2i32 to v2f32 is legal.
1419 if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1422 // This function only handles v2f64 outputs.
1423 if (VT == MVT::v2f64) {
1424 // Extend the input argument to a v2i64 that we can feed into the
1425 // floating point conversion. Zero or sign extend based on whether
1426 // we're doing a signed or unsigned float conversion.
1428 Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1429 assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1430 SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1431 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1434 // Scalarize v2i64 to v2f32 conversions.
1435 std::vector<SDValue> BuildVectorOps;
1436 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1437 SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1438 DAG.getConstant(i, MVT::i64));
1439 Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1440 BuildVectorOps.push_back(Sclr);
1443 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, BuildVectorOps);
1446 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1447 SelectionDAG &DAG) const {
1448 if (Op.getValueType().isVector())
1449 return LowerVectorINT_TO_FP(Op, DAG);
1451 // i128 conversions are libcalls.
1452 if (Op.getOperand(0).getValueType() == MVT::i128)
1455 // Other conversions are legal, unless it's to the completely software-based
1457 if (Op.getValueType() != MVT::f128)
1461 if (Op.getOpcode() == ISD::SINT_TO_FP)
1462 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1464 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1466 return LowerF128Call(Op, DAG, LC);
1469 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1470 // For iOS, we want to call an alternative entry point: __sincos_stret,
1471 // which returns the values in two S / D registers.
1473 SDValue Arg = Op.getOperand(0);
1474 EVT ArgVT = Arg.getValueType();
1475 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1482 Entry.isSExt = false;
1483 Entry.isZExt = false;
1484 Args.push_back(Entry);
1486 const char *LibcallName =
1487 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1488 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1490 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1491 TargetLowering::CallLoweringInfo CLI(
1492 DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1493 CallingConv::Fast, /*isTaillCall=*/false,
1494 /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1495 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1496 return CallResult.first;
1499 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1500 SelectionDAG &DAG) const {
1501 switch (Op.getOpcode()) {
1503 llvm_unreachable("unimplemented operand");
1505 case ISD::GlobalAddress:
1506 return LowerGlobalAddress(Op, DAG);
1507 case ISD::GlobalTLSAddress:
1508 return LowerGlobalTLSAddress(Op, DAG);
1510 return LowerSETCC(Op, DAG);
1512 return LowerBR_CC(Op, DAG);
1514 return LowerSELECT(Op, DAG);
1515 case ISD::SELECT_CC:
1516 return LowerSELECT_CC(Op, DAG);
1517 case ISD::JumpTable:
1518 return LowerJumpTable(Op, DAG);
1519 case ISD::ConstantPool:
1520 return LowerConstantPool(Op, DAG);
1521 case ISD::BlockAddress:
1522 return LowerBlockAddress(Op, DAG);
1524 return LowerVASTART(Op, DAG);
1526 return LowerVACOPY(Op, DAG);
1528 return LowerVAARG(Op, DAG);
1533 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1540 return LowerXALUO(Op, DAG);
1542 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1544 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1546 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1548 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1550 return LowerFP_ROUND(Op, DAG);
1551 case ISD::FP_EXTEND:
1552 return LowerFP_EXTEND(Op, DAG);
1553 case ISD::FRAMEADDR:
1554 return LowerFRAMEADDR(Op, DAG);
1555 case ISD::RETURNADDR:
1556 return LowerRETURNADDR(Op, DAG);
1557 case ISD::INSERT_VECTOR_ELT:
1558 return LowerINSERT_VECTOR_ELT(Op, DAG);
1559 case ISD::EXTRACT_VECTOR_ELT:
1560 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1561 case ISD::BUILD_VECTOR:
1562 return LowerBUILD_VECTOR(Op, DAG);
1563 case ISD::VECTOR_SHUFFLE:
1564 return LowerVECTOR_SHUFFLE(Op, DAG);
1565 case ISD::EXTRACT_SUBVECTOR:
1566 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1570 return LowerVectorSRA_SRL_SHL(Op, DAG);
1571 case ISD::SHL_PARTS:
1572 return LowerShiftLeftParts(Op, DAG);
1573 case ISD::SRL_PARTS:
1574 case ISD::SRA_PARTS:
1575 return LowerShiftRightParts(Op, DAG);
1577 return LowerCTPOP(Op, DAG);
1578 case ISD::FCOPYSIGN:
1579 return LowerFCOPYSIGN(Op, DAG);
1581 return LowerVectorAND(Op, DAG);
1583 return LowerVectorOR(Op, DAG);
1585 return LowerXOR(Op, DAG);
1587 return LowerPREFETCH(Op, DAG);
1588 case ISD::SINT_TO_FP:
1589 case ISD::UINT_TO_FP:
1590 return LowerINT_TO_FP(Op, DAG);
1591 case ISD::FP_TO_SINT:
1592 case ISD::FP_TO_UINT:
1593 return LowerFP_TO_INT(Op, DAG);
1595 return LowerFSINCOS(Op, DAG);
1599 /// getFunctionAlignment - Return the Log2 alignment of this function.
1600 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
1604 //===----------------------------------------------------------------------===//
1605 // Calling Convention Implementation
1606 //===----------------------------------------------------------------------===//
1608 #include "ARM64GenCallingConv.inc"
1610 /// Selects the correct CCAssignFn for a the given CallingConvention
1612 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1613 bool IsVarArg) const {
1616 llvm_unreachable("Unsupported calling convention.");
1617 case CallingConv::WebKit_JS:
1618 return CC_ARM64_WebKit_JS;
1619 case CallingConv::C:
1620 case CallingConv::Fast:
1621 if (!Subtarget->isTargetDarwin())
1622 return CC_ARM64_AAPCS;
1623 return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
1627 SDValue ARM64TargetLowering::LowerFormalArguments(
1628 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1629 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1630 SmallVectorImpl<SDValue> &InVals) const {
1631 MachineFunction &MF = DAG.getMachineFunction();
1632 MachineFrameInfo *MFI = MF.getFrameInfo();
1634 // Assign locations to all of the incoming arguments.
1635 SmallVector<CCValAssign, 16> ArgLocs;
1636 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1637 getTargetMachine(), ArgLocs, *DAG.getContext());
1639 // At this point, Ins[].VT may already be promoted to i32. To correctly
1640 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1641 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1642 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1643 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1645 unsigned NumArgs = Ins.size();
1646 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1647 unsigned CurArgIdx = 0;
1648 for (unsigned i = 0; i != NumArgs; ++i) {
1649 MVT ValVT = Ins[i].VT;
1650 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1651 CurArgIdx = Ins[i].OrigArgIndex;
1653 // Get type of the original argument.
1654 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1655 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1656 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1658 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1660 else if (ActualMVT == MVT::i16)
1663 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1665 AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1666 assert(!Res && "Call operand has unhandled type");
1669 assert(ArgLocs.size() == Ins.size());
1670 SmallVector<SDValue, 16> ArgValues;
1671 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1672 CCValAssign &VA = ArgLocs[i];
1674 if (Ins[i].Flags.isByVal()) {
1675 // Byval is used for HFAs in the PCS, but the system should work in a
1676 // non-compliant manner for larger structs.
1677 EVT PtrTy = getPointerTy();
1678 int Size = Ins[i].Flags.getByValSize();
1679 unsigned NumRegs = (Size + 7) / 8;
1682 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1683 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1684 InVals.push_back(FrameIdxN);
1687 } if (VA.isRegLoc()) {
1688 // Arguments stored in registers.
1689 EVT RegVT = VA.getLocVT();
1692 const TargetRegisterClass *RC;
1694 if (RegVT == MVT::i32)
1695 RC = &ARM64::GPR32RegClass;
1696 else if (RegVT == MVT::i64)
1697 RC = &ARM64::GPR64RegClass;
1698 else if (RegVT == MVT::f32)
1699 RC = &ARM64::FPR32RegClass;
1700 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
1701 RC = &ARM64::FPR64RegClass;
1702 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
1703 RC = &ARM64::FPR128RegClass;
1705 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1707 // Transform the arguments in physical registers into virtual ones.
1708 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1709 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1711 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1712 // to 64 bits. Insert an assert[sz]ext to capture this, then
1713 // truncate to the right size.
1714 switch (VA.getLocInfo()) {
1716 llvm_unreachable("Unknown loc info!");
1717 case CCValAssign::Full:
1719 case CCValAssign::BCvt:
1720 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1722 case CCValAssign::SExt:
1723 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
1724 DAG.getValueType(VA.getValVT()));
1725 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1727 case CCValAssign::ZExt:
1728 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
1729 DAG.getValueType(VA.getValVT()));
1730 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1734 InVals.push_back(ArgValue);
1736 } else { // VA.isRegLoc()
1737 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1738 unsigned ArgOffset = VA.getLocMemOffset();
1739 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1740 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
1742 // Create load nodes to retrieve arguments from the stack.
1743 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1744 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
1745 MachinePointerInfo::getFixedStack(FI), false,
1752 if (!Subtarget->isTargetDarwin()) {
1753 // The AAPCS variadic function ABI is identical to the non-variadic
1754 // one. As a result there may be more arguments in registers and we should
1755 // save them for future reference.
1756 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1759 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
1760 // This will point to the next argument passed via stack.
1761 unsigned StackOffset = CCInfo.getNextStackOffset();
1762 // We currently pass all varargs at 8-byte alignment.
1763 StackOffset = ((StackOffset + 7) & ~7);
1764 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1770 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1771 SelectionDAG &DAG, SDLoc DL,
1772 SDValue &Chain) const {
1773 MachineFunction &MF = DAG.getMachineFunction();
1774 MachineFrameInfo *MFI = MF.getFrameInfo();
1775 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
1777 SmallVector<SDValue, 8> MemOps;
1779 static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
1780 ARM64::X3, ARM64::X4, ARM64::X5,
1781 ARM64::X6, ARM64::X7 };
1782 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1783 unsigned FirstVariadicGPR =
1784 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1786 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1788 if (GPRSaveSize != 0) {
1789 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1791 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1793 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1794 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
1795 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1797 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1798 MachinePointerInfo::getStack(i * 8), false, false, 0);
1799 MemOps.push_back(Store);
1800 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1801 DAG.getConstant(8, getPointerTy()));
1804 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1805 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1807 if (Subtarget->hasFPARMv8()) {
1808 static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
1809 ARM64::Q3, ARM64::Q4, ARM64::Q5,
1810 ARM64::Q6, ARM64::Q7 };
1811 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1812 unsigned FirstVariadicFPR =
1813 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1815 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1817 if (FPRSaveSize != 0) {
1818 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1820 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1822 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1823 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
1824 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
1826 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1827 MachinePointerInfo::getStack(i * 16), false, false, 0);
1828 MemOps.push_back(Store);
1829 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1830 DAG.getConstant(16, getPointerTy()));
1833 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1834 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1837 if (!MemOps.empty()) {
1838 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1842 /// LowerCallResult - Lower the result values of a call into the
1843 /// appropriate copies out of appropriate physical registers.
1844 SDValue ARM64TargetLowering::LowerCallResult(
1845 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1846 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1847 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1848 SDValue ThisVal) const {
1849 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1850 : RetCC_ARM64_AAPCS;
1851 // Assign locations to each value returned by this call.
1852 SmallVector<CCValAssign, 16> RVLocs;
1853 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1854 getTargetMachine(), RVLocs, *DAG.getContext());
1855 CCInfo.AnalyzeCallResult(Ins, RetCC);
1857 // Copy all of the result registers out of their specified physreg.
1858 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1859 CCValAssign VA = RVLocs[i];
1861 // Pass 'this' value directly from the argument to return value, to avoid
1862 // reg unit interference
1863 if (i == 0 && isThisReturn) {
1864 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1865 "unexpected return calling convention register assignment");
1866 InVals.push_back(ThisVal);
1871 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1872 Chain = Val.getValue(1);
1873 InFlag = Val.getValue(2);
1875 switch (VA.getLocInfo()) {
1877 llvm_unreachable("Unknown loc info!");
1878 case CCValAssign::Full:
1880 case CCValAssign::BCvt:
1881 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1885 InVals.push_back(Val);
1891 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
1892 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1893 bool isCalleeStructRet, bool isCallerStructRet,
1894 const SmallVectorImpl<ISD::OutputArg> &Outs,
1895 const SmallVectorImpl<SDValue> &OutVals,
1896 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1897 // Look for obvious safe cases to perform tail call optimization that do not
1898 // require ABI changes. This is what gcc calls sibcall.
1900 // Do not sibcall optimize vararg calls unless the call site is not passing
1902 if (isVarArg && !Outs.empty())
1905 // Also avoid sibcall optimization if either caller or callee uses struct
1906 // return semantics.
1907 if (isCalleeStructRet || isCallerStructRet)
1910 // Note that currently ARM64 "C" calling convention and "Fast" calling
1911 // convention are compatible. If/when that ever changes, we'll need to
1912 // add checks here to make sure any interactions are OK.
1914 // If the callee takes no arguments then go on to check the results of the
1916 if (!Outs.empty()) {
1917 // Check if stack adjustment is needed. For now, do not do this if any
1918 // argument is passed on the stack.
1919 SmallVector<CCValAssign, 16> ArgLocs;
1920 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1921 getTargetMachine(), ArgLocs, *DAG.getContext());
1922 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
1923 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
1924 if (CCInfo.getNextStackOffset()) {
1925 // Check if the arguments are already laid out in the right way as
1926 // the caller's fixed stack objects.
1927 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1928 ++i, ++realArgIdx) {
1929 CCValAssign &VA = ArgLocs[i];
1930 if (VA.getLocInfo() == CCValAssign::Indirect)
1932 if (VA.needsCustom()) {
1933 // Just don't handle anything that needs custom adjustments for now.
1934 // If need be, we can revisit later, but we shouldn't ever end up
1937 } else if (!VA.isRegLoc()) {
1938 // Likewise, don't try to handle stack based arguments for the
1948 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
1949 /// and add input and output parameter nodes.
1950 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1951 SmallVectorImpl<SDValue> &InVals) const {
1952 SelectionDAG &DAG = CLI.DAG;
1954 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1955 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1956 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1957 SDValue Chain = CLI.Chain;
1958 SDValue Callee = CLI.Callee;
1959 bool &IsTailCall = CLI.IsTailCall;
1960 CallingConv::ID CallConv = CLI.CallConv;
1961 bool IsVarArg = CLI.IsVarArg;
1963 MachineFunction &MF = DAG.getMachineFunction();
1964 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1965 bool IsThisReturn = false;
1967 // If tail calls are explicitly disabled, make sure not to use them.
1968 if (!EnableARM64TailCalls)
1972 // Check if it's really possible to do a tail call.
1973 IsTailCall = isEligibleForTailCallOptimization(
1974 Callee, CallConv, IsVarArg, IsStructRet,
1975 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
1976 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
1977 report_fatal_error("failed to perform tail call elimination on a call "
1978 "site marked musttail");
1979 // We don't support GuaranteedTailCallOpt, only automatically
1980 // detected sibcalls.
1981 // FIXME: Re-evaluate. Is this true? Should it be true?
1986 // Analyze operands of the call, assigning locations to each operand.
1987 SmallVector<CCValAssign, 16> ArgLocs;
1988 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1989 getTargetMachine(), ArgLocs, *DAG.getContext());
1992 // Handle fixed and variable vector arguments differently.
1993 // Variable vector arguments always go into memory.
1994 unsigned NumArgs = Outs.size();
1996 for (unsigned i = 0; i != NumArgs; ++i) {
1997 MVT ArgVT = Outs[i].VT;
1998 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1999 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2000 /*IsVarArg=*/ !Outs[i].IsFixed);
2001 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2002 assert(!Res && "Call operand has unhandled type");
2006 // At this point, Outs[].VT may already be promoted to i32. To correctly
2007 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2008 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2009 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2010 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2012 unsigned NumArgs = Outs.size();
2013 for (unsigned i = 0; i != NumArgs; ++i) {
2014 MVT ValVT = Outs[i].VT;
2015 // Get type of the original argument.
2016 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
2017 /*AllowUnknown*/ true);
2018 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2019 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2020 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2022 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2024 else if (ActualMVT == MVT::i16)
2027 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2028 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
2029 assert(!Res && "Call operand has unhandled type");
2034 // Get a count of how many bytes are to be pushed on the stack.
2035 unsigned NumBytes = CCInfo.getNextStackOffset();
2037 // Adjust the stack pointer for the new arguments...
2038 // These operations are automatically eliminated by the prolog/epilog pass
2041 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2043 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
2045 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2046 SmallVector<SDValue, 8> MemOpChains;
2048 // Walk the register/memloc assignments, inserting copies/loads.
2049 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2050 ++i, ++realArgIdx) {
2051 CCValAssign &VA = ArgLocs[i];
2052 SDValue Arg = OutVals[realArgIdx];
2053 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2055 // Promote the value if needed.
2056 switch (VA.getLocInfo()) {
2058 llvm_unreachable("Unknown loc info!");
2059 case CCValAssign::Full:
2061 case CCValAssign::SExt:
2062 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2064 case CCValAssign::ZExt:
2065 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2067 case CCValAssign::AExt:
2068 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2070 case CCValAssign::BCvt:
2071 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2073 case CCValAssign::FPExt:
2074 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2078 if (VA.isRegLoc()) {
2079 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2080 assert(VA.getLocVT() == MVT::i64 &&
2081 "unexpected calling convention register assignment");
2082 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2083 "unexpected use of 'returned'");
2084 IsThisReturn = true;
2086 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2088 assert(VA.isMemLoc());
2089 // There's no reason we can't support stack args w/ tailcall, but
2090 // we currently don't, so assert if we see one.
2091 assert(!IsTailCall && "stack argument with tail call!?");
2092 unsigned LocMemOffset = VA.getLocMemOffset();
2093 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2094 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2096 if (Outs[i].Flags.isByVal()) {
2098 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2099 SDValue Cpy = DAG.getMemcpy(
2100 Chain, DL, PtrOff, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2101 /*isVolatile = */ false,
2102 /*alwaysInline = */ false,
2103 MachinePointerInfo::getStack(LocMemOffset), MachinePointerInfo());
2105 MemOpChains.push_back(Cpy);
2107 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2108 // promoted to a legal register type i32, we should truncate Arg back to
2110 if (Arg.getValueType().isSimple() &&
2111 Arg.getValueType().getSimpleVT() == MVT::i32 &&
2112 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2113 VA.getLocVT() == MVT::i16))
2114 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2116 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2117 MachinePointerInfo::getStack(LocMemOffset),
2119 MemOpChains.push_back(Store);
2124 if (!MemOpChains.empty())
2125 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2127 // Build a sequence of copy-to-reg nodes chained together with token chain
2128 // and flag operands which copy the outgoing args into the appropriate regs.
2130 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2131 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2132 RegsToPass[i].second, InFlag);
2133 InFlag = Chain.getValue(1);
2136 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2137 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2138 // node so that legalize doesn't hack it.
2139 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2140 Subtarget->isTargetMachO()) {
2141 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2142 const GlobalValue *GV = G->getGlobal();
2143 bool InternalLinkage = GV->hasInternalLinkage();
2144 if (InternalLinkage)
2145 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2147 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2149 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2151 } else if (ExternalSymbolSDNode *S =
2152 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2153 const char *Sym = S->getSymbol();
2155 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2156 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2158 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2159 const GlobalValue *GV = G->getGlobal();
2160 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2161 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2162 const char *Sym = S->getSymbol();
2163 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2166 std::vector<SDValue> Ops;
2167 Ops.push_back(Chain);
2168 Ops.push_back(Callee);
2170 // Add argument registers to the end of the list so that they are known live
2172 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2173 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2174 RegsToPass[i].second.getValueType()));
2176 // Add a register mask operand representing the call-preserved registers.
2177 const uint32_t *Mask;
2178 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2179 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2181 // For 'this' returns, use the X0-preserving mask if applicable
2182 Mask = ARI->getThisReturnPreservedMask(CallConv);
2184 IsThisReturn = false;
2185 Mask = ARI->getCallPreservedMask(CallConv);
2188 Mask = ARI->getCallPreservedMask(CallConv);
2190 assert(Mask && "Missing call preserved mask for calling convention");
2191 Ops.push_back(DAG.getRegisterMask(Mask));
2193 if (InFlag.getNode())
2194 Ops.push_back(InFlag);
2196 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2198 // If we're doing a tall call, use a TC_RETURN here rather than an
2199 // actual call instruction.
2201 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, Ops);
2203 // Returns a chain and a flag for retval copy to use.
2204 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, Ops);
2205 InFlag = Chain.getValue(1);
2207 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2208 DAG.getIntPtrConstant(0, true), InFlag, DL);
2210 InFlag = Chain.getValue(1);
2212 // Handle result values, copying them out of physregs into vregs that we
2214 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2215 InVals, IsThisReturn,
2216 IsThisReturn ? OutVals[0] : SDValue());
2219 bool ARM64TargetLowering::CanLowerReturn(
2220 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2221 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2222 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2223 : RetCC_ARM64_AAPCS;
2224 SmallVector<CCValAssign, 16> RVLocs;
2225 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2226 return CCInfo.CheckReturn(Outs, RetCC);
2230 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2232 const SmallVectorImpl<ISD::OutputArg> &Outs,
2233 const SmallVectorImpl<SDValue> &OutVals,
2234 SDLoc DL, SelectionDAG &DAG) const {
2235 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2236 : RetCC_ARM64_AAPCS;
2237 SmallVector<CCValAssign, 16> RVLocs;
2238 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2239 getTargetMachine(), RVLocs, *DAG.getContext());
2240 CCInfo.AnalyzeReturn(Outs, RetCC);
2242 // Copy the result values into the output registers.
2244 SmallVector<SDValue, 4> RetOps(1, Chain);
2245 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2246 ++i, ++realRVLocIdx) {
2247 CCValAssign &VA = RVLocs[i];
2248 assert(VA.isRegLoc() && "Can only return in registers!");
2249 SDValue Arg = OutVals[realRVLocIdx];
2251 switch (VA.getLocInfo()) {
2253 llvm_unreachable("Unknown loc info!");
2254 case CCValAssign::Full:
2256 case CCValAssign::BCvt:
2257 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2261 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2262 Flag = Chain.getValue(1);
2263 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2266 RetOps[0] = Chain; // Update chain.
2268 // Add the flag if we have it.
2270 RetOps.push_back(Flag);
2272 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2275 //===----------------------------------------------------------------------===//
2276 // Other Lowering Code
2277 //===----------------------------------------------------------------------===//
2279 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2280 SelectionDAG &DAG) const {
2281 EVT PtrVT = getPointerTy();
2283 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2284 unsigned char OpFlags =
2285 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2287 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2288 "unexpected offset in global node");
2290 // This also catched the large code model case for Darwin.
2291 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2292 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2293 // FIXME: Once remat is capable of dealing with instructions with register
2294 // operands, expand this into two nodes instead of using a wrapper node.
2295 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2298 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2299 const unsigned char MO_NC = ARM64II::MO_NC;
2301 ARM64ISD::WrapperLarge, DL, PtrVT,
2302 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2303 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2304 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2305 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2307 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2308 // the only correct model on Darwin.
2309 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2310 OpFlags | ARM64II::MO_PAGE);
2311 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2312 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2314 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2315 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2319 /// \brief Convert a TLS address reference into the correct sequence of loads
2320 /// and calls to compute the variable's address (for Darwin, currently) and
2321 /// return an SDValue containing the final node.
2323 /// Darwin only has one TLS scheme which must be capable of dealing with the
2324 /// fully general situation, in the worst case. This means:
2325 /// + "extern __thread" declaration.
2326 /// + Defined in a possibly unknown dynamic library.
2328 /// The general system is that each __thread variable has a [3 x i64] descriptor
2329 /// which contains information used by the runtime to calculate the address. The
2330 /// only part of this the compiler needs to know about is the first xword, which
2331 /// contains a function pointer that must be called with the address of the
2332 /// entire descriptor in "x0".
2334 /// Since this descriptor may be in a different unit, in general even the
2335 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2337 /// adrp x0, _var@TLVPPAGE
2338 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2339 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2340 /// ; the function pointer
2341 /// blr x1 ; Uses descriptor address in x0
2342 /// ; Address of _var is now in x0.
2344 /// If the address of _var's descriptor *is* known to the linker, then it can
2345 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2346 /// a slight efficiency gain.
2348 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2349 SelectionDAG &DAG) const {
2350 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2353 MVT PtrVT = getPointerTy();
2354 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2357 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2358 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2360 // The first entry in the descriptor is a function pointer that we must call
2361 // to obtain the address of the variable.
2362 SDValue Chain = DAG.getEntryNode();
2363 SDValue FuncTLVGet =
2364 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2365 false, true, true, 8);
2366 Chain = FuncTLVGet.getValue(1);
2368 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2369 MFI->setAdjustsStack(true);
2371 // TLS calls preserve all registers except those that absolutely must be
2372 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2374 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2375 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2376 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2378 // Finally, we can make the call. This is just a degenerate version of a
2379 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2380 // the address of the variable in this thread.
2381 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2382 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2383 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2384 DAG.getRegisterMask(Mask), Chain.getValue(1));
2385 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2388 /// When accessing thread-local variables under either the general-dynamic or
2389 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2390 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2391 /// is a function pointer to carry out the resolution. This function takes the
2392 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2393 /// other registers (except LR, NZCV) are preserved.
2395 /// Thus, the ideal call sequence on AArch64 is:
2397 /// adrp x0, :tlsdesc:thread_var
2398 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2399 /// add x0, x0, :tlsdesc_lo12:thread_var
2400 /// .tlsdesccall thread_var
2402 /// (TPIDR_EL0 offset now in x0).
2404 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2405 /// relocation to help the linker relax this sequence if it turns out to be too
2408 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2410 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2411 SDValue DescAddr, SDLoc DL,
2412 SelectionDAG &DAG) const {
2413 EVT PtrVT = getPointerTy();
2415 // The function we need to call is simply the first entry in the GOT for this
2416 // descriptor, load it in preparation.
2417 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2419 // TLS calls preserve all registers except those that absolutely must be
2420 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2422 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2423 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2424 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2426 // The function takes only one argument: the address of the descriptor itself
2428 SDValue Glue, Chain;
2429 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2430 Glue = Chain.getValue(1);
2432 // We're now ready to populate the argument list, as with a normal call:
2433 SmallVector<SDValue, 6> Ops;
2434 Ops.push_back(Chain);
2435 Ops.push_back(Func);
2436 Ops.push_back(SymAddr);
2437 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2438 Ops.push_back(DAG.getRegisterMask(Mask));
2439 Ops.push_back(Glue);
2441 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2442 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, Ops);
2443 Glue = Chain.getValue(1);
2445 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2448 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2449 SelectionDAG &DAG) const {
2450 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2451 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2452 "ELF TLS only supported in small memory model");
2453 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2455 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2458 EVT PtrVT = getPointerTy();
2460 const GlobalValue *GV = GA->getGlobal();
2462 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2464 if (Model == TLSModel::LocalExec) {
2465 SDValue HiVar = DAG.getTargetGlobalAddress(
2466 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2467 SDValue LoVar = DAG.getTargetGlobalAddress(
2468 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2470 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2471 DAG.getTargetConstant(16, MVT::i32)),
2473 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2474 DAG.getTargetConstant(0, MVT::i32)),
2476 } else if (Model == TLSModel::InitialExec) {
2477 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2478 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2479 } else if (Model == TLSModel::LocalDynamic) {
2480 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2481 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2482 // the beginning of the module's TLS region, followed by a DTPREL offset
2485 // These accesses will need deduplicating if there's more than one.
2486 ARM64FunctionInfo *MFI =
2487 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2488 MFI->incNumLocalDynamicTLSAccesses();
2490 // Accesses used in this sequence go via the TLS descriptor which lives in
2491 // the GOT. Prepare an address we can use to handle this.
2492 SDValue HiDesc = DAG.getTargetExternalSymbol(
2493 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2494 SDValue LoDesc = DAG.getTargetExternalSymbol(
2495 "_TLS_MODULE_BASE_", PtrVT,
2496 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2498 // First argument to the descriptor call is the address of the descriptor
2500 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2501 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2503 // The call needs a relocation too for linker relaxation. It doesn't make
2504 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2506 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2509 // Now we can calculate the offset from TPIDR_EL0 to this module's
2510 // thread-local area.
2511 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2513 // Now use :dtprel_whatever: operations to calculate this variable's offset
2514 // in its thread-storage area.
2515 SDValue HiVar = DAG.getTargetGlobalAddress(
2516 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2517 SDValue LoVar = DAG.getTargetGlobalAddress(
2518 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2521 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2522 DAG.getTargetConstant(16, MVT::i32)),
2524 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2525 DAG.getTargetConstant(0, MVT::i32)),
2528 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2529 } else if (Model == TLSModel::GeneralDynamic) {
2530 // Accesses used in this sequence go via the TLS descriptor which lives in
2531 // the GOT. Prepare an address we can use to handle this.
2532 SDValue HiDesc = DAG.getTargetGlobalAddress(
2533 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2534 SDValue LoDesc = DAG.getTargetGlobalAddress(
2536 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2538 // First argument to the descriptor call is the address of the descriptor
2540 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2541 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2543 // The call needs a relocation too for linker relaxation. It doesn't make
2544 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2547 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2549 // Finally we can make a call to calculate the offset from tpidr_el0.
2550 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2552 llvm_unreachable("Unsupported ELF TLS access model");
2554 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2557 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2558 SelectionDAG &DAG) const {
2559 if (Subtarget->isTargetDarwin())
2560 return LowerDarwinGlobalTLSAddress(Op, DAG);
2561 else if (Subtarget->isTargetELF())
2562 return LowerELFGlobalTLSAddress(Op, DAG);
2564 llvm_unreachable("Unexpected platform trying to use TLS");
2566 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2567 SDValue Chain = Op.getOperand(0);
2568 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2569 SDValue LHS = Op.getOperand(2);
2570 SDValue RHS = Op.getOperand(3);
2571 SDValue Dest = Op.getOperand(4);
2574 // Handle f128 first, since lowering it will result in comparing the return
2575 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2576 // is expecting to deal with.
2577 if (LHS.getValueType() == MVT::f128) {
2578 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2580 // If softenSetCCOperands returned a scalar, we need to compare the result
2581 // against zero to select between true and false values.
2582 if (!RHS.getNode()) {
2583 RHS = DAG.getConstant(0, LHS.getValueType());
2588 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2590 unsigned Opc = LHS.getOpcode();
2591 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2592 cast<ConstantSDNode>(RHS)->isOne() &&
2593 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2594 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2595 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2596 "Unexpected condition code.");
2597 // Only lower legal XALUO ops.
2598 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2601 // The actual operation with overflow check.
2602 ARM64CC::CondCode OFCC;
2603 SDValue Value, Overflow;
2604 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2606 if (CC == ISD::SETNE)
2607 OFCC = getInvertedCondCode(OFCC);
2608 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2610 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2614 if (LHS.getValueType().isInteger()) {
2615 assert((LHS.getValueType() == RHS.getValueType()) &&
2616 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2618 // If the RHS of the comparison is zero, we can potentially fold this
2619 // to a specialized branch.
2620 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2621 if (RHSC && RHSC->getZExtValue() == 0) {
2622 if (CC == ISD::SETEQ) {
2623 // See if we can use a TBZ to fold in an AND as well.
2624 // TBZ has a smaller branch displacement than CBZ. If the offset is
2625 // out of bounds, a late MI-layer pass rewrites branches.
2626 // 403.gcc is an example that hits this case.
2627 if (LHS.getOpcode() == ISD::AND &&
2628 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2629 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2630 SDValue Test = LHS.getOperand(0);
2631 uint64_t Mask = LHS.getConstantOperandVal(1);
2633 // TBZ only operates on i64's, but the ext should be free.
2634 if (Test.getValueType() == MVT::i32)
2635 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2637 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
2638 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2641 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2642 } else if (CC == ISD::SETNE) {
2643 // See if we can use a TBZ to fold in an AND as well.
2644 // TBZ has a smaller branch displacement than CBZ. If the offset is
2645 // out of bounds, a late MI-layer pass rewrites branches.
2646 // 403.gcc is an example that hits this case.
2647 if (LHS.getOpcode() == ISD::AND &&
2648 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2649 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2650 SDValue Test = LHS.getOperand(0);
2651 uint64_t Mask = LHS.getConstantOperandVal(1);
2653 // TBNZ only operates on i64's, but the ext should be free.
2654 if (Test.getValueType() == MVT::i32)
2655 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2657 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2658 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2661 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2666 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2667 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2671 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2673 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2674 // clean. Some of them require two branches to implement.
2675 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2676 ARM64CC::CondCode CC1, CC2;
2677 changeFPCCToARM64CC(CC, CC1, CC2);
2678 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2680 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2681 if (CC2 != ARM64CC::AL) {
2682 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2683 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2690 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2691 SelectionDAG &DAG) const {
2692 EVT VT = Op.getValueType();
2695 SDValue In1 = Op.getOperand(0);
2696 SDValue In2 = Op.getOperand(1);
2697 EVT SrcVT = In2.getValueType();
2699 if (SrcVT == MVT::f32 && VT == MVT::f64)
2700 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2701 else if (SrcVT == MVT::f64 && VT == MVT::f32)
2702 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
2704 // FIXME: Src type is different, bail out for now. Can VT really be a
2711 SDValue EltMask, VecVal1, VecVal2;
2712 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
2715 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
2717 if (!VT.isVector()) {
2718 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2719 DAG.getUNDEF(VecVT), In1);
2720 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2721 DAG.getUNDEF(VecVT), In2);
2723 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2724 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2726 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
2730 // We want to materialize a mask with the the high bit set, but the AdvSIMD
2731 // immediate moves cannot materialize that in a single instruction for
2732 // 64-bit elements. Instead, materialize zero and then negate it.
2733 EltMask = DAG.getConstant(0, EltVT);
2735 if (!VT.isVector()) {
2736 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2737 DAG.getUNDEF(VecVT), In1);
2738 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2739 DAG.getUNDEF(VecVT), In2);
2741 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2742 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2745 llvm_unreachable("Invalid type for copysign!");
2748 std::vector<SDValue> BuildVectorOps;
2749 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
2750 BuildVectorOps.push_back(EltMask);
2752 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
2754 // If we couldn't materialize the mask above, then the mask vector will be
2755 // the zero vector, and we need to negate it here.
2756 if (VT == MVT::f64 || VT == MVT::v2f64) {
2757 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
2758 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
2759 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
2763 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
2766 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
2767 else if (VT == MVT::f64)
2768 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
2770 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
2773 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
2774 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
2775 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
2778 // While there is no integer popcount instruction, it can
2779 // be more efficiently lowered to the following sequence that uses
2780 // AdvSIMD registers/instructions as long as the copies to/from
2781 // the AdvSIMD registers are cheap.
2782 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
2783 // CNT V0.8B, V0.8B // 8xbyte pop-counts
2784 // ADDV B0, V0.8B // sum 8xbyte pop-counts
2785 // UMOV X0, V0.B[0] // copy byte result back to integer reg
2786 SDValue Val = Op.getOperand(0);
2788 EVT VT = Op.getValueType();
2789 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
2792 if (VT == MVT::i32) {
2793 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
2795 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
2797 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
2800 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
2801 SDValue UaddLV = DAG.getNode(
2802 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2803 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
2806 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
2810 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2812 if (Op.getValueType().isVector())
2813 return LowerVSETCC(Op, DAG);
2815 SDValue LHS = Op.getOperand(0);
2816 SDValue RHS = Op.getOperand(1);
2817 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2820 // We chose ZeroOrOneBooleanContents, so use zero and one.
2821 EVT VT = Op.getValueType();
2822 SDValue TVal = DAG.getConstant(1, VT);
2823 SDValue FVal = DAG.getConstant(0, VT);
2825 // Handle f128 first, since one possible outcome is a normal integer
2826 // comparison which gets picked up by the next if statement.
2827 if (LHS.getValueType() == MVT::f128) {
2828 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2830 // If softenSetCCOperands returned a scalar, use it.
2831 if (!RHS.getNode()) {
2832 assert(LHS.getValueType() == Op.getValueType() &&
2833 "Unexpected setcc expansion!");
2838 if (LHS.getValueType().isInteger()) {
2841 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
2843 // Note that we inverted the condition above, so we reverse the order of
2844 // the true and false operands here. This will allow the setcc to be
2845 // matched to a single CSINC instruction.
2846 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
2849 // Now we know we're dealing with FP values.
2850 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2852 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
2853 // and do the comparison.
2854 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2856 ARM64CC::CondCode CC1, CC2;
2857 changeFPCCToARM64CC(CC, CC1, CC2);
2858 if (CC2 == ARM64CC::AL) {
2859 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
2860 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2862 // Note that we inverted the condition above, so we reverse the order of
2863 // the true and false operands here. This will allow the setcc to be
2864 // matched to a single CSINC instruction.
2865 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
2867 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2868 // clean. Some of them require two CSELs to implement. As is in this case,
2869 // we emit the first CSEL and then emit a second using the output of the
2870 // first as the RHS. We're effectively OR'ing the two CC's together.
2872 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
2873 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2874 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2876 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2877 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
2881 /// A SELECT_CC operation is really some kind of max or min if both values being
2882 /// compared are, in some sense, equal to the results in either case. However,
2883 /// it is permissible to compare f32 values and produce directly extended f64
2886 /// Extending the comparison operands would also be allowed, but is less likely
2887 /// to happen in practice since their use is right here. Note that truncate
2888 /// operations would *not* be semantically equivalent.
2889 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
2893 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
2894 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
2895 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
2896 Result.getValueType() == MVT::f64) {
2898 APFloat CmpVal = CCmp->getValueAPF();
2899 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
2900 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
2903 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
2906 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2907 SDValue CC = Op->getOperand(0);
2908 SDValue TVal = Op->getOperand(1);
2909 SDValue FVal = Op->getOperand(2);
2912 unsigned Opc = CC.getOpcode();
2913 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
2915 if (CC.getResNo() == 1 &&
2916 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2917 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2918 // Only lower legal XALUO ops.
2919 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
2922 ARM64CC::CondCode OFCC;
2923 SDValue Value, Overflow;
2924 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
2925 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2927 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
2931 if (CC.getOpcode() == ISD::SETCC)
2932 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
2933 cast<CondCodeSDNode>(CC.getOperand(2))->get());
2935 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
2939 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
2940 SelectionDAG &DAG) const {
2941 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2942 SDValue LHS = Op.getOperand(0);
2943 SDValue RHS = Op.getOperand(1);
2944 SDValue TVal = Op.getOperand(2);
2945 SDValue FVal = Op.getOperand(3);
2948 // Handle f128 first, because it will result in a comparison of some RTLIB
2949 // call result against zero.
2950 if (LHS.getValueType() == MVT::f128) {
2951 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2953 // If softenSetCCOperands returned a scalar, we need to compare the result
2954 // against zero to select between true and false values.
2955 if (!RHS.getNode()) {
2956 RHS = DAG.getConstant(0, LHS.getValueType());
2961 // Handle integers first.
2962 if (LHS.getValueType().isInteger()) {
2963 assert((LHS.getValueType() == RHS.getValueType()) &&
2964 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2966 unsigned Opcode = ARM64ISD::CSEL;
2968 // If both the TVal and the FVal are constants, see if we can swap them in
2969 // order to for a CSINV or CSINC out of them.
2970 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2971 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2973 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2974 std::swap(TVal, FVal);
2975 std::swap(CTVal, CFVal);
2976 CC = ISD::getSetCCInverse(CC, true);
2977 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
2978 std::swap(TVal, FVal);
2979 std::swap(CTVal, CFVal);
2980 CC = ISD::getSetCCInverse(CC, true);
2981 } else if (TVal.getOpcode() == ISD::XOR) {
2982 // If TVal is a NOT we want to swap TVal and FVal so that we can match
2983 // with a CSINV rather than a CSEL.
2984 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
2986 if (CVal && CVal->isAllOnesValue()) {
2987 std::swap(TVal, FVal);
2988 std::swap(CTVal, CFVal);
2989 CC = ISD::getSetCCInverse(CC, true);
2991 } else if (TVal.getOpcode() == ISD::SUB) {
2992 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
2993 // that we can match with a CSNEG rather than a CSEL.
2994 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
2996 if (CVal && CVal->isNullValue()) {
2997 std::swap(TVal, FVal);
2998 std::swap(CTVal, CFVal);
2999 CC = ISD::getSetCCInverse(CC, true);
3001 } else if (CTVal && CFVal) {
3002 const int64_t TrueVal = CTVal->getSExtValue();
3003 const int64_t FalseVal = CFVal->getSExtValue();
3006 // If both TVal and FVal are constants, see if FVal is the
3007 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3008 // instead of a CSEL in that case.
3009 if (TrueVal == ~FalseVal) {
3010 Opcode = ARM64ISD::CSINV;
3011 } else if (TrueVal == -FalseVal) {
3012 Opcode = ARM64ISD::CSNEG;
3013 } else if (TVal.getValueType() == MVT::i32) {
3014 // If our operands are only 32-bit wide, make sure we use 32-bit
3015 // arithmetic for the check whether we can use CSINC. This ensures that
3016 // the addition in the check will wrap around properly in case there is
3017 // an overflow (which would not be the case if we do the check with
3018 // 64-bit arithmetic).
3019 const uint32_t TrueVal32 = CTVal->getZExtValue();
3020 const uint32_t FalseVal32 = CFVal->getZExtValue();
3022 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3023 Opcode = ARM64ISD::CSINC;
3025 if (TrueVal32 > FalseVal32) {
3029 // 64-bit check whether we can use CSINC.
3030 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3031 Opcode = ARM64ISD::CSINC;
3033 if (TrueVal > FalseVal) {
3038 // Swap TVal and FVal if necessary.
3040 std::swap(TVal, FVal);
3041 std::swap(CTVal, CFVal);
3042 CC = ISD::getSetCCInverse(CC, true);
3045 if (Opcode != ARM64ISD::CSEL) {
3046 // Drop FVal since we can get its value by simply inverting/negating
3053 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3055 EVT VT = Op.getValueType();
3056 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3059 // Now we know we're dealing with FP values.
3060 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3061 assert(LHS.getValueType() == RHS.getValueType());
3062 EVT VT = Op.getValueType();
3064 // Try to match this select into a max/min operation, which have dedicated
3065 // opcode in the instruction set.
3066 // NOTE: This is not correct in the presence of NaNs, so we only enable this
3068 if (getTargetMachine().Options.NoNaNsFPMath) {
3069 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3070 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3071 CC = ISD::getSetCCSwappedOperands(CC);
3072 std::swap(TVal, FVal);
3075 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3076 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3086 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3094 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3100 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3101 // and do the comparison.
3102 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3104 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3105 // clean. Some of them require two CSELs to implement.
3106 ARM64CC::CondCode CC1, CC2;
3107 changeFPCCToARM64CC(CC, CC1, CC2);
3108 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3109 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3111 // If we need a second CSEL, emit it, using the output of the first as the
3112 // RHS. We're effectively OR'ing the two CC's together.
3113 if (CC2 != ARM64CC::AL) {
3114 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3115 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3118 // Otherwise, return the output of the first CSEL.
3122 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3123 SelectionDAG &DAG) const {
3124 // Jump table entries as PC relative offsets. No additional tweaking
3125 // is necessary here. Just get the address of the jump table.
3126 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3127 EVT PtrVT = getPointerTy();
3130 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3131 !Subtarget->isTargetMachO()) {
3132 const unsigned char MO_NC = ARM64II::MO_NC;
3134 ARM64ISD::WrapperLarge, DL, PtrVT,
3135 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G3),
3136 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G2 | MO_NC),
3137 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G1 | MO_NC),
3138 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G0 | MO_NC));
3141 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3142 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3143 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3144 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3145 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3148 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3149 SelectionDAG &DAG) const {
3150 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3151 EVT PtrVT = getPointerTy();
3154 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3155 // Use the GOT for the large code model on iOS.
3156 if (Subtarget->isTargetMachO()) {
3157 SDValue GotAddr = DAG.getTargetConstantPool(
3158 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3160 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3163 const unsigned char MO_NC = ARM64II::MO_NC;
3165 ARM64ISD::WrapperLarge, DL, PtrVT,
3166 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3167 CP->getOffset(), ARM64II::MO_G3),
3168 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3169 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3170 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3171 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3172 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3173 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3175 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3176 // ELF, the only valid one on Darwin.
3178 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3179 CP->getOffset(), ARM64II::MO_PAGE);
3180 SDValue Lo = DAG.getTargetConstantPool(
3181 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3182 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3184 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3185 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3189 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3190 SelectionDAG &DAG) const {
3191 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3192 EVT PtrVT = getPointerTy();
3194 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3195 !Subtarget->isTargetMachO()) {
3196 const unsigned char MO_NC = ARM64II::MO_NC;
3198 ARM64ISD::WrapperLarge, DL, PtrVT,
3199 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3200 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3201 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3202 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3204 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3205 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3207 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3208 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3212 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3213 SelectionDAG &DAG) const {
3214 ARM64FunctionInfo *FuncInfo =
3215 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3219 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3220 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3221 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3222 MachinePointerInfo(SV), false, false, 0);
3225 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3226 SelectionDAG &DAG) const {
3227 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3228 // Standard, section B.3.
3229 MachineFunction &MF = DAG.getMachineFunction();
3230 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3233 SDValue Chain = Op.getOperand(0);
3234 SDValue VAList = Op.getOperand(1);
3235 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3236 SmallVector<SDValue, 4> MemOps;
3238 // void *__stack at offset 0
3240 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3241 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3242 MachinePointerInfo(SV), false, false, 8));
3244 // void *__gr_top at offset 8
3245 int GPRSize = FuncInfo->getVarArgsGPRSize();
3247 SDValue GRTop, GRTopAddr;
3249 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3250 DAG.getConstant(8, getPointerTy()));
3252 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3253 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3254 DAG.getConstant(GPRSize, getPointerTy()));
3256 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3257 MachinePointerInfo(SV, 8), false, false, 8));
3260 // void *__vr_top at offset 16
3261 int FPRSize = FuncInfo->getVarArgsFPRSize();
3263 SDValue VRTop, VRTopAddr;
3264 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3265 DAG.getConstant(16, getPointerTy()));
3267 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3268 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3269 DAG.getConstant(FPRSize, getPointerTy()));
3271 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3272 MachinePointerInfo(SV, 16), false, false, 8));
3275 // int __gr_offs at offset 24
3276 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3277 DAG.getConstant(24, getPointerTy()));
3278 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3279 GROffsAddr, MachinePointerInfo(SV, 24), false,
3282 // int __vr_offs at offset 28
3283 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3284 DAG.getConstant(28, getPointerTy()));
3285 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3286 VROffsAddr, MachinePointerInfo(SV, 28), false,
3289 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3292 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3293 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3294 : LowerAAPCS_VASTART(Op, DAG);
3297 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3298 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3300 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3301 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3302 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3304 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3305 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3306 8, false, false, MachinePointerInfo(DestSV),
3307 MachinePointerInfo(SrcSV));
3310 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3311 assert(Subtarget->isTargetDarwin() &&
3312 "automatic va_arg instruction only works on Darwin");
3314 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3315 EVT VT = Op.getValueType();
3317 SDValue Chain = Op.getOperand(0);
3318 SDValue Addr = Op.getOperand(1);
3319 unsigned Align = Op.getConstantOperandVal(3);
3321 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3322 MachinePointerInfo(V), false, false, false, 0);
3323 Chain = VAList.getValue(1);
3326 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3327 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3328 DAG.getConstant(Align - 1, getPointerTy()));
3329 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3330 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3333 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3334 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3336 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3337 // up to 64 bits. At the very least, we have to increase the striding of the
3338 // vaargs list to match this, and for FP values we need to introduce
3339 // FP_ROUND nodes as well.
3340 if (VT.isInteger() && !VT.isVector())
3342 bool NeedFPTrunc = false;
3343 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3348 // Increment the pointer, VAList, to the next vaarg
3349 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3350 DAG.getConstant(ArgSize, getPointerTy()));
3351 // Store the incremented VAList to the legalized pointer
3352 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3355 // Load the actual argument out of the pointer VAList
3357 // Load the value as an f64.
3358 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3359 MachinePointerInfo(), false, false, false, 0);
3360 // Round the value down to an f32.
3361 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3362 DAG.getIntPtrConstant(1));
3363 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3364 // Merge the rounded value with the chain output of the load.
3365 return DAG.getMergeValues(Ops, DL);
3368 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3372 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3373 SelectionDAG &DAG) const {
3374 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3375 MFI->setFrameAddressIsTaken(true);
3377 EVT VT = Op.getValueType();
3379 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3380 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3382 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3383 MachinePointerInfo(), false, false, false, 0);
3387 // FIXME? Maybe this could be a TableGen attribute on some registers and
3388 // this table could be generated automatically from RegInfo.
3389 unsigned ARM64TargetLowering::getRegisterByName(const char* RegName) const {
3390 unsigned Reg = StringSwitch<unsigned>(RegName)
3391 .Case("sp", ARM64::SP)
3395 report_fatal_error("Invalid register name global variable");
3398 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3399 SelectionDAG &DAG) const {
3400 MachineFunction &MF = DAG.getMachineFunction();
3401 MachineFrameInfo *MFI = MF.getFrameInfo();
3402 MFI->setReturnAddressIsTaken(true);
3404 EVT VT = Op.getValueType();
3406 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3408 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3409 SDValue Offset = DAG.getConstant(8, getPointerTy());
3410 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3411 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3412 MachinePointerInfo(), false, false, false, 0);
3415 // Return LR, which contains the return address. Mark it an implicit live-in.
3416 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3417 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3420 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3421 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3422 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3423 SelectionDAG &DAG) const {
3424 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3425 EVT VT = Op.getValueType();
3426 unsigned VTBits = VT.getSizeInBits();
3428 SDValue ShOpLo = Op.getOperand(0);
3429 SDValue ShOpHi = Op.getOperand(1);
3430 SDValue ShAmt = Op.getOperand(2);
3432 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3434 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3436 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3437 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3438 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3439 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3440 DAG.getConstant(VTBits, MVT::i64));
3441 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3443 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3444 ISD::SETGE, dl, DAG);
3445 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3447 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3448 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3450 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3452 // ARM64 shifts larger than the register width are wrapped rather than
3453 // clamped, so we can't just emit "hi >> x".
3454 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3455 SDValue TrueValHi = Opc == ISD::SRA
3456 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3457 DAG.getConstant(VTBits - 1, MVT::i64))
3458 : DAG.getConstant(0, VT);
3460 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3462 SDValue Ops[2] = { Lo, Hi };
3463 return DAG.getMergeValues(Ops, dl);
3466 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3467 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3468 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3469 SelectionDAG &DAG) const {
3470 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3471 EVT VT = Op.getValueType();
3472 unsigned VTBits = VT.getSizeInBits();
3474 SDValue ShOpLo = Op.getOperand(0);
3475 SDValue ShOpHi = Op.getOperand(1);
3476 SDValue ShAmt = Op.getOperand(2);
3479 assert(Op.getOpcode() == ISD::SHL_PARTS);
3480 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3481 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3482 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3483 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3484 DAG.getConstant(VTBits, MVT::i64));
3485 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3486 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3488 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3490 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3491 ISD::SETGE, dl, DAG);
3492 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3493 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3495 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3496 // so we can't just emit "lo << a" if a is too big.
3497 SDValue TrueValLo = DAG.getConstant(0, VT);
3498 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3500 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3502 SDValue Ops[2] = { Lo, Hi };
3503 return DAG.getMergeValues(Ops, dl);
3507 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3508 // The ARM64 target doesn't support folding offsets into global addresses.
3512 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3513 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3514 // FIXME: We should be able to handle f128 as well with a clever lowering.
3515 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3519 return ARM64_AM::getFP64Imm(Imm) != -1;
3520 else if (VT == MVT::f32)
3521 return ARM64_AM::getFP32Imm(Imm) != -1;
3525 //===----------------------------------------------------------------------===//
3526 // ARM64 Optimization Hooks
3527 //===----------------------------------------------------------------------===//
3529 //===----------------------------------------------------------------------===//
3530 // ARM64 Inline Assembly Support
3531 //===----------------------------------------------------------------------===//
3533 // Table of Constraints
3534 // TODO: This is the current set of constraints supported by ARM for the
3535 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3537 // r - A general register
3538 // w - An FP/SIMD register of some size in the range v0-v31
3539 // x - An FP/SIMD register of some size in the range v0-v15
3540 // I - Constant that can be used with an ADD instruction
3541 // J - Constant that can be used with a SUB instruction
3542 // K - Constant that can be used with a 32-bit logical instruction
3543 // L - Constant that can be used with a 64-bit logical instruction
3544 // M - Constant that can be used as a 32-bit MOV immediate
3545 // N - Constant that can be used as a 64-bit MOV immediate
3546 // Q - A memory reference with base register and no offset
3547 // S - A symbolic address
3548 // Y - Floating point constant zero
3549 // Z - Integer constant zero
3551 // Note that general register operands will be output using their 64-bit x
3552 // register name, whatever the size of the variable, unless the asm operand
3553 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3554 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3557 /// getConstraintType - Given a constraint letter, return the type of
3558 /// constraint it is for this target.
3559 ARM64TargetLowering::ConstraintType
3560 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3561 if (Constraint.size() == 1) {
3562 switch (Constraint[0]) {
3569 return C_RegisterClass;
3570 // An address with a single base register. Due to the way we
3571 // currently handle addresses it is the same as 'r'.
3576 return TargetLowering::getConstraintType(Constraint);
3579 /// Examine constraint type and operand type and determine a weight value.
3580 /// This object must already have been set up with the operand type
3581 /// and the current alternative constraint selected.
3582 TargetLowering::ConstraintWeight
3583 ARM64TargetLowering::getSingleConstraintMatchWeight(
3584 AsmOperandInfo &info, const char *constraint) const {
3585 ConstraintWeight weight = CW_Invalid;
3586 Value *CallOperandVal = info.CallOperandVal;
3587 // If we don't have a value, we can't do a match,
3588 // but allow it at the lowest weight.
3589 if (!CallOperandVal)
3591 Type *type = CallOperandVal->getType();
3592 // Look at the constraint type.
3593 switch (*constraint) {
3595 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3599 if (type->isFloatingPointTy() || type->isVectorTy())
3600 weight = CW_Register;
3603 weight = CW_Constant;
3609 std::pair<unsigned, const TargetRegisterClass *>
3610 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3612 if (Constraint.size() == 1) {
3613 switch (Constraint[0]) {
3615 if (VT.getSizeInBits() == 64)
3616 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3617 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3620 return std::make_pair(0U, &ARM64::FPR32RegClass);
3621 if (VT.getSizeInBits() == 64)
3622 return std::make_pair(0U, &ARM64::FPR64RegClass);
3623 if (VT.getSizeInBits() == 128)
3624 return std::make_pair(0U, &ARM64::FPR128RegClass);
3626 // The instructions that this constraint is designed for can
3627 // only take 128-bit registers so just use that regclass.
3629 if (VT.getSizeInBits() == 128)
3630 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
3634 if (StringRef("{cc}").equals_lower(Constraint))
3635 return std::make_pair(unsigned(ARM64::NZCV), &ARM64::CCRRegClass);
3637 // Use the default implementation in TargetLowering to convert the register
3638 // constraint into a member of a register class.
3639 std::pair<unsigned, const TargetRegisterClass *> Res;
3640 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3642 // Not found as a standard register?
3644 unsigned Size = Constraint.size();
3645 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3646 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3647 const std::string Reg =
3648 std::string(&Constraint[2], &Constraint[Size - 1]);
3649 int RegNo = atoi(Reg.c_str());
3650 if (RegNo >= 0 && RegNo <= 31) {
3651 // v0 - v31 are aliases of q0 - q31.
3652 // By default we'll emit v0-v31 for this unless there's a modifier where
3653 // we'll emit the correct register as well.
3654 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
3655 Res.second = &ARM64::FPR128RegClass;
3663 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3664 /// vector. If it is invalid, don't add anything to Ops.
3665 void ARM64TargetLowering::LowerAsmOperandForConstraint(
3666 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3667 SelectionDAG &DAG) const {
3670 // Currently only support length 1 constraints.
3671 if (Constraint.length() != 1)
3674 char ConstraintLetter = Constraint[0];
3675 switch (ConstraintLetter) {
3679 // This set of constraints deal with valid constants for various instructions.
3680 // Validate and return a target constant for them if we can.
3682 // 'z' maps to xzr or wzr so it needs an input of 0.
3683 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3684 if (!C || C->getZExtValue() != 0)
3687 if (Op.getValueType() == MVT::i64)
3688 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
3690 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
3700 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3704 // Grab the value and do some validation.
3705 uint64_t CVal = C->getZExtValue();
3706 switch (ConstraintLetter) {
3707 // The I constraint applies only to simple ADD or SUB immediate operands:
3708 // i.e. 0 to 4095 with optional shift by 12
3709 // The J constraint applies only to ADD or SUB immediates that would be
3710 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
3711 // instruction [or vice versa], in other words -1 to -4095 with optional
3712 // left shift by 12.
3714 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
3718 uint64_t NVal = -C->getSExtValue();
3719 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
3723 // The K and L constraints apply *only* to logical immediates, including
3724 // what used to be the MOVI alias for ORR (though the MOVI alias has now
3725 // been removed and MOV should be used). So these constraints have to
3726 // distinguish between bit patterns that are valid 32-bit or 64-bit
3727 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
3728 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
3731 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3735 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3738 // The M and N constraints are a superset of K and L respectively, for use
3739 // with the MOV (immediate) alias. As well as the logical immediates they
3740 // also match 32 or 64-bit immediates that can be loaded either using a
3741 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
3742 // (M) or 64-bit 0x1234000000000000 (N) etc.
3743 // As a note some of this code is liberally stolen from the asm parser.
3745 if (!isUInt<32>(CVal))
3747 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3749 if ((CVal & 0xFFFF) == CVal)
3751 if ((CVal & 0xFFFF0000ULL) == CVal)
3753 uint64_t NCVal = ~(uint32_t)CVal;
3754 if ((NCVal & 0xFFFFULL) == NCVal)
3756 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3761 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3763 if ((CVal & 0xFFFFULL) == CVal)
3765 if ((CVal & 0xFFFF0000ULL) == CVal)
3767 if ((CVal & 0xFFFF00000000ULL) == CVal)
3769 if ((CVal & 0xFFFF000000000000ULL) == CVal)
3771 uint64_t NCVal = ~CVal;
3772 if ((NCVal & 0xFFFFULL) == NCVal)
3774 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3776 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
3778 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
3786 // All assembler immediates are 64-bit integers.
3787 Result = DAG.getTargetConstant(CVal, MVT::i64);
3791 if (Result.getNode()) {
3792 Ops.push_back(Result);
3796 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3799 //===----------------------------------------------------------------------===//
3800 // ARM64 Advanced SIMD Support
3801 //===----------------------------------------------------------------------===//
3803 /// WidenVector - Given a value in the V64 register class, produce the
3804 /// equivalent value in the V128 register class.
3805 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
3806 EVT VT = V64Reg.getValueType();
3807 unsigned NarrowSize = VT.getVectorNumElements();
3808 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3809 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
3812 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
3813 V64Reg, DAG.getConstant(0, MVT::i32));
3816 /// getExtFactor - Determine the adjustment factor for the position when
3817 /// generating an "extract from vector registers" instruction.
3818 static unsigned getExtFactor(SDValue &V) {
3819 EVT EltType = V.getValueType().getVectorElementType();
3820 return EltType.getSizeInBits() / 8;
3823 /// NarrowVector - Given a value in the V128 register class, produce the
3824 /// equivalent value in the V64 register class.
3825 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
3826 EVT VT = V128Reg.getValueType();
3827 unsigned WideSize = VT.getVectorNumElements();
3828 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3829 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
3832 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
3835 // Gather data to see if the operation can be modelled as a
3836 // shuffle in combination with VEXTs.
3837 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
3838 SelectionDAG &DAG) const {
3840 EVT VT = Op.getValueType();
3841 unsigned NumElts = VT.getVectorNumElements();
3843 SmallVector<SDValue, 2> SourceVecs;
3844 SmallVector<unsigned, 2> MinElts;
3845 SmallVector<unsigned, 2> MaxElts;
3847 for (unsigned i = 0; i < NumElts; ++i) {
3848 SDValue V = Op.getOperand(i);
3849 if (V.getOpcode() == ISD::UNDEF)
3851 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3852 // A shuffle can only come from building a vector from various
3853 // elements of other vectors.
3857 // Record this extraction against the appropriate vector if possible...
3858 SDValue SourceVec = V.getOperand(0);
3859 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3860 bool FoundSource = false;
3861 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3862 if (SourceVecs[j] == SourceVec) {
3863 if (MinElts[j] > EltNo)
3865 if (MaxElts[j] < EltNo)
3872 // Or record a new source if not...
3874 SourceVecs.push_back(SourceVec);
3875 MinElts.push_back(EltNo);
3876 MaxElts.push_back(EltNo);
3880 // Currently only do something sane when at most two source vectors
3882 if (SourceVecs.size() > 2)
3885 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3886 int VEXTOffsets[2] = { 0, 0 };
3888 // This loop extracts the usage patterns of the source vectors
3889 // and prepares appropriate SDValues for a shuffle if possible.
3890 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3891 if (SourceVecs[i].getValueType() == VT) {
3892 // No VEXT necessary
3893 ShuffleSrcs[i] = SourceVecs[i];
3896 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3897 // We can pad out the smaller vector for free, so if it's part of a
3899 ShuffleSrcs[i] = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, SourceVecs[i],
3900 DAG.getUNDEF(SourceVecs[i].getValueType()));
3904 // Don't attempt to extract subvectors from BUILD_VECTOR sources
3905 // that expand or trunc the original value.
3906 // TODO: We can try to bitcast and ANY_EXTEND the result but
3907 // we need to consider the cost of vector ANY_EXTEND, and the
3908 // legality of all the types.
3909 if (SourceVecs[i].getValueType().getVectorElementType() !=
3910 VT.getVectorElementType())
3913 // Since only 64-bit and 128-bit vectors are legal on ARM and
3914 // we've eliminated the other cases...
3915 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3916 "unexpected vector sizes in ReconstructShuffle");
3918 if (MaxElts[i] - MinElts[i] >= NumElts) {
3919 // Span too large for a VEXT to cope
3923 if (MinElts[i] >= NumElts) {
3924 // The extraction can just take the second half
3925 VEXTOffsets[i] = NumElts;
3927 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3928 DAG.getIntPtrConstant(NumElts));
3929 } else if (MaxElts[i] < NumElts) {
3930 // The extraction can just take the first half
3932 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3933 SourceVecs[i], DAG.getIntPtrConstant(0));
3935 // An actual VEXT is needed
3936 VEXTOffsets[i] = MinElts[i];
3937 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3938 SourceVecs[i], DAG.getIntPtrConstant(0));
3940 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3941 DAG.getIntPtrConstant(NumElts));
3942 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
3943 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
3944 DAG.getConstant(Imm, MVT::i32));
3948 SmallVector<int, 8> Mask;
3950 for (unsigned i = 0; i < NumElts; ++i) {
3951 SDValue Entry = Op.getOperand(i);
3952 if (Entry.getOpcode() == ISD::UNDEF) {
3957 SDValue ExtractVec = Entry.getOperand(0);
3959 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
3960 if (ExtractVec == SourceVecs[0]) {
3961 Mask.push_back(ExtractElt - VEXTOffsets[0]);
3963 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
3967 // Final check before we try to produce nonsense...
3968 if (isShuffleMaskLegal(Mask, VT))
3969 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
3975 // check if an EXT instruction can handle the shuffle mask when the
3976 // vector sources of the shuffle are the same.
3977 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3978 unsigned NumElts = VT.getVectorNumElements();
3980 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3986 // If this is a VEXT shuffle, the immediate value is the index of the first
3987 // element. The other shuffle indices must be the successive elements after
3989 unsigned ExpectedElt = Imm;
3990 for (unsigned i = 1; i < NumElts; ++i) {
3991 // Increment the expected index. If it wraps around, just follow it
3992 // back to index zero and keep going.
3994 if (ExpectedElt == NumElts)
3998 continue; // ignore UNDEF indices
3999 if (ExpectedElt != static_cast<unsigned>(M[i]))
4006 // check if an EXT instruction can handle the shuffle mask when the
4007 // vector sources of the shuffle are different.
4008 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4010 // Look for the first non-undef element.
4011 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4012 [](int Elt) {return Elt >= 0;});
4014 // Benefit form APInt to handle overflow when calculating expected element.
4015 unsigned NumElts = VT.getVectorNumElements();
4016 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4017 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4018 // The following shuffle indices must be the successive elements after the
4019 // first real element.
4020 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4021 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4022 if (FirstWrongElt != M.end())
4025 // The index of an EXT is the first element if it is not UNDEF.
4026 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4027 // value of the first element.
4028 // E.g. <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4029 // <-1, -1, 0, 1, ...> is treated as <IDX, IDX+1, 0, 1, ...>. IDX is
4030 // equal to the ExpectedElt.
4031 Imm = (M[0] >= 0) ? static_cast<unsigned>(M[0]) : ExpectedElt.getZExtValue();
4033 // If no beginning UNDEFs, do swap when M[0] >= NumElts.
4034 if (M[0] >= 0 && Imm >= NumElts) {
4037 } else if (M[0] < 0) {
4038 // Only do swap when beginning UNDEFs more than the first real element,
4039 if (*FirstRealElt < FirstRealElt - M.begin())
4048 /// isREVMask - Check if a vector shuffle corresponds to a REV
4049 /// instruction with the specified blocksize. (The order of the elements
4050 /// within each block of the vector is reversed.)
4051 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4052 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4053 "Only possible block sizes for REV are: 16, 32, 64");
4055 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4059 unsigned NumElts = VT.getVectorNumElements();
4060 unsigned BlockElts = M[0] + 1;
4061 // If the first shuffle index is UNDEF, be optimistic.
4063 BlockElts = BlockSize / EltSz;
4065 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4068 for (unsigned i = 0; i < NumElts; ++i) {
4070 continue; // ignore UNDEF indices
4071 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4078 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4079 unsigned NumElts = VT.getVectorNumElements();
4080 WhichResult = (M[0] == 0 ? 0 : 1);
4081 unsigned Idx = WhichResult * NumElts / 2;
4082 for (unsigned i = 0; i != NumElts; i += 2) {
4083 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4084 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4092 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4093 unsigned NumElts = VT.getVectorNumElements();
4094 WhichResult = (M[0] == 0 ? 0 : 1);
4095 for (unsigned i = 0; i != NumElts; ++i) {
4097 continue; // ignore UNDEF indices
4098 if ((unsigned)M[i] != 2 * i + WhichResult)
4105 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4106 unsigned NumElts = VT.getVectorNumElements();
4107 WhichResult = (M[0] == 0 ? 0 : 1);
4108 for (unsigned i = 0; i < NumElts; i += 2) {
4109 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4110 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4116 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4117 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4118 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4119 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4120 unsigned NumElts = VT.getVectorNumElements();
4121 WhichResult = (M[0] == 0 ? 0 : 1);
4122 unsigned Idx = WhichResult * NumElts / 2;
4123 for (unsigned i = 0; i != NumElts; i += 2) {
4124 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4125 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4133 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4134 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4135 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4136 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4137 unsigned Half = VT.getVectorNumElements() / 2;
4138 WhichResult = (M[0] == 0 ? 0 : 1);
4139 for (unsigned j = 0; j != 2; ++j) {
4140 unsigned Idx = WhichResult;
4141 for (unsigned i = 0; i != Half; ++i) {
4142 int MIdx = M[i + j * Half];
4143 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4152 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4153 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4154 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4155 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4156 unsigned NumElts = VT.getVectorNumElements();
4157 WhichResult = (M[0] == 0 ? 0 : 1);
4158 for (unsigned i = 0; i < NumElts; i += 2) {
4159 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4160 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4166 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4167 bool &DstIsLeft, int &Anomaly) {
4168 if (M.size() != static_cast<size_t>(NumInputElements))
4171 int NumLHSMatch = 0, NumRHSMatch = 0;
4172 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4174 for (int i = 0; i < NumInputElements; ++i) {
4184 LastLHSMismatch = i;
4186 if (M[i] == i + NumInputElements)
4189 LastRHSMismatch = i;
4192 if (NumLHSMatch == NumInputElements - 1) {
4194 Anomaly = LastLHSMismatch;
4196 } else if (NumRHSMatch == NumInputElements - 1) {
4198 Anomaly = LastRHSMismatch;
4205 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4206 if (VT.getSizeInBits() != 128)
4209 unsigned NumElts = VT.getVectorNumElements();
4211 for (int I = 0, E = NumElts / 2; I != E; I++) {
4216 int Offset = NumElts / 2;
4217 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4218 if (Mask[I] != I + SplitLHS * Offset)
4225 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4227 EVT VT = Op.getValueType();
4228 SDValue V0 = Op.getOperand(0);
4229 SDValue V1 = Op.getOperand(1);
4230 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4232 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4233 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4236 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4238 if (!isConcatMask(Mask, VT, SplitV0))
4241 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4242 VT.getVectorNumElements() / 2);
4244 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4245 DAG.getConstant(0, MVT::i64));
4247 if (V1.getValueType().getSizeInBits() == 128) {
4248 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4249 DAG.getConstant(0, MVT::i64));
4251 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4254 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4255 /// the specified operations to build the shuffle.
4256 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4257 SDValue RHS, SelectionDAG &DAG,
4259 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4260 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4261 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4264 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4273 OP_VUZPL, // VUZP, left result
4274 OP_VUZPR, // VUZP, right result
4275 OP_VZIPL, // VZIP, left result
4276 OP_VZIPR, // VZIP, right result
4277 OP_VTRNL, // VTRN, left result
4278 OP_VTRNR // VTRN, right result
4281 if (OpNum == OP_COPY) {
4282 if (LHSID == (1 * 9 + 2) * 9 + 3)
4284 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4288 SDValue OpLHS, OpRHS;
4289 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4290 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4291 EVT VT = OpLHS.getValueType();
4295 llvm_unreachable("Unknown shuffle opcode!");
4297 // VREV divides the vector in half and swaps within the half.
4298 if (VT.getVectorElementType() == MVT::i32 ||
4299 VT.getVectorElementType() == MVT::f32)
4300 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4301 // vrev <4 x i16> -> REV32
4302 if (VT.getVectorElementType() == MVT::i16)
4303 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4304 // vrev <4 x i8> -> REV16
4305 assert(VT.getVectorElementType() == MVT::i8);
4306 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4311 EVT EltTy = VT.getVectorElementType();
4313 if (EltTy == MVT::i8)
4314 Opcode = ARM64ISD::DUPLANE8;
4315 else if (EltTy == MVT::i16)
4316 Opcode = ARM64ISD::DUPLANE16;
4317 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4318 Opcode = ARM64ISD::DUPLANE32;
4319 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4320 Opcode = ARM64ISD::DUPLANE64;
4322 llvm_unreachable("Invalid vector element type?");
4324 if (VT.getSizeInBits() == 64)
4325 OpLHS = WidenVector(OpLHS, DAG);
4326 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4327 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4332 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4333 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4334 DAG.getConstant(Imm, MVT::i32));
4337 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4339 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4341 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4343 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4345 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4347 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4351 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4352 SelectionDAG &DAG) {
4353 // Check to see if we can use the TBL instruction.
4354 SDValue V1 = Op.getOperand(0);
4355 SDValue V2 = Op.getOperand(1);
4358 EVT EltVT = Op.getValueType().getVectorElementType();
4359 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4361 SmallVector<SDValue, 8> TBLMask;
4362 for (int Val : ShuffleMask) {
4363 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4364 unsigned Offset = Byte + Val * BytesPerElt;
4365 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4369 MVT IndexVT = MVT::v8i8;
4370 unsigned IndexLen = 8;
4371 if (Op.getValueType().getSizeInBits() == 128) {
4372 IndexVT = MVT::v16i8;
4376 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4377 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4380 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4382 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4383 Shuffle = DAG.getNode(
4384 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4385 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4386 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4387 makeArrayRef(TBLMask.data(), IndexLen)));
4389 if (IndexLen == 8) {
4390 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4391 Shuffle = DAG.getNode(
4392 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4393 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4394 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4395 makeArrayRef(TBLMask.data(), IndexLen)));
4397 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4398 // cannot currently represent the register constraints on the input
4400 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4401 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4402 // &TBLMask[0], IndexLen));
4403 Shuffle = DAG.getNode(
4404 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4405 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4406 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4407 makeArrayRef(TBLMask.data(), IndexLen)));
4410 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4413 static unsigned getDUPLANEOp(EVT EltType) {
4414 if (EltType == MVT::i8)
4415 return ARM64ISD::DUPLANE8;
4416 if (EltType == MVT::i16)
4417 return ARM64ISD::DUPLANE16;
4418 if (EltType == MVT::i32 || EltType == MVT::f32)
4419 return ARM64ISD::DUPLANE32;
4420 if (EltType == MVT::i64 || EltType == MVT::f64)
4421 return ARM64ISD::DUPLANE64;
4423 llvm_unreachable("Invalid vector element type?");
4426 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4427 SelectionDAG &DAG) const {
4429 EVT VT = Op.getValueType();
4431 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4433 // Convert shuffles that are directly supported on NEON to target-specific
4434 // DAG nodes, instead of keeping them as shuffles and matching them again
4435 // during code selection. This is more efficient and avoids the possibility
4436 // of inconsistencies between legalization and selection.
4437 ArrayRef<int> ShuffleMask = SVN->getMask();
4439 SDValue V1 = Op.getOperand(0);
4440 SDValue V2 = Op.getOperand(1);
4442 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4443 V1.getValueType().getSimpleVT())) {
4444 int Lane = SVN->getSplatIndex();
4445 // If this is undef splat, generate it via "just" vdup, if possible.
4449 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4450 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4452 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4453 // constant. If so, we can just reference the lane's definition directly.
4454 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4455 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4456 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4458 // Otherwise, duplicate from the lane of the input vector.
4459 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4461 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4462 // to make a vector of the same size as this SHUFFLE. We can ignore the
4463 // extract entirely, and canonicalise the concat using WidenVector.
4464 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4465 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4466 V1 = V1.getOperand(0);
4467 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4468 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4469 Lane -= Idx * VT.getVectorNumElements() / 2;
4470 V1 = WidenVector(V1.getOperand(Idx), DAG);
4471 } else if (VT.getSizeInBits() == 64)
4472 V1 = WidenVector(V1, DAG);
4474 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4477 if (isREVMask(ShuffleMask, VT, 64))
4478 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4479 if (isREVMask(ShuffleMask, VT, 32))
4480 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4481 if (isREVMask(ShuffleMask, VT, 16))
4482 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4484 bool ReverseEXT = false;
4486 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4489 Imm *= getExtFactor(V1);
4490 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4491 DAG.getConstant(Imm, MVT::i32));
4492 } else if (V2->getOpcode() == ISD::UNDEF &&
4493 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4494 Imm *= getExtFactor(V1);
4495 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4496 DAG.getConstant(Imm, MVT::i32));
4499 unsigned WhichResult;
4500 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4501 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4502 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4504 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4505 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4506 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4508 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4509 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4510 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4513 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4514 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4515 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4517 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4518 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4519 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4521 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4522 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4523 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4526 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4527 if (Concat.getNode())
4532 int NumInputElements = V1.getValueType().getVectorNumElements();
4533 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4534 SDValue DstVec = DstIsLeft ? V1 : V2;
4535 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4537 SDValue SrcVec = V1;
4538 int SrcLane = ShuffleMask[Anomaly];
4539 if (SrcLane >= NumInputElements) {
4541 SrcLane -= VT.getVectorNumElements();
4543 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4545 EVT ScalarVT = VT.getVectorElementType();
4546 if (ScalarVT.getSizeInBits() < 32)
4547 ScalarVT = MVT::i32;
4550 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4551 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4555 // If the shuffle is not directly supported and it has 4 elements, use
4556 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4557 unsigned NumElts = VT.getVectorNumElements();
4559 unsigned PFIndexes[4];
4560 for (unsigned i = 0; i != 4; ++i) {
4561 if (ShuffleMask[i] < 0)
4564 PFIndexes[i] = ShuffleMask[i];
4567 // Compute the index in the perfect shuffle table.
4568 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4569 PFIndexes[2] * 9 + PFIndexes[3];
4570 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4571 unsigned Cost = (PFEntry >> 30);
4574 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4577 return GenerateTBL(Op, ShuffleMask, DAG);
4580 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4582 EVT VT = BVN->getValueType(0);
4583 APInt SplatBits, SplatUndef;
4584 unsigned SplatBitSize;
4586 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4587 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4589 for (unsigned i = 0; i < NumSplats; ++i) {
4590 CnstBits <<= SplatBitSize;
4591 UndefBits <<= SplatBitSize;
4592 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4593 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4602 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4603 SelectionDAG &DAG) const {
4604 BuildVectorSDNode *BVN =
4605 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4606 SDValue LHS = Op.getOperand(0);
4608 EVT VT = Op.getValueType();
4613 APInt CnstBits(VT.getSizeInBits(), 0);
4614 APInt UndefBits(VT.getSizeInBits(), 0);
4615 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4616 // We only have BIC vector immediate instruction, which is and-not.
4617 CnstBits = ~CnstBits;
4619 // We make use of a little bit of goto ickiness in order to avoid having to
4620 // duplicate the immediate matching logic for the undef toggled case.
4621 bool SecondTry = false;
4624 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4625 CnstBits = CnstBits.zextOrTrunc(64);
4626 uint64_t CnstVal = CnstBits.getZExtValue();
4628 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4629 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4630 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4631 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4632 DAG.getConstant(CnstVal, MVT::i32),
4633 DAG.getConstant(0, MVT::i32));
4634 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4637 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4638 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4639 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4640 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4641 DAG.getConstant(CnstVal, MVT::i32),
4642 DAG.getConstant(8, MVT::i32));
4643 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4646 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4647 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4648 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4649 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4650 DAG.getConstant(CnstVal, MVT::i32),
4651 DAG.getConstant(16, MVT::i32));
4652 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4655 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4656 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4657 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4658 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4659 DAG.getConstant(CnstVal, MVT::i32),
4660 DAG.getConstant(24, MVT::i32));
4661 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4664 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4665 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4666 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4667 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4668 DAG.getConstant(CnstVal, MVT::i32),
4669 DAG.getConstant(0, MVT::i32));
4670 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4673 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4674 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4675 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4676 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4677 DAG.getConstant(CnstVal, MVT::i32),
4678 DAG.getConstant(8, MVT::i32));
4679 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4686 CnstBits = ~UndefBits;
4690 // We can always fall back to a non-immediate AND.
4695 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4696 // consists of only the same constant int value, returned in reference arg
4698 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4699 uint64_t &ConstVal) {
4700 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4703 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4706 EVT VT = Bvec->getValueType(0);
4707 unsigned NumElts = VT.getVectorNumElements();
4708 for (unsigned i = 1; i < NumElts; ++i)
4709 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4711 ConstVal = FirstElt->getZExtValue();
4715 static unsigned getIntrinsicID(const SDNode *N) {
4716 unsigned Opcode = N->getOpcode();
4719 return Intrinsic::not_intrinsic;
4720 case ISD::INTRINSIC_WO_CHAIN: {
4721 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4722 if (IID < Intrinsic::num_intrinsics)
4724 return Intrinsic::not_intrinsic;
4729 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4730 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4731 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4732 // Also, logical shift right -> sri, with the same structure.
4733 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4734 EVT VT = N->getValueType(0);
4741 // Is the first op an AND?
4742 const SDValue And = N->getOperand(0);
4743 if (And.getOpcode() != ISD::AND)
4746 // Is the second op an shl or lshr?
4747 SDValue Shift = N->getOperand(1);
4748 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4749 // or ARM64ISD::VLSHR vector, #shift
4750 unsigned ShiftOpc = Shift.getOpcode();
4751 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4753 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4755 // Is the shift amount constant?
4756 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4760 // Is the and mask vector all constant?
4762 if (!isAllConstantBuildVector(And.getOperand(1), C1))
4765 // Is C1 == ~C2, taking into account how much one can shift elements of a
4767 uint64_t C2 = C2node->getZExtValue();
4768 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4769 if (C2 > ElemSizeInBits)
4771 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4772 if ((C1 & ElemMask) != (~C2 & ElemMask))
4775 SDValue X = And.getOperand(0);
4776 SDValue Y = Shift.getOperand(0);
4779 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4781 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4782 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4784 DEBUG(dbgs() << "arm64-lower: transformed: \n");
4785 DEBUG(N->dump(&DAG));
4786 DEBUG(dbgs() << "into: \n");
4787 DEBUG(ResultSLI->dump(&DAG));
4793 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4794 SelectionDAG &DAG) const {
4795 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4796 if (EnableARM64SlrGeneration) {
4797 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4802 BuildVectorSDNode *BVN =
4803 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4804 SDValue LHS = Op.getOperand(1);
4806 EVT VT = Op.getValueType();
4808 // OR commutes, so try swapping the operands.
4810 LHS = Op.getOperand(0);
4811 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4816 APInt CnstBits(VT.getSizeInBits(), 0);
4817 APInt UndefBits(VT.getSizeInBits(), 0);
4818 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4819 // We make use of a little bit of goto ickiness in order to avoid having to
4820 // duplicate the immediate matching logic for the undef toggled case.
4821 bool SecondTry = false;
4824 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4825 CnstBits = CnstBits.zextOrTrunc(64);
4826 uint64_t CnstVal = CnstBits.getZExtValue();
4828 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4829 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4830 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4831 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4832 DAG.getConstant(CnstVal, MVT::i32),
4833 DAG.getConstant(0, MVT::i32));
4834 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4837 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4838 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4839 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4840 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4841 DAG.getConstant(CnstVal, MVT::i32),
4842 DAG.getConstant(8, MVT::i32));
4843 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4846 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4847 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4848 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4849 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4850 DAG.getConstant(CnstVal, MVT::i32),
4851 DAG.getConstant(16, MVT::i32));
4852 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4855 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4856 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4857 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4858 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4859 DAG.getConstant(CnstVal, MVT::i32),
4860 DAG.getConstant(24, MVT::i32));
4861 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4864 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4865 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4866 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4867 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4868 DAG.getConstant(CnstVal, MVT::i32),
4869 DAG.getConstant(0, MVT::i32));
4870 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4873 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4874 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4875 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4876 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4877 DAG.getConstant(CnstVal, MVT::i32),
4878 DAG.getConstant(8, MVT::i32));
4879 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4886 CnstBits = UndefBits;
4890 // We can always fall back to a non-immediate OR.
4895 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4896 SelectionDAG &DAG) const {
4897 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4899 EVT VT = Op.getValueType();
4901 APInt CnstBits(VT.getSizeInBits(), 0);
4902 APInt UndefBits(VT.getSizeInBits(), 0);
4903 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4904 // We make use of a little bit of goto ickiness in order to avoid having to
4905 // duplicate the immediate matching logic for the undef toggled case.
4906 bool SecondTry = false;
4909 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4910 CnstBits = CnstBits.zextOrTrunc(64);
4911 uint64_t CnstVal = CnstBits.getZExtValue();
4913 // Certain magic vector constants (used to express things like NOT
4914 // and NEG) are passed through unmodified. This allows codegen patterns
4915 // for these operations to match. Special-purpose patterns will lower
4916 // these immediates to MOVIs if it proves necessary.
4917 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4920 // The many faces of MOVI...
4921 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4922 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4923 if (VT.getSizeInBits() == 128) {
4924 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4925 DAG.getConstant(CnstVal, MVT::i32));
4926 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4929 // Support the V64 version via subregister insertion.
4930 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4931 DAG.getConstant(CnstVal, MVT::i32));
4932 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4935 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4936 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4937 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4938 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4939 DAG.getConstant(CnstVal, MVT::i32),
4940 DAG.getConstant(0, MVT::i32));
4941 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4944 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4945 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4946 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4947 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4948 DAG.getConstant(CnstVal, MVT::i32),
4949 DAG.getConstant(8, MVT::i32));
4950 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4953 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4954 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4955 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4956 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4957 DAG.getConstant(CnstVal, MVT::i32),
4958 DAG.getConstant(16, MVT::i32));
4959 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4962 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4963 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4964 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4965 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4966 DAG.getConstant(CnstVal, MVT::i32),
4967 DAG.getConstant(24, MVT::i32));
4968 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4971 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4972 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4973 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4974 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4975 DAG.getConstant(CnstVal, MVT::i32),
4976 DAG.getConstant(0, MVT::i32));
4977 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4980 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4981 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4982 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4983 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4984 DAG.getConstant(CnstVal, MVT::i32),
4985 DAG.getConstant(8, MVT::i32));
4986 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4989 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4990 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4991 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4992 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4993 DAG.getConstant(CnstVal, MVT::i32),
4994 DAG.getConstant(264, MVT::i32));
4995 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4998 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4999 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5000 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5001 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5002 DAG.getConstant(CnstVal, MVT::i32),
5003 DAG.getConstant(272, MVT::i32));
5004 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5007 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
5008 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
5009 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5010 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
5011 DAG.getConstant(CnstVal, MVT::i32));
5012 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5015 // The few faces of FMOV...
5016 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
5017 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
5018 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5019 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
5020 DAG.getConstant(CnstVal, MVT::i32));
5021 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5024 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
5025 VT.getSizeInBits() == 128) {
5026 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
5027 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
5028 DAG.getConstant(CnstVal, MVT::i32));
5029 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5032 // The many faces of MVNI...
5034 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5035 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5036 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5037 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5038 DAG.getConstant(CnstVal, MVT::i32),
5039 DAG.getConstant(0, MVT::i32));
5040 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5043 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5044 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5045 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5046 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5047 DAG.getConstant(CnstVal, MVT::i32),
5048 DAG.getConstant(8, MVT::i32));
5049 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5052 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5053 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5054 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5055 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5056 DAG.getConstant(CnstVal, MVT::i32),
5057 DAG.getConstant(16, MVT::i32));
5058 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5061 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5062 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5063 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5064 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5065 DAG.getConstant(CnstVal, MVT::i32),
5066 DAG.getConstant(24, MVT::i32));
5067 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5070 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5071 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5072 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5073 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5074 DAG.getConstant(CnstVal, MVT::i32),
5075 DAG.getConstant(0, MVT::i32));
5076 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5079 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5080 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5081 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5082 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5083 DAG.getConstant(CnstVal, MVT::i32),
5084 DAG.getConstant(8, MVT::i32));
5085 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5088 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5089 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5090 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5091 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5092 DAG.getConstant(CnstVal, MVT::i32),
5093 DAG.getConstant(264, MVT::i32));
5094 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5097 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5098 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5099 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5100 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5101 DAG.getConstant(CnstVal, MVT::i32),
5102 DAG.getConstant(272, MVT::i32));
5103 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5110 CnstBits = UndefBits;
5115 // Scan through the operands to find some interesting properties we can
5117 // 1) If only one value is used, we can use a DUP, or
5118 // 2) if only the low element is not undef, we can just insert that, or
5119 // 3) if only one constant value is used (w/ some non-constant lanes),
5120 // we can splat the constant value into the whole vector then fill
5121 // in the non-constant lanes.
5122 // 4) FIXME: If different constant values are used, but we can intelligently
5123 // select the values we'll be overwriting for the non-constant
5124 // lanes such that we can directly materialize the vector
5125 // some other way (MOVI, e.g.), we can be sneaky.
5126 unsigned NumElts = VT.getVectorNumElements();
5127 bool isOnlyLowElement = true;
5128 bool usesOnlyOneValue = true;
5129 bool usesOnlyOneConstantValue = true;
5130 bool isConstant = true;
5131 unsigned NumConstantLanes = 0;
5133 SDValue ConstantValue;
5134 for (unsigned i = 0; i < NumElts; ++i) {
5135 SDValue V = Op.getOperand(i);
5136 if (V.getOpcode() == ISD::UNDEF)
5139 isOnlyLowElement = false;
5140 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5143 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5145 if (!ConstantValue.getNode())
5147 else if (ConstantValue != V)
5148 usesOnlyOneConstantValue = false;
5151 if (!Value.getNode())
5153 else if (V != Value)
5154 usesOnlyOneValue = false;
5157 if (!Value.getNode())
5158 return DAG.getUNDEF(VT);
5160 if (isOnlyLowElement)
5161 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5163 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5164 // i32 and try again.
5165 if (usesOnlyOneValue) {
5167 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5168 Value.getValueType() != VT)
5169 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5171 // This is actually a DUPLANExx operation, which keeps everything vectory.
5173 // DUPLANE works on 128-bit vectors, widen it if necessary.
5174 SDValue Lane = Value.getOperand(1);
5175 Value = Value.getOperand(0);
5176 if (Value.getValueType().getSizeInBits() == 64)
5177 Value = WidenVector(Value, DAG);
5179 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5180 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5183 if (VT.getVectorElementType().isFloatingPoint()) {
5184 SmallVector<SDValue, 8> Ops;
5186 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5187 for (unsigned i = 0; i < NumElts; ++i)
5188 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5189 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5190 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5191 Val = LowerBUILD_VECTOR(Val, DAG);
5193 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5197 // If there was only one constant value used and for more than one lane,
5198 // start by splatting that value, then replace the non-constant lanes. This
5199 // is better than the default, which will perform a separate initialization
5201 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5202 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5203 // Now insert the non-constant lanes.
5204 for (unsigned i = 0; i < NumElts; ++i) {
5205 SDValue V = Op.getOperand(i);
5206 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5207 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5208 // Note that type legalization likely mucked about with the VT of the
5209 // source operand, so we may have to convert it here before inserting.
5210 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5216 // If all elements are constants and the case above didn't get hit, fall back
5217 // to the default expansion, which will generate a load from the constant
5222 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5224 SDValue shuffle = ReconstructShuffle(Op, DAG);
5225 if (shuffle != SDValue())
5229 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5230 // know the default expansion would otherwise fall back on something even
5231 // worse. For a vector with one or two non-undef values, that's
5232 // scalar_to_vector for the elements followed by a shuffle (provided the
5233 // shuffle is valid for the target) and materialization element by element
5234 // on the stack followed by a load for everything else.
5235 if (!isConstant && !usesOnlyOneValue) {
5236 SDValue Vec = DAG.getUNDEF(VT);
5237 SDValue Op0 = Op.getOperand(0);
5238 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5240 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5241 // a) Avoid a RMW dependency on the full vector register, and
5242 // b) Allow the register coalescer to fold away the copy if the
5243 // value is already in an S or D register.
5244 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5245 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5247 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5248 DAG.getTargetConstant(SubIdx, MVT::i32));
5249 Vec = SDValue(N, 0);
5252 for (; i < NumElts; ++i) {
5253 SDValue V = Op.getOperand(i);
5254 if (V.getOpcode() == ISD::UNDEF)
5256 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5257 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5262 // Just use the default expansion. We failed to find a better alternative.
5266 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5267 SelectionDAG &DAG) const {
5268 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5270 // Check for non-constant lane.
5271 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5274 EVT VT = Op.getOperand(0).getValueType();
5276 // Insertion/extraction are legal for V128 types.
5277 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5278 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5281 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5282 VT != MVT::v1i64 && VT != MVT::v2f32)
5285 // For V64 types, we perform insertion by expanding the value
5286 // to a V128 type and perform the insertion on that.
5288 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5289 EVT WideTy = WideVec.getValueType();
5291 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5292 Op.getOperand(1), Op.getOperand(2));
5293 // Re-narrow the resultant vector.
5294 return NarrowVector(Node, DAG);
5297 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5298 SelectionDAG &DAG) const {
5299 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5301 // Check for non-constant lane.
5302 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5305 EVT VT = Op.getOperand(0).getValueType();
5307 // Insertion/extraction are legal for V128 types.
5308 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5309 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5312 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5313 VT != MVT::v1i64 && VT != MVT::v2f32)
5316 // For V64 types, we perform extraction by expanding the value
5317 // to a V128 type and perform the extraction on that.
5319 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5320 EVT WideTy = WideVec.getValueType();
5322 EVT ExtrTy = WideTy.getVectorElementType();
5323 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5326 // For extractions, we just return the result directly.
5327 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5331 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5332 SelectionDAG &DAG) const {
5333 EVT VT = Op.getOperand(0).getValueType();
5339 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5342 unsigned Val = Cst->getZExtValue();
5344 unsigned Size = Op.getValueType().getSizeInBits();
5348 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5351 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5354 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5357 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5360 llvm_unreachable("Unexpected vector type in extract_subvector!");
5363 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5365 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5371 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5373 if (VT.getVectorNumElements() == 4 &&
5374 (VT.is128BitVector() || VT.is64BitVector())) {
5375 unsigned PFIndexes[4];
5376 for (unsigned i = 0; i != 4; ++i) {
5380 PFIndexes[i] = M[i];
5383 // Compute the index in the perfect shuffle table.
5384 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5385 PFIndexes[2] * 9 + PFIndexes[3];
5386 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5387 unsigned Cost = (PFEntry >> 30);
5395 unsigned DummyUnsigned;
5397 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5398 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5399 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5400 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5401 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5402 isZIPMask(M, VT, DummyUnsigned) ||
5403 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5404 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5405 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5406 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5407 isConcatMask(M, VT, VT.getSizeInBits() == 128));
5410 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5411 /// operand of a vector shift operation, where all the elements of the
5412 /// build_vector must have the same constant integer value.
5413 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5414 // Ignore bit_converts.
5415 while (Op.getOpcode() == ISD::BITCAST)
5416 Op = Op.getOperand(0);
5417 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5418 APInt SplatBits, SplatUndef;
5419 unsigned SplatBitSize;
5421 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5422 HasAnyUndefs, ElementBits) ||
5423 SplatBitSize > ElementBits)
5425 Cnt = SplatBits.getSExtValue();
5429 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5430 /// operand of a vector shift left operation. That value must be in the range:
5431 /// 0 <= Value < ElementBits for a left shift; or
5432 /// 0 <= Value <= ElementBits for a long left shift.
5433 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5434 assert(VT.isVector() && "vector shift count is not a vector type");
5435 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5436 if (!getVShiftImm(Op, ElementBits, Cnt))
5438 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5441 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5442 /// operand of a vector shift right operation. For a shift opcode, the value
5443 /// is positive, but for an intrinsic the value count must be negative. The
5444 /// absolute value must be in the range:
5445 /// 1 <= |Value| <= ElementBits for a right shift; or
5446 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5447 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5449 assert(VT.isVector() && "vector shift count is not a vector type");
5450 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5451 if (!getVShiftImm(Op, ElementBits, Cnt))
5455 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5458 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5459 SelectionDAG &DAG) const {
5460 EVT VT = Op.getValueType();
5464 if (!Op.getOperand(1).getValueType().isVector())
5466 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5468 switch (Op.getOpcode()) {
5470 llvm_unreachable("unexpected shift opcode");
5473 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5474 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5475 DAG.getConstant(Cnt, MVT::i32));
5476 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5477 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5478 Op.getOperand(0), Op.getOperand(1));
5481 // Right shift immediate
5482 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5485 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5486 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5487 DAG.getConstant(Cnt, MVT::i32));
5490 // Right shift register. Note, there is not a shift right register
5491 // instruction, but the shift left register instruction takes a signed
5492 // value, where negative numbers specify a right shift.
5493 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5494 : Intrinsic::arm64_neon_ushl;
5495 // negate the shift amount
5496 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5497 SDValue NegShiftLeft =
5498 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5499 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5500 return NegShiftLeft;
5506 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5507 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5508 SDLoc dl, SelectionDAG &DAG) {
5509 EVT SrcVT = LHS.getValueType();
5511 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5512 APInt CnstBits(VT.getSizeInBits(), 0);
5513 APInt UndefBits(VT.getSizeInBits(), 0);
5514 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5515 bool IsZero = IsCnst && (CnstBits == 0);
5517 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5524 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5526 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5527 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5531 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5532 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5535 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5536 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5539 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5540 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5543 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5544 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5548 // If we ignore NaNs then we can use to the MI implementation.
5552 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5553 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5563 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5565 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5566 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5570 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5571 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5574 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5575 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5578 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5579 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5582 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5583 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5585 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5587 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5590 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5591 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5593 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5595 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5599 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5600 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5601 SDValue LHS = Op.getOperand(0);
5602 SDValue RHS = Op.getOperand(1);
5605 if (LHS.getValueType().getVectorElementType().isInteger()) {
5606 assert(LHS.getValueType() == RHS.getValueType());
5607 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5608 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5612 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5613 LHS.getValueType().getVectorElementType() == MVT::f64);
5615 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5616 // clean. Some of them require two branches to implement.
5617 ARM64CC::CondCode CC1, CC2;
5619 changeVectorFPCCToARM64CC(CC, CC1, CC2, ShouldInvert);
5621 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5623 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5627 if (CC2 != ARM64CC::AL) {
5629 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5630 if (!Cmp2.getNode())
5633 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
5637 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
5642 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5643 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5644 /// specified in the intrinsic calls.
5645 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5647 unsigned Intrinsic) const {
5648 switch (Intrinsic) {
5649 case Intrinsic::arm64_neon_ld2:
5650 case Intrinsic::arm64_neon_ld3:
5651 case Intrinsic::arm64_neon_ld4:
5652 case Intrinsic::arm64_neon_ld2lane:
5653 case Intrinsic::arm64_neon_ld3lane:
5654 case Intrinsic::arm64_neon_ld4lane:
5655 case Intrinsic::arm64_neon_ld2r:
5656 case Intrinsic::arm64_neon_ld3r:
5657 case Intrinsic::arm64_neon_ld4r: {
5658 Info.opc = ISD::INTRINSIC_W_CHAIN;
5659 // Conservatively set memVT to the entire set of vectors loaded.
5660 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5661 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5662 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5665 Info.vol = false; // volatile loads with NEON intrinsics not supported
5666 Info.readMem = true;
5667 Info.writeMem = false;
5670 case Intrinsic::arm64_neon_st2:
5671 case Intrinsic::arm64_neon_st3:
5672 case Intrinsic::arm64_neon_st4:
5673 case Intrinsic::arm64_neon_st2lane:
5674 case Intrinsic::arm64_neon_st3lane:
5675 case Intrinsic::arm64_neon_st4lane: {
5676 Info.opc = ISD::INTRINSIC_VOID;
5677 // Conservatively set memVT to the entire set of vectors stored.
5678 unsigned NumElts = 0;
5679 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5680 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5681 if (!ArgTy->isVectorTy())
5683 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5685 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5686 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5689 Info.vol = false; // volatile stores with NEON intrinsics not supported
5690 Info.readMem = false;
5691 Info.writeMem = true;
5694 case Intrinsic::arm64_ldaxr:
5695 case Intrinsic::arm64_ldxr: {
5696 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5697 Info.opc = ISD::INTRINSIC_W_CHAIN;
5698 Info.memVT = MVT::getVT(PtrTy->getElementType());
5699 Info.ptrVal = I.getArgOperand(0);
5701 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5703 Info.readMem = true;
5704 Info.writeMem = false;
5707 case Intrinsic::arm64_stlxr:
5708 case Intrinsic::arm64_stxr: {
5709 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5710 Info.opc = ISD::INTRINSIC_W_CHAIN;
5711 Info.memVT = MVT::getVT(PtrTy->getElementType());
5712 Info.ptrVal = I.getArgOperand(1);
5714 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5716 Info.readMem = false;
5717 Info.writeMem = true;
5720 case Intrinsic::arm64_ldaxp:
5721 case Intrinsic::arm64_ldxp: {
5722 Info.opc = ISD::INTRINSIC_W_CHAIN;
5723 Info.memVT = MVT::i128;
5724 Info.ptrVal = I.getArgOperand(0);
5728 Info.readMem = true;
5729 Info.writeMem = false;
5732 case Intrinsic::arm64_stlxp:
5733 case Intrinsic::arm64_stxp: {
5734 Info.opc = ISD::INTRINSIC_W_CHAIN;
5735 Info.memVT = MVT::i128;
5736 Info.ptrVal = I.getArgOperand(2);
5740 Info.readMem = false;
5741 Info.writeMem = true;
5751 // Truncations from 64-bit GPR to 32-bit GPR is free.
5752 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5753 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5755 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5756 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5757 if (NumBits1 <= NumBits2)
5761 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5762 if (!VT1.isInteger() || !VT2.isInteger())
5764 unsigned NumBits1 = VT1.getSizeInBits();
5765 unsigned NumBits2 = VT2.getSizeInBits();
5766 if (NumBits1 <= NumBits2)
5771 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5773 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5774 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5776 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5777 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5778 if (NumBits1 == 32 && NumBits2 == 64)
5782 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5783 if (!VT1.isInteger() || !VT2.isInteger())
5785 unsigned NumBits1 = VT1.getSizeInBits();
5786 unsigned NumBits2 = VT2.getSizeInBits();
5787 if (NumBits1 == 32 && NumBits2 == 64)
5792 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5793 EVT VT1 = Val.getValueType();
5794 if (isZExtFree(VT1, VT2)) {
5798 if (Val.getOpcode() != ISD::LOAD)
5801 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5802 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5803 VT2.isInteger() && VT1.getSizeInBits() <= 32);
5806 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5807 unsigned &RequiredAligment) const {
5808 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5810 // Cyclone supports unaligned accesses.
5811 RequiredAligment = 0;
5812 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5813 return NumBits == 32 || NumBits == 64;
5816 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5817 unsigned &RequiredAligment) const {
5818 if (!LoadedType.isSimple() ||
5819 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5821 // Cyclone supports unaligned accesses.
5822 RequiredAligment = 0;
5823 unsigned NumBits = LoadedType.getSizeInBits();
5824 return NumBits == 32 || NumBits == 64;
5827 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5828 unsigned AlignCheck) {
5829 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5830 (DstAlign == 0 || DstAlign % AlignCheck == 0));
5833 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5834 unsigned SrcAlign, bool IsMemset,
5835 bool ZeroMemset, bool MemcpyStrSrc,
5836 MachineFunction &MF) const {
5837 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5838 // instruction to materialize the v2i64 zero and one store (with restrictive
5839 // addressing mode). Just do two i64 store of zero-registers.
5841 const Function *F = MF.getFunction();
5842 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
5843 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5844 Attribute::NoImplicitFloat) &&
5845 (memOpAlign(SrcAlign, DstAlign, 16) ||
5846 (allowsUnalignedMemoryAccesses(MVT::f128, 0, &Fast) && Fast)))
5849 return Size >= 8 ? MVT::i64 : MVT::i32;
5852 // 12-bit optionally shifted immediates are legal for adds.
5853 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5854 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5859 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5860 // immediates is the same as for an add or a sub.
5861 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5864 return isLegalAddImmediate(Immed);
5867 /// isLegalAddressingMode - Return true if the addressing mode represented
5868 /// by AM is legal for this target, for a load/store of the specified type.
5869 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5871 // ARM64 has five basic addressing modes:
5873 // reg + 9-bit signed offset
5874 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
5876 // reg + SIZE_IN_BYTES * reg
5878 // No global is ever allowed as a base.
5882 // No reg+reg+imm addressing.
5883 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5886 // check reg + imm case:
5887 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5888 uint64_t NumBytes = 0;
5889 if (Ty->isSized()) {
5890 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5891 NumBytes = NumBits / 8;
5892 if (!isPowerOf2_64(NumBits))
5897 int64_t Offset = AM.BaseOffs;
5899 // 9-bit signed offset
5900 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5903 // 12-bit unsigned offset
5904 unsigned shift = Log2_64(NumBytes);
5905 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5906 // Must be a multiple of NumBytes (NumBytes is a power of 2)
5907 (Offset >> shift) << shift == Offset)
5912 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5914 if (!AM.Scale || AM.Scale == 1 ||
5915 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5920 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5922 // Scaling factors are not free at all.
5923 // Operands | Rt Latency
5924 // -------------------------------------------
5926 // -------------------------------------------
5927 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
5928 // Rt, [Xn, Wm, <extend> #imm] |
5929 if (isLegalAddressingMode(AM, Ty))
5930 // Scale represents reg2 * scale, thus account for 1 if
5931 // it is not equal to 0 or 1.
5932 return AM.Scale != 0 && AM.Scale != 1;
5936 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
5937 VT = VT.getScalarType();
5942 switch (VT.getSimpleVT().SimpleTy) {
5954 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
5955 // LR is a callee-save register, but we must treat it as clobbered by any call
5956 // site. Hence we include LR in the scratch registers, which are in turn added
5957 // as implicit-defs for stackmaps and patchpoints.
5958 static const MCPhysReg ScratchRegs[] = {
5959 ARM64::X16, ARM64::X17, ARM64::LR, 0
5964 bool ARM64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
5965 EVT VT = N->getValueType(0);
5966 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
5967 // it with shift to let it be lowered to UBFX.
5968 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
5969 isa<ConstantSDNode>(N->getOperand(1))) {
5970 uint64_t TruncMask = N->getConstantOperandVal(1);
5971 if (isMask_64(TruncMask) &&
5972 N->getOperand(0).getOpcode() == ISD::SRL &&
5973 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
5979 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5981 assert(Ty->isIntegerTy());
5983 unsigned BitSize = Ty->getPrimitiveSizeInBits();
5987 int64_t Val = Imm.getSExtValue();
5988 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
5991 if ((int64_t)Val < 0)
5994 Val &= (1LL << 32) - 1;
5996 unsigned LZ = countLeadingZeros((uint64_t)Val);
5997 unsigned Shift = (63 - LZ) / 16;
5998 // MOVZ is free so return true for one or fewer MOVK.
5999 return (Shift < 3) ? true : false;
6002 // Generate SUBS and CSEL for integer abs.
6003 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6004 EVT VT = N->getValueType(0);
6006 SDValue N0 = N->getOperand(0);
6007 SDValue N1 = N->getOperand(1);
6010 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6011 // and change it to SUB and CSEL.
6012 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6013 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6014 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6015 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6016 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6017 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6019 // Generate SUBS & CSEL.
6021 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6022 N0.getOperand(0), DAG.getConstant(0, VT));
6023 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6024 DAG.getConstant(ARM64CC::PL, MVT::i32),
6025 SDValue(Cmp.getNode(), 1));
6030 // performXorCombine - Attempts to handle integer ABS.
6031 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6032 TargetLowering::DAGCombinerInfo &DCI,
6033 const ARM64Subtarget *Subtarget) {
6034 if (DCI.isBeforeLegalizeOps())
6037 return performIntegerAbsCombine(N, DAG);
6040 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6041 TargetLowering::DAGCombinerInfo &DCI,
6042 const ARM64Subtarget *Subtarget) {
6043 if (DCI.isBeforeLegalizeOps())
6046 // Multiplication of a power of two plus/minus one can be done more
6047 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6048 // future CPUs have a cheaper MADD instruction, this may need to be
6049 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6050 // 64-bit is 5 cycles, so this is always a win.
6051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6052 APInt Value = C->getAPIntValue();
6053 EVT VT = N->getValueType(0);
6054 APInt VP1 = Value + 1;
6055 if (VP1.isPowerOf2()) {
6056 // Multiplying by one less than a power of two, replace with a shift
6058 SDValue ShiftedVal =
6059 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6060 DAG.getConstant(VP1.logBase2(), MVT::i64));
6061 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6063 APInt VM1 = Value - 1;
6064 if (VM1.isPowerOf2()) {
6065 // Multiplying by one more than a power of two, replace with a shift
6067 SDValue ShiftedVal =
6068 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6069 DAG.getConstant(VM1.logBase2(), MVT::i64));
6070 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6076 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6077 EVT VT = N->getValueType(0);
6078 if (VT != MVT::f32 && VT != MVT::f64)
6080 // Only optimize when the source and destination types have the same width.
6081 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6084 // If the result of an integer load is only used by an integer-to-float
6085 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6086 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6087 SDValue N0 = N->getOperand(0);
6088 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6089 // Do not change the width of a volatile load.
6090 !cast<LoadSDNode>(N0)->isVolatile()) {
6091 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6092 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6093 LN0->getPointerInfo(), LN0->isVolatile(),
6094 LN0->isNonTemporal(), LN0->isInvariant(),
6095 LN0->getAlignment());
6097 // Make sure successors of the original load stay after it by updating them
6098 // to use the new Chain.
6099 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6102 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6103 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6109 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6110 /// searches for and classifies those shifts.
6111 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6113 if (N.getOpcode() == ISD::SHL)
6115 else if (N.getOpcode() == ISD::SRL)
6120 if (!isa<ConstantSDNode>(N.getOperand(1)))
6123 ShiftAmount = N->getConstantOperandVal(1);
6124 Src = N->getOperand(0);
6128 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6129 /// registers viewed as a high/low pair. This function looks for the pattern:
6130 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6131 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6133 static SDValue tryCombineToEXTR(SDNode *N,
6134 TargetLowering::DAGCombinerInfo &DCI) {
6135 SelectionDAG &DAG = DCI.DAG;
6137 EVT VT = N->getValueType(0);
6139 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6141 if (VT != MVT::i32 && VT != MVT::i64)
6145 uint32_t ShiftLHS = 0;
6147 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6151 uint32_t ShiftRHS = 0;
6153 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6156 // If they're both trying to come from the high part of the register, they're
6157 // not really an EXTR.
6158 if (LHSFromHi == RHSFromHi)
6161 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6165 std::swap(LHS, RHS);
6166 std::swap(ShiftLHS, ShiftRHS);
6169 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6170 DAG.getConstant(ShiftRHS, MVT::i64));
6173 static SDValue tryCombineToBSL(SDNode *N,
6174 TargetLowering::DAGCombinerInfo &DCI) {
6175 EVT VT = N->getValueType(0);
6176 SelectionDAG &DAG = DCI.DAG;
6182 SDValue N0 = N->getOperand(0);
6183 if (N0.getOpcode() != ISD::AND)
6186 SDValue N1 = N->getOperand(1);
6187 if (N1.getOpcode() != ISD::AND)
6190 // We only have to look for constant vectors here since the general, variable
6191 // case can be handled in TableGen.
6192 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6193 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6194 for (int i = 1; i >= 0; --i)
6195 for (int j = 1; j >= 0; --j) {
6196 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6197 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6201 bool FoundMatch = true;
6202 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6203 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6204 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6206 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6213 return DAG.getNode(ARM64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6214 N0->getOperand(1 - i), N1->getOperand(1 - j));
6220 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6221 const ARM64Subtarget *Subtarget) {
6222 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6223 if (!EnableARM64ExtrGeneration)
6225 SelectionDAG &DAG = DCI.DAG;
6226 EVT VT = N->getValueType(0);
6228 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6231 SDValue Res = tryCombineToEXTR(N, DCI);
6235 Res = tryCombineToBSL(N, DCI);
6242 static SDValue performBitcastCombine(SDNode *N,
6243 TargetLowering::DAGCombinerInfo &DCI,
6244 SelectionDAG &DAG) {
6245 // Wait 'til after everything is legalized to try this. That way we have
6246 // legal vector types and such.
6247 if (DCI.isBeforeLegalizeOps())
6250 // Remove extraneous bitcasts around an extract_subvector.
6252 // (v4i16 (bitconvert
6253 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6255 // (extract_subvector ((v8i16 ...), (i64 4)))
6257 // Only interested in 64-bit vectors as the ultimate result.
6258 EVT VT = N->getValueType(0);
6261 if (VT.getSimpleVT().getSizeInBits() != 64)
6263 // Is the operand an extract_subvector starting at the beginning or halfway
6264 // point of the vector? A low half may also come through as an
6265 // EXTRACT_SUBREG, so look for that, too.
6266 SDValue Op0 = N->getOperand(0);
6267 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6268 !(Op0->isMachineOpcode() &&
6269 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6271 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6272 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6273 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6275 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6276 if (idx != ARM64::dsub)
6278 // The dsub reference is equivalent to a lane zero subvector reference.
6281 // Look through the bitcast of the input to the extract.
6282 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6284 SDValue Source = Op0->getOperand(0)->getOperand(0);
6285 // If the source type has twice the number of elements as our destination
6286 // type, we know this is an extract of the high or low half of the vector.
6287 EVT SVT = Source->getValueType(0);
6288 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6291 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6293 // Create the simplified form to just extract the low or high half of the
6294 // vector directly rather than bothering with the bitcasts.
6296 unsigned NumElements = VT.getVectorNumElements();
6298 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6299 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6301 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6302 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6308 static SDValue performConcatVectorsCombine(SDNode *N,
6309 TargetLowering::DAGCombinerInfo &DCI,
6310 SelectionDAG &DAG) {
6311 // Wait 'til after everything is legalized to try this. That way we have
6312 // legal vector types and such.
6313 if (DCI.isBeforeLegalizeOps())
6317 EVT VT = N->getValueType(0);
6319 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6320 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6321 // canonicalise to that.
6322 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6323 assert(VT.getVectorElementType().getSizeInBits() == 64);
6324 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6325 WidenVector(N->getOperand(0), DAG),
6326 DAG.getConstant(0, MVT::i64));
6329 // Canonicalise concat_vectors so that the right-hand vector has as few
6330 // bit-casts as possible before its real operation. The primary matching
6331 // destination for these operations will be the narrowing "2" instructions,
6332 // which depend on the operation being performed on this right-hand vector.
6334 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6336 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6338 SDValue Op1 = N->getOperand(1);
6339 if (Op1->getOpcode() != ISD::BITCAST)
6341 SDValue RHS = Op1->getOperand(0);
6342 MVT RHSTy = RHS.getValueType().getSimpleVT();
6343 // If the RHS is not a vector, this is not the pattern we're looking for.
6344 if (!RHSTy.isVector())
6347 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6349 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6350 RHSTy.getVectorNumElements() * 2);
6352 ISD::BITCAST, dl, VT,
6353 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6354 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6357 static SDValue tryCombineFixedPointConvert(SDNode *N,
6358 TargetLowering::DAGCombinerInfo &DCI,
6359 SelectionDAG &DAG) {
6360 // Wait 'til after everything is legalized to try this. That way we have
6361 // legal vector types and such.
6362 if (DCI.isBeforeLegalizeOps())
6364 // Transform a scalar conversion of a value from a lane extract into a
6365 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6366 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6367 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6369 // The second form interacts better with instruction selection and the
6370 // register allocator to avoid cross-class register copies that aren't
6371 // coalescable due to a lane reference.
6373 // Check the operand and see if it originates from a lane extract.
6374 SDValue Op1 = N->getOperand(1);
6375 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6376 // Yep, no additional predication needed. Perform the transform.
6377 SDValue IID = N->getOperand(0);
6378 SDValue Shift = N->getOperand(2);
6379 SDValue Vec = Op1.getOperand(0);
6380 SDValue Lane = Op1.getOperand(1);
6381 EVT ResTy = N->getValueType(0);
6385 // The vector width should be 128 bits by the time we get here, even
6386 // if it started as 64 bits (the extract_vector handling will have
6388 assert(Vec.getValueType().getSizeInBits() == 128 &&
6389 "unexpected vector size on extract_vector_elt!");
6390 if (Vec.getValueType() == MVT::v4i32)
6391 VecResTy = MVT::v4f32;
6392 else if (Vec.getValueType() == MVT::v2i64)
6393 VecResTy = MVT::v2f64;
6395 assert(0 && "unexpected vector type!");
6398 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6399 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6404 // AArch64 high-vector "long" operations are formed by performing the non-high
6405 // version on an extract_subvector of each operand which gets the high half:
6407 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6409 // However, there are cases which don't have an extract_high explicitly, but
6410 // have another operation that can be made compatible with one for free. For
6413 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6415 // This routine does the actual conversion of such DUPs, once outer routines
6416 // have determined that everything else is in order.
6417 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6418 // We can handle most types of duplicate, but the lane ones have an extra
6419 // operand saying *which* lane, so we need to know.
6421 switch (N.getOpcode()) {
6425 case ARM64ISD::DUPLANE8:
6426 case ARM64ISD::DUPLANE16:
6427 case ARM64ISD::DUPLANE32:
6428 case ARM64ISD::DUPLANE64:
6435 MVT NarrowTy = N.getSimpleValueType();
6436 if (!NarrowTy.is64BitVector())
6439 MVT ElementTy = NarrowTy.getVectorElementType();
6440 unsigned NumElems = NarrowTy.getVectorNumElements();
6441 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6445 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6448 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6450 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6451 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6454 static bool isEssentiallyExtractSubvector(SDValue N) {
6455 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6458 return N.getOpcode() == ISD::BITCAST &&
6459 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6462 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6463 struct GenericSetCCInfo {
6464 const SDValue *Opnd0;
6465 const SDValue *Opnd1;
6469 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6470 struct ARM64SetCCInfo {
6472 ARM64CC::CondCode CC;
6475 /// \brief Helper structure to keep track of SetCC information.
6477 GenericSetCCInfo Generic;
6478 ARM64SetCCInfo ARM64;
6481 /// \brief Helper structure to be able to read SetCC information.
6482 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6483 /// a GenericSetCCInfo.
6484 struct SetCCInfoAndKind {
6489 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6491 /// ARM64 lowered one.
6492 /// \p SetCCInfo is filled accordingly.
6493 /// \post SetCCInfo is meanginfull only when this function returns true.
6494 /// \return True when Op is a kind of SET_CC operation.
6495 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6496 // If this is a setcc, this is straight forward.
6497 if (Op.getOpcode() == ISD::SETCC) {
6498 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6499 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6500 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6501 SetCCInfo.IsARM64 = false;
6504 // Otherwise, check if this is a matching csel instruction.
6508 if (Op.getOpcode() != ARM64ISD::CSEL)
6510 // Set the information about the operands.
6511 // TODO: we want the operands of the Cmp not the csel
6512 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6513 SetCCInfo.IsARM64 = true;
6514 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6515 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6517 // Check that the operands matches the constraints:
6518 // (1) Both operands must be constants.
6519 // (2) One must be 1 and the other must be 0.
6520 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6521 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6524 if (!TValue || !FValue)
6528 if (!TValue->isOne()) {
6529 // Update the comparison when we are interested in !cc.
6530 std::swap(TValue, FValue);
6531 SetCCInfo.Info.ARM64.CC =
6532 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6534 return TValue->isOne() && FValue->isNullValue();
6537 // The folding we want to perform is:
6538 // (add x, (setcc cc ...) )
6540 // (csel x, (add x, 1), !cc ...)
6542 // The latter will get matched to a CSINC instruction.
6543 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6544 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6545 SDValue LHS = Op->getOperand(0);
6546 SDValue RHS = Op->getOperand(1);
6547 SetCCInfoAndKind InfoAndKind;
6549 // If neither operand is a SET_CC, give up.
6550 if (!isSetCC(LHS, InfoAndKind)) {
6551 std::swap(LHS, RHS);
6552 if (!isSetCC(LHS, InfoAndKind))
6556 // FIXME: This could be generatized to work for FP comparisons.
6557 EVT CmpVT = InfoAndKind.IsARM64
6558 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6559 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6560 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6566 if (InfoAndKind.IsARM64) {
6567 CCVal = DAG.getConstant(
6568 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6569 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6571 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6572 *InfoAndKind.Info.Generic.Opnd1,
6573 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6576 EVT VT = Op->getValueType(0);
6577 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6578 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6581 // The basic add/sub long vector instructions have variants with "2" on the end
6582 // which act on the high-half of their inputs. They are normally matched by
6585 // (add (zeroext (extract_high LHS)),
6586 // (zeroext (extract_high RHS)))
6587 // -> uaddl2 vD, vN, vM
6589 // However, if one of the extracts is something like a duplicate, this
6590 // instruction can still be used profitably. This function puts the DAG into a
6591 // more appropriate form for those patterns to trigger.
6592 static SDValue performAddSubLongCombine(SDNode *N,
6593 TargetLowering::DAGCombinerInfo &DCI,
6594 SelectionDAG &DAG) {
6595 if (DCI.isBeforeLegalizeOps())
6598 MVT VT = N->getSimpleValueType(0);
6599 if (!VT.is128BitVector()) {
6600 if (N->getOpcode() == ISD::ADD)
6601 return performSetccAddFolding(N, DAG);
6605 // Make sure both branches are extended in the same way.
6606 SDValue LHS = N->getOperand(0);
6607 SDValue RHS = N->getOperand(1);
6608 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6609 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6610 LHS.getOpcode() != RHS.getOpcode())
6613 unsigned ExtType = LHS.getOpcode();
6615 // It's not worth doing if at least one of the inputs isn't already an
6616 // extract, but we don't know which it'll be so we have to try both.
6617 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6618 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6622 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6623 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6624 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6628 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6631 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6634 // Massage DAGs which we can use the high-half "long" operations on into
6635 // something isel will recognize better. E.g.
6637 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6638 // (arm64_neon_umull (extract_high (v2i64 vec)))
6639 // (extract_high (v2i64 (dup128 scalar)))))
6641 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6642 TargetLowering::DAGCombinerInfo &DCI,
6643 SelectionDAG &DAG) {
6644 if (DCI.isBeforeLegalizeOps())
6647 SDValue LHS = N->getOperand(1);
6648 SDValue RHS = N->getOperand(2);
6649 assert(LHS.getValueType().is64BitVector() &&
6650 RHS.getValueType().is64BitVector() &&
6651 "unexpected shape for long operation");
6653 // Either node could be a DUP, but it's not worth doing both of them (you'd
6654 // just as well use the non-high version) so look for a corresponding extract
6655 // operation on the other "wing".
6656 if (isEssentiallyExtractSubvector(LHS)) {
6657 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6660 } else if (isEssentiallyExtractSubvector(RHS)) {
6661 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6666 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6667 N->getOperand(0), LHS, RHS);
6670 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6671 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6672 unsigned ElemBits = ElemTy.getSizeInBits();
6674 int64_t ShiftAmount;
6675 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6676 APInt SplatValue, SplatUndef;
6677 unsigned SplatBitSize;
6679 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6680 HasAnyUndefs, ElemBits) ||
6681 SplatBitSize != ElemBits)
6684 ShiftAmount = SplatValue.getSExtValue();
6685 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6686 ShiftAmount = CVN->getSExtValue();
6694 llvm_unreachable("Unknown shift intrinsic");
6695 case Intrinsic::arm64_neon_sqshl:
6696 Opcode = ARM64ISD::SQSHL_I;
6697 IsRightShift = false;
6699 case Intrinsic::arm64_neon_uqshl:
6700 Opcode = ARM64ISD::UQSHL_I;
6701 IsRightShift = false;
6703 case Intrinsic::arm64_neon_srshl:
6704 Opcode = ARM64ISD::SRSHR_I;
6705 IsRightShift = true;
6707 case Intrinsic::arm64_neon_urshl:
6708 Opcode = ARM64ISD::URSHR_I;
6709 IsRightShift = true;
6711 case Intrinsic::arm64_neon_sqshlu:
6712 Opcode = ARM64ISD::SQSHLU_I;
6713 IsRightShift = false;
6717 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6718 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6719 DAG.getConstant(-ShiftAmount, MVT::i32));
6720 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6721 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6722 DAG.getConstant(ShiftAmount, MVT::i32));
6727 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6728 // the intrinsics must be legal and take an i32, this means there's almost
6729 // certainly going to be a zext in the DAG which we can eliminate.
6730 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6731 SDValue AndN = N->getOperand(2);
6732 if (AndN.getOpcode() != ISD::AND)
6735 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6736 if (!CMask || CMask->getZExtValue() != Mask)
6739 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6740 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6743 static SDValue performIntrinsicCombine(SDNode *N,
6744 TargetLowering::DAGCombinerInfo &DCI,
6745 const ARM64Subtarget *Subtarget) {
6746 SelectionDAG &DAG = DCI.DAG;
6747 unsigned IID = getIntrinsicID(N);
6751 case Intrinsic::arm64_neon_vcvtfxs2fp:
6752 case Intrinsic::arm64_neon_vcvtfxu2fp:
6753 return tryCombineFixedPointConvert(N, DCI, DAG);
6755 case Intrinsic::arm64_neon_fmax:
6756 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6757 N->getOperand(1), N->getOperand(2));
6758 case Intrinsic::arm64_neon_fmin:
6759 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6760 N->getOperand(1), N->getOperand(2));
6761 case Intrinsic::arm64_neon_smull:
6762 case Intrinsic::arm64_neon_umull:
6763 case Intrinsic::arm64_neon_pmull:
6764 case Intrinsic::arm64_neon_sqdmull:
6765 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6766 case Intrinsic::arm64_neon_sqshl:
6767 case Intrinsic::arm64_neon_uqshl:
6768 case Intrinsic::arm64_neon_sqshlu:
6769 case Intrinsic::arm64_neon_srshl:
6770 case Intrinsic::arm64_neon_urshl:
6771 return tryCombineShiftImm(IID, N, DAG);
6772 case Intrinsic::arm64_crc32b:
6773 case Intrinsic::arm64_crc32cb:
6774 return tryCombineCRC32(0xff, N, DAG);
6775 case Intrinsic::arm64_crc32h:
6776 case Intrinsic::arm64_crc32ch:
6777 return tryCombineCRC32(0xffff, N, DAG);
6782 static SDValue performExtendCombine(SDNode *N,
6783 TargetLowering::DAGCombinerInfo &DCI,
6784 SelectionDAG &DAG) {
6785 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6786 // we can convert that DUP into another extract_high (of a bigger DUP), which
6787 // helps the backend to decide that an sabdl2 would be useful, saving a real
6788 // extract_high operation.
6789 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6790 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6791 SDNode *ABDNode = N->getOperand(0).getNode();
6792 unsigned IID = getIntrinsicID(ABDNode);
6793 if (IID == Intrinsic::arm64_neon_sabd ||
6794 IID == Intrinsic::arm64_neon_uabd) {
6795 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6796 if (!NewABD.getNode())
6799 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6804 // This is effectively a custom type legalization for ARM64.
6806 // Type legalization will split an extend of a small, legal, type to a larger
6807 // illegal type by first splitting the destination type, often creating
6808 // illegal source types, which then get legalized in isel-confusing ways,
6809 // leading to really terrible codegen. E.g.,
6810 // %result = v8i32 sext v8i8 %value
6812 // %losrc = extract_subreg %value, ...
6813 // %hisrc = extract_subreg %value, ...
6814 // %lo = v4i32 sext v4i8 %losrc
6815 // %hi = v4i32 sext v4i8 %hisrc
6816 // Things go rapidly downhill from there.
6818 // For ARM64, the [sz]ext vector instructions can only go up one element
6819 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6820 // take two instructions.
6822 // This implies that the most efficient way to do the extend from v8i8
6823 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6824 // the normal splitting to happen for the v8i16->v8i32.
6826 // This is pre-legalization to catch some cases where the default
6827 // type legalization will create ill-tempered code.
6828 if (!DCI.isBeforeLegalizeOps())
6831 // We're only interested in cleaning things up for non-legal vector types
6832 // here. If both the source and destination are legal, things will just
6833 // work naturally without any fiddling.
6834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6835 EVT ResVT = N->getValueType(0);
6836 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6838 // If the vector type isn't a simple VT, it's beyond the scope of what
6839 // we're worried about here. Let legalization do its thing and hope for
6841 if (!ResVT.isSimple())
6844 SDValue Src = N->getOperand(0);
6845 MVT SrcVT = Src->getValueType(0).getSimpleVT();
6846 // If the source VT is a 64-bit vector, we can play games and get the
6847 // better results we want.
6848 if (SrcVT.getSizeInBits() != 64)
6851 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6852 unsigned ElementCount = SrcVT.getVectorNumElements();
6853 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6855 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6857 // Now split the rest of the operation into two halves, each with a 64
6861 unsigned NumElements = ResVT.getVectorNumElements();
6862 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6863 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6864 ResVT.getVectorElementType(), NumElements / 2);
6866 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6867 LoVT.getVectorNumElements());
6868 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6869 DAG.getIntPtrConstant(0));
6870 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6871 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6872 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6873 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6875 // Now combine the parts back together so we still have a single result
6876 // like the combiner expects.
6877 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6880 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6881 /// value. The load store optimizer pass will merge them to store pair stores.
6882 /// This has better performance than a splat of the scalar followed by a split
6883 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6884 /// followed by an ext.b and two stores.
6885 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6886 SDValue StVal = St->getValue();
6887 EVT VT = StVal.getValueType();
6889 // Don't replace floating point stores, they possibly won't be transformed to
6890 // stp because of the store pair suppress pass.
6891 if (VT.isFloatingPoint())
6894 // Check for insert vector elements.
6895 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6898 // We can express a splat as store pair(s) for 2 or 4 elements.
6899 unsigned NumVecElts = VT.getVectorNumElements();
6900 if (NumVecElts != 4 && NumVecElts != 2)
6902 SDValue SplatVal = StVal.getOperand(1);
6903 unsigned RemainInsertElts = NumVecElts - 1;
6905 // Check that this is a splat.
6906 while (--RemainInsertElts) {
6907 SDValue NextInsertElt = StVal.getOperand(0);
6908 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6910 if (NextInsertElt.getOperand(1) != SplatVal)
6912 StVal = NextInsertElt;
6914 unsigned OrigAlignment = St->getAlignment();
6915 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6916 unsigned Alignment = std::min(OrigAlignment, EltOffset);
6918 // Create scalar stores. This is at least as good as the code sequence for a
6919 // split unaligned store wich is a dup.s, ext.b, and two stores.
6920 // Most of the time the three stores should be replaced by store pair
6921 // instructions (stp).
6923 SDValue BasePtr = St->getBasePtr();
6925 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6926 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6928 unsigned Offset = EltOffset;
6929 while (--NumVecElts) {
6930 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6931 DAG.getConstant(Offset, MVT::i64));
6932 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6933 St->getPointerInfo(), St->isVolatile(),
6934 St->isNonTemporal(), Alignment);
6935 Offset += EltOffset;
6940 static SDValue performSTORECombine(SDNode *N,
6941 TargetLowering::DAGCombinerInfo &DCI,
6943 const ARM64Subtarget *Subtarget) {
6944 if (!DCI.isBeforeLegalize())
6947 StoreSDNode *S = cast<StoreSDNode>(N);
6948 if (S->isVolatile())
6951 // Cyclone has bad performance on unaligned 16B stores when crossing line and
6952 // page boundries. We want to split such stores.
6953 if (!Subtarget->isCyclone())
6956 // Don't split at Oz.
6957 MachineFunction &MF = DAG.getMachineFunction();
6958 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
6959 AttributeSet::FunctionIndex, Attribute::MinSize);
6963 SDValue StVal = S->getValue();
6964 EVT VT = StVal.getValueType();
6966 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
6967 // those up regresses performance on micro-benchmarks and olden/bh.
6968 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
6971 // Split unaligned 16B stores. They are terrible for performance.
6972 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
6973 // extensions can use this to mark that it does not want splitting to happen
6974 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
6975 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
6976 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
6977 S->getAlignment() <= 2)
6980 // If we get a splat of a scalar convert this vector store to a store of
6981 // scalars. They will be merged into store pairs thereby removing two
6983 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
6984 if (ReplacedSplat != SDValue())
6985 return ReplacedSplat;
6988 unsigned NumElts = VT.getVectorNumElements() / 2;
6989 // Split VT into two.
6991 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
6992 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6993 DAG.getIntPtrConstant(0));
6994 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6995 DAG.getIntPtrConstant(NumElts));
6996 SDValue BasePtr = S->getBasePtr();
6998 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
6999 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7000 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7001 DAG.getConstant(8, MVT::i64));
7002 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7003 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7007 // Optimize compare with zero and branch.
7008 static SDValue performBRCONDCombine(SDNode *N,
7009 TargetLowering::DAGCombinerInfo &DCI,
7010 SelectionDAG &DAG) {
7011 SDValue Chain = N->getOperand(0);
7012 SDValue Dest = N->getOperand(1);
7013 SDValue CCVal = N->getOperand(2);
7014 SDValue Cmp = N->getOperand(3);
7016 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7017 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7018 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
7021 unsigned CmpOpc = Cmp.getOpcode();
7022 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
7025 // Only attempt folding if there is only one use of the flag and no use of the
7027 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7030 SDValue LHS = Cmp.getOperand(0);
7031 SDValue RHS = Cmp.getOperand(1);
7033 assert(LHS.getValueType() == RHS.getValueType() &&
7034 "Expected the value type to be the same for both operands!");
7035 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7038 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7039 std::swap(LHS, RHS);
7041 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7044 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7045 LHS.getOpcode() == ISD::SRL)
7048 // Fold the compare into the branch instruction.
7050 if (CC == ARM64CC::EQ)
7051 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7053 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7055 // Do not add new nodes to DAG combiner worklist.
7056 DCI.CombineTo(N, BR, false);
7061 // vselect (v1i1 setcc) ->
7062 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
7063 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7064 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7066 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7067 SDValue N0 = N->getOperand(0);
7068 EVT CCVT = N0.getValueType();
7070 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7071 CCVT.getVectorElementType() != MVT::i1)
7074 EVT ResVT = N->getValueType(0);
7075 EVT CmpVT = N0.getOperand(0).getValueType();
7076 // Only combine when the result type is of the same size as the compared
7078 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7081 SDValue IfTrue = N->getOperand(1);
7082 SDValue IfFalse = N->getOperand(2);
7084 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7085 N0.getOperand(0), N0.getOperand(1),
7086 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7087 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7091 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7092 DAGCombinerInfo &DCI) const {
7093 SelectionDAG &DAG = DCI.DAG;
7094 switch (N->getOpcode()) {
7099 return performAddSubLongCombine(N, DCI, DAG);
7101 return performXorCombine(N, DAG, DCI, Subtarget);
7103 return performMulCombine(N, DAG, DCI, Subtarget);
7104 case ISD::SINT_TO_FP:
7105 case ISD::UINT_TO_FP:
7106 return performIntToFpCombine(N, DAG);
7108 return performORCombine(N, DCI, Subtarget);
7109 case ISD::INTRINSIC_WO_CHAIN:
7110 return performIntrinsicCombine(N, DCI, Subtarget);
7111 case ISD::ANY_EXTEND:
7112 case ISD::ZERO_EXTEND:
7113 case ISD::SIGN_EXTEND:
7114 return performExtendCombine(N, DCI, DAG);
7116 return performBitcastCombine(N, DCI, DAG);
7117 case ISD::CONCAT_VECTORS:
7118 return performConcatVectorsCombine(N, DCI, DAG);
7120 return performVSelectCombine(N, DCI.DAG);
7122 return performSTORECombine(N, DCI, DAG, Subtarget);
7123 case ARM64ISD::BRCOND:
7124 return performBRCONDCombine(N, DCI, DAG);
7129 // Check if the return value is used as only a return value, as otherwise
7130 // we can't perform a tail-call. In particular, we need to check for
7131 // target ISD nodes that are returns and any other "odd" constructs
7132 // that the generic analysis code won't necessarily catch.
7133 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7134 if (N->getNumValues() != 1)
7136 if (!N->hasNUsesOfValue(1, 0))
7139 SDValue TCChain = Chain;
7140 SDNode *Copy = *N->use_begin();
7141 if (Copy->getOpcode() == ISD::CopyToReg) {
7142 // If the copy has a glue operand, we conservatively assume it isn't safe to
7143 // perform a tail call.
7144 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7147 TCChain = Copy->getOperand(0);
7148 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7151 bool HasRet = false;
7152 for (SDNode *Node : Copy->uses()) {
7153 if (Node->getOpcode() != ARM64ISD::RET_FLAG)
7165 // Return whether the an instruction can potentially be optimized to a tail
7166 // call. This will cause the optimizers to attempt to move, or duplicate,
7167 // return instructions to help enable tail call optimizations for this
7169 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7170 if (!EnableARM64TailCalls)
7173 if (!CI->isTailCall())
7179 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7181 ISD::MemIndexedMode &AM,
7183 SelectionDAG &DAG) const {
7184 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7187 Base = Op->getOperand(0);
7188 // All of the indexed addressing mode instructions take a signed
7189 // 9 bit immediate offset.
7190 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7191 int64_t RHSC = (int64_t)RHS->getZExtValue();
7192 if (RHSC >= 256 || RHSC <= -256)
7194 IsInc = (Op->getOpcode() == ISD::ADD);
7195 Offset = Op->getOperand(1);
7201 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7203 ISD::MemIndexedMode &AM,
7204 SelectionDAG &DAG) const {
7207 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7208 VT = LD->getMemoryVT();
7209 Ptr = LD->getBasePtr();
7210 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7211 VT = ST->getMemoryVT();
7212 Ptr = ST->getBasePtr();
7217 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7219 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7223 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7226 ISD::MemIndexedMode &AM,
7227 SelectionDAG &DAG) const {
7230 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7231 VT = LD->getMemoryVT();
7232 Ptr = LD->getBasePtr();
7233 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7234 VT = ST->getMemoryVT();
7235 Ptr = ST->getBasePtr();
7240 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7242 // Post-indexing updates the base, so it's not a valid transform
7243 // if that's not the same as the load's pointer.
7246 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7250 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7251 SmallVectorImpl<SDValue> &Results,
7252 SelectionDAG &DAG) const {
7253 switch (N->getOpcode()) {
7255 llvm_unreachable("Don't know how to custom expand this");
7256 case ISD::FP_TO_UINT:
7257 case ISD::FP_TO_SINT:
7258 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7259 // Let normal code take care of it by not adding anything to Results.
7264 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
7265 // Loads and stores less than 128-bits are already atomic; ones above that
7266 // are doomed anyway, so defer to the default libcall and blame the OS when
7268 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
7269 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
7270 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
7271 return LI->getType()->getPrimitiveSizeInBits() == 128;
7273 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
7274 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
7277 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
7278 AtomicOrdering Ord) const {
7279 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7280 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
7282 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7284 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
7285 // intrinsic must return {i64, i64} and we have to recombine them into a
7286 // single i128 here.
7287 if (ValTy->getPrimitiveSizeInBits() == 128) {
7289 IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
7290 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
7292 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7293 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
7295 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
7296 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
7297 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
7298 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
7299 return Builder.CreateOr(
7300 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
7303 Type *Tys[] = { Addr->getType() };
7305 IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
7306 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
7308 return Builder.CreateTruncOrBitCast(
7309 Builder.CreateCall(Ldxr, Addr),
7310 cast<PointerType>(Addr->getType())->getElementType());
7313 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
7314 Value *Val, Value *Addr,
7315 AtomicOrdering Ord) const {
7316 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7318 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7320 // Since the intrinsics must have legal type, the i128 intrinsics take two
7321 // parameters: "i64, i64". We must marshal Val into the appropriate form
7323 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7325 IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7326 Function *Stxr = Intrinsic::getDeclaration(M, Int);
7327 Type *Int64Ty = Type::getInt64Ty(M->getContext());
7329 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7330 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7331 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7332 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7336 IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7337 Type *Tys[] = { Addr->getType() };
7338 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7340 return Builder.CreateCall2(
7341 Stxr, Builder.CreateZExtOrBitCast(
7342 Val, Stxr->getFunctionType()->getParamType(0)),