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;
1681 // FIXME: This works on big-endian for composite byvals, which are the common
1682 // case. It should also work for fundamental types too.
1684 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1685 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1686 InVals.push_back(FrameIdxN);
1689 } if (VA.isRegLoc()) {
1690 // Arguments stored in registers.
1691 EVT RegVT = VA.getLocVT();
1694 const TargetRegisterClass *RC;
1696 if (RegVT == MVT::i32)
1697 RC = &ARM64::GPR32RegClass;
1698 else if (RegVT == MVT::i64)
1699 RC = &ARM64::GPR64RegClass;
1700 else if (RegVT == MVT::f32)
1701 RC = &ARM64::FPR32RegClass;
1702 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
1703 RC = &ARM64::FPR64RegClass;
1704 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
1705 RC = &ARM64::FPR128RegClass;
1707 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1709 // Transform the arguments in physical registers into virtual ones.
1710 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1711 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1713 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1714 // to 64 bits. Insert an assert[sz]ext to capture this, then
1715 // truncate to the right size.
1716 switch (VA.getLocInfo()) {
1718 llvm_unreachable("Unknown loc info!");
1719 case CCValAssign::Full:
1721 case CCValAssign::BCvt:
1722 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1724 case CCValAssign::SExt:
1725 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
1726 DAG.getValueType(VA.getValVT()));
1727 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1729 case CCValAssign::ZExt:
1730 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
1731 DAG.getValueType(VA.getValVT()));
1732 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1736 InVals.push_back(ArgValue);
1738 } else { // VA.isRegLoc()
1739 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1740 unsigned ArgOffset = VA.getLocMemOffset();
1741 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1743 uint32_t BEAlign = 0;
1744 if (ArgSize < 8 && !Subtarget->isLittleEndian())
1745 BEAlign = 8 - ArgSize;
1747 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
1749 // Create load nodes to retrieve arguments from the stack.
1750 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1753 // If the loc type and val type are not the same, create an anyext load.
1754 if (VA.getLocVT().getSizeInBits() != VA.getValVT().getSizeInBits()) {
1755 // We should only get here if this is a pure integer.
1756 assert(!VA.getValVT().isVector() && VA.getValVT().isInteger() &&
1757 "Only integer extension supported!");
1758 ArgValue = DAG.getExtLoad(ISD::EXTLOAD, DL, VA.getValVT(), Chain, FIN,
1759 MachinePointerInfo::getFixedStack(FI),
1761 false, false, false, 0);
1763 ArgValue = DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
1764 MachinePointerInfo::getFixedStack(FI), false,
1768 InVals.push_back(ArgValue);
1774 if (!Subtarget->isTargetDarwin()) {
1775 // The AAPCS variadic function ABI is identical to the non-variadic
1776 // one. As a result there may be more arguments in registers and we should
1777 // save them for future reference.
1778 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1781 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
1782 // This will point to the next argument passed via stack.
1783 unsigned StackOffset = CCInfo.getNextStackOffset();
1784 // We currently pass all varargs at 8-byte alignment.
1785 StackOffset = ((StackOffset + 7) & ~7);
1786 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1792 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1793 SelectionDAG &DAG, SDLoc DL,
1794 SDValue &Chain) const {
1795 MachineFunction &MF = DAG.getMachineFunction();
1796 MachineFrameInfo *MFI = MF.getFrameInfo();
1797 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
1799 SmallVector<SDValue, 8> MemOps;
1801 static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
1802 ARM64::X3, ARM64::X4, ARM64::X5,
1803 ARM64::X6, ARM64::X7 };
1804 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1805 unsigned FirstVariadicGPR =
1806 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1808 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1810 if (GPRSaveSize != 0) {
1811 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1813 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1815 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1816 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
1817 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1819 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1820 MachinePointerInfo::getStack(i * 8), false, false, 0);
1821 MemOps.push_back(Store);
1822 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1823 DAG.getConstant(8, getPointerTy()));
1826 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1827 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1829 if (Subtarget->hasFPARMv8()) {
1830 static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
1831 ARM64::Q3, ARM64::Q4, ARM64::Q5,
1832 ARM64::Q6, ARM64::Q7 };
1833 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1834 unsigned FirstVariadicFPR =
1835 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1837 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1839 if (FPRSaveSize != 0) {
1840 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1842 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1844 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1845 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
1846 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
1848 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1849 MachinePointerInfo::getStack(i * 16), false, false, 0);
1850 MemOps.push_back(Store);
1851 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1852 DAG.getConstant(16, getPointerTy()));
1855 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1856 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1859 if (!MemOps.empty()) {
1860 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1864 /// LowerCallResult - Lower the result values of a call into the
1865 /// appropriate copies out of appropriate physical registers.
1866 SDValue ARM64TargetLowering::LowerCallResult(
1867 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1868 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1869 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1870 SDValue ThisVal) const {
1871 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1872 : RetCC_ARM64_AAPCS;
1873 // Assign locations to each value returned by this call.
1874 SmallVector<CCValAssign, 16> RVLocs;
1875 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1876 getTargetMachine(), RVLocs, *DAG.getContext());
1877 CCInfo.AnalyzeCallResult(Ins, RetCC);
1879 // Copy all of the result registers out of their specified physreg.
1880 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1881 CCValAssign VA = RVLocs[i];
1883 // Pass 'this' value directly from the argument to return value, to avoid
1884 // reg unit interference
1885 if (i == 0 && isThisReturn) {
1886 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1887 "unexpected return calling convention register assignment");
1888 InVals.push_back(ThisVal);
1893 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1894 Chain = Val.getValue(1);
1895 InFlag = Val.getValue(2);
1897 switch (VA.getLocInfo()) {
1899 llvm_unreachable("Unknown loc info!");
1900 case CCValAssign::Full:
1902 case CCValAssign::BCvt:
1903 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1907 InVals.push_back(Val);
1913 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
1914 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1915 bool isCalleeStructRet, bool isCallerStructRet,
1916 const SmallVectorImpl<ISD::OutputArg> &Outs,
1917 const SmallVectorImpl<SDValue> &OutVals,
1918 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1919 // Look for obvious safe cases to perform tail call optimization that do not
1920 // require ABI changes. This is what gcc calls sibcall.
1922 // Do not sibcall optimize vararg calls unless the call site is not passing
1924 if (isVarArg && !Outs.empty())
1927 // Also avoid sibcall optimization if either caller or callee uses struct
1928 // return semantics.
1929 if (isCalleeStructRet || isCallerStructRet)
1932 // Note that currently ARM64 "C" calling convention and "Fast" calling
1933 // convention are compatible. If/when that ever changes, we'll need to
1934 // add checks here to make sure any interactions are OK.
1936 // If the callee takes no arguments then go on to check the results of the
1938 if (!Outs.empty()) {
1939 // Check if stack adjustment is needed. For now, do not do this if any
1940 // argument is passed on the stack.
1941 SmallVector<CCValAssign, 16> ArgLocs;
1942 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1943 getTargetMachine(), ArgLocs, *DAG.getContext());
1944 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
1945 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
1946 if (CCInfo.getNextStackOffset()) {
1947 // Check if the arguments are already laid out in the right way as
1948 // the caller's fixed stack objects.
1949 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1950 ++i, ++realArgIdx) {
1951 CCValAssign &VA = ArgLocs[i];
1952 if (VA.getLocInfo() == CCValAssign::Indirect)
1954 if (VA.needsCustom()) {
1955 // Just don't handle anything that needs custom adjustments for now.
1956 // If need be, we can revisit later, but we shouldn't ever end up
1959 } else if (!VA.isRegLoc()) {
1960 // Likewise, don't try to handle stack based arguments for the
1970 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
1971 /// and add input and output parameter nodes.
1972 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1973 SmallVectorImpl<SDValue> &InVals) const {
1974 SelectionDAG &DAG = CLI.DAG;
1976 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1977 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1978 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1979 SDValue Chain = CLI.Chain;
1980 SDValue Callee = CLI.Callee;
1981 bool &IsTailCall = CLI.IsTailCall;
1982 CallingConv::ID CallConv = CLI.CallConv;
1983 bool IsVarArg = CLI.IsVarArg;
1985 MachineFunction &MF = DAG.getMachineFunction();
1986 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1987 bool IsThisReturn = false;
1989 // If tail calls are explicitly disabled, make sure not to use them.
1990 if (!EnableARM64TailCalls)
1994 // Check if it's really possible to do a tail call.
1995 IsTailCall = isEligibleForTailCallOptimization(
1996 Callee, CallConv, IsVarArg, IsStructRet,
1997 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
1998 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
1999 report_fatal_error("failed to perform tail call elimination on a call "
2000 "site marked musttail");
2001 // We don't support GuaranteedTailCallOpt, only automatically
2002 // detected sibcalls.
2003 // FIXME: Re-evaluate. Is this true? Should it be true?
2008 // Analyze operands of the call, assigning locations to each operand.
2009 SmallVector<CCValAssign, 16> ArgLocs;
2010 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2011 getTargetMachine(), ArgLocs, *DAG.getContext());
2014 // Handle fixed and variable vector arguments differently.
2015 // Variable vector arguments always go into memory.
2016 unsigned NumArgs = Outs.size();
2018 for (unsigned i = 0; i != NumArgs; ++i) {
2019 MVT ArgVT = Outs[i].VT;
2020 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2021 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2022 /*IsVarArg=*/ !Outs[i].IsFixed);
2023 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2024 assert(!Res && "Call operand has unhandled type");
2028 // At this point, Outs[].VT may already be promoted to i32. To correctly
2029 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2030 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2031 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2032 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2034 unsigned NumArgs = Outs.size();
2035 for (unsigned i = 0; i != NumArgs; ++i) {
2036 MVT ValVT = Outs[i].VT;
2037 // Get type of the original argument.
2038 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
2039 /*AllowUnknown*/ true);
2040 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2041 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2042 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2044 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2046 else if (ActualMVT == MVT::i16)
2049 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2050 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
2051 assert(!Res && "Call operand has unhandled type");
2056 // Get a count of how many bytes are to be pushed on the stack.
2057 unsigned NumBytes = CCInfo.getNextStackOffset();
2059 // Adjust the stack pointer for the new arguments...
2060 // These operations are automatically eliminated by the prolog/epilog pass
2063 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2065 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
2067 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2068 SmallVector<SDValue, 8> MemOpChains;
2070 // Walk the register/memloc assignments, inserting copies/loads.
2071 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2072 ++i, ++realArgIdx) {
2073 CCValAssign &VA = ArgLocs[i];
2074 SDValue Arg = OutVals[realArgIdx];
2075 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2077 // Promote the value if needed.
2078 switch (VA.getLocInfo()) {
2080 llvm_unreachable("Unknown loc info!");
2081 case CCValAssign::Full:
2083 case CCValAssign::SExt:
2084 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2086 case CCValAssign::ZExt:
2087 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2089 case CCValAssign::AExt:
2090 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2092 case CCValAssign::BCvt:
2093 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2095 case CCValAssign::FPExt:
2096 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2100 if (VA.isRegLoc()) {
2101 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2102 assert(VA.getLocVT() == MVT::i64 &&
2103 "unexpected calling convention register assignment");
2104 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2105 "unexpected use of 'returned'");
2106 IsThisReturn = true;
2108 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2110 assert(VA.isMemLoc());
2111 // There's no reason we can't support stack args w/ tailcall, but
2112 // we currently don't, so assert if we see one.
2113 assert(!IsTailCall && "stack argument with tail call!?");
2115 // FIXME: This works on big-endian for composite byvals, which are the common
2116 // case. It should also work for fundamental types too.
2117 uint32_t BEAlign = 0;
2118 if (!Subtarget->isLittleEndian() && !Flags.isByVal()) {
2119 unsigned OpSize = (VA.getLocVT().getSizeInBits() + 7) / 8;
2121 BEAlign = 8 - OpSize;
2124 unsigned LocMemOffset = VA.getLocMemOffset();
2125 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset + BEAlign);
2126 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2128 if (Outs[i].Flags.isByVal()) {
2130 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2131 SDValue Cpy = DAG.getMemcpy(
2132 Chain, DL, PtrOff, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2133 /*isVolatile = */ false,
2134 /*alwaysInline = */ false,
2135 MachinePointerInfo::getStack(LocMemOffset), MachinePointerInfo());
2137 MemOpChains.push_back(Cpy);
2139 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2140 // promoted to a legal register type i32, we should truncate Arg back to
2142 if (Arg.getValueType().isSimple() &&
2143 Arg.getValueType().getSimpleVT() == MVT::i32 &&
2144 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2145 VA.getLocVT() == MVT::i16))
2146 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2148 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2149 MachinePointerInfo::getStack(LocMemOffset),
2151 MemOpChains.push_back(Store);
2156 if (!MemOpChains.empty())
2157 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2159 // Build a sequence of copy-to-reg nodes chained together with token chain
2160 // and flag operands which copy the outgoing args into the appropriate regs.
2162 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2163 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2164 RegsToPass[i].second, InFlag);
2165 InFlag = Chain.getValue(1);
2168 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2169 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2170 // node so that legalize doesn't hack it.
2171 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2172 Subtarget->isTargetMachO()) {
2173 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2174 const GlobalValue *GV = G->getGlobal();
2175 bool InternalLinkage = GV->hasInternalLinkage();
2176 if (InternalLinkage)
2177 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2179 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2181 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2183 } else if (ExternalSymbolSDNode *S =
2184 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2185 const char *Sym = S->getSymbol();
2187 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2188 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2190 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2191 const GlobalValue *GV = G->getGlobal();
2192 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2193 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2194 const char *Sym = S->getSymbol();
2195 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2198 std::vector<SDValue> Ops;
2199 Ops.push_back(Chain);
2200 Ops.push_back(Callee);
2202 // Add argument registers to the end of the list so that they are known live
2204 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2205 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2206 RegsToPass[i].second.getValueType()));
2208 // Add a register mask operand representing the call-preserved registers.
2209 const uint32_t *Mask;
2210 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2211 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2213 // For 'this' returns, use the X0-preserving mask if applicable
2214 Mask = ARI->getThisReturnPreservedMask(CallConv);
2216 IsThisReturn = false;
2217 Mask = ARI->getCallPreservedMask(CallConv);
2220 Mask = ARI->getCallPreservedMask(CallConv);
2222 assert(Mask && "Missing call preserved mask for calling convention");
2223 Ops.push_back(DAG.getRegisterMask(Mask));
2225 if (InFlag.getNode())
2226 Ops.push_back(InFlag);
2228 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2230 // If we're doing a tall call, use a TC_RETURN here rather than an
2231 // actual call instruction.
2233 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, Ops);
2235 // Returns a chain and a flag for retval copy to use.
2236 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, Ops);
2237 InFlag = Chain.getValue(1);
2239 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2240 DAG.getIntPtrConstant(0, true), InFlag, DL);
2242 InFlag = Chain.getValue(1);
2244 // Handle result values, copying them out of physregs into vregs that we
2246 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2247 InVals, IsThisReturn,
2248 IsThisReturn ? OutVals[0] : SDValue());
2251 bool ARM64TargetLowering::CanLowerReturn(
2252 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2253 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2254 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2255 : RetCC_ARM64_AAPCS;
2256 SmallVector<CCValAssign, 16> RVLocs;
2257 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2258 return CCInfo.CheckReturn(Outs, RetCC);
2262 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2264 const SmallVectorImpl<ISD::OutputArg> &Outs,
2265 const SmallVectorImpl<SDValue> &OutVals,
2266 SDLoc DL, SelectionDAG &DAG) const {
2267 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2268 : RetCC_ARM64_AAPCS;
2269 SmallVector<CCValAssign, 16> RVLocs;
2270 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2271 getTargetMachine(), RVLocs, *DAG.getContext());
2272 CCInfo.AnalyzeReturn(Outs, RetCC);
2274 // Copy the result values into the output registers.
2276 SmallVector<SDValue, 4> RetOps(1, Chain);
2277 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2278 ++i, ++realRVLocIdx) {
2279 CCValAssign &VA = RVLocs[i];
2280 assert(VA.isRegLoc() && "Can only return in registers!");
2281 SDValue Arg = OutVals[realRVLocIdx];
2283 switch (VA.getLocInfo()) {
2285 llvm_unreachable("Unknown loc info!");
2286 case CCValAssign::Full:
2288 case CCValAssign::BCvt:
2289 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2293 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2294 Flag = Chain.getValue(1);
2295 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2298 RetOps[0] = Chain; // Update chain.
2300 // Add the flag if we have it.
2302 RetOps.push_back(Flag);
2304 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2307 //===----------------------------------------------------------------------===//
2308 // Other Lowering Code
2309 //===----------------------------------------------------------------------===//
2311 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2312 SelectionDAG &DAG) const {
2313 EVT PtrVT = getPointerTy();
2315 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2316 unsigned char OpFlags =
2317 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2319 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2320 "unexpected offset in global node");
2322 // This also catched the large code model case for Darwin.
2323 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2324 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2325 // FIXME: Once remat is capable of dealing with instructions with register
2326 // operands, expand this into two nodes instead of using a wrapper node.
2327 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2330 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2331 const unsigned char MO_NC = ARM64II::MO_NC;
2333 ARM64ISD::WrapperLarge, DL, PtrVT,
2334 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2335 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2336 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2337 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2339 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2340 // the only correct model on Darwin.
2341 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2342 OpFlags | ARM64II::MO_PAGE);
2343 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2344 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2346 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2347 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2351 /// \brief Convert a TLS address reference into the correct sequence of loads
2352 /// and calls to compute the variable's address (for Darwin, currently) and
2353 /// return an SDValue containing the final node.
2355 /// Darwin only has one TLS scheme which must be capable of dealing with the
2356 /// fully general situation, in the worst case. This means:
2357 /// + "extern __thread" declaration.
2358 /// + Defined in a possibly unknown dynamic library.
2360 /// The general system is that each __thread variable has a [3 x i64] descriptor
2361 /// which contains information used by the runtime to calculate the address. The
2362 /// only part of this the compiler needs to know about is the first xword, which
2363 /// contains a function pointer that must be called with the address of the
2364 /// entire descriptor in "x0".
2366 /// Since this descriptor may be in a different unit, in general even the
2367 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2369 /// adrp x0, _var@TLVPPAGE
2370 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2371 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2372 /// ; the function pointer
2373 /// blr x1 ; Uses descriptor address in x0
2374 /// ; Address of _var is now in x0.
2376 /// If the address of _var's descriptor *is* known to the linker, then it can
2377 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2378 /// a slight efficiency gain.
2380 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2381 SelectionDAG &DAG) const {
2382 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2385 MVT PtrVT = getPointerTy();
2386 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2389 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2390 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2392 // The first entry in the descriptor is a function pointer that we must call
2393 // to obtain the address of the variable.
2394 SDValue Chain = DAG.getEntryNode();
2395 SDValue FuncTLVGet =
2396 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2397 false, true, true, 8);
2398 Chain = FuncTLVGet.getValue(1);
2400 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2401 MFI->setAdjustsStack(true);
2403 // TLS calls preserve all registers except those that absolutely must be
2404 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2406 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2407 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2408 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2410 // Finally, we can make the call. This is just a degenerate version of a
2411 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2412 // the address of the variable in this thread.
2413 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2414 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2415 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2416 DAG.getRegisterMask(Mask), Chain.getValue(1));
2417 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2420 /// When accessing thread-local variables under either the general-dynamic or
2421 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2422 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2423 /// is a function pointer to carry out the resolution. This function takes the
2424 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2425 /// other registers (except LR, NZCV) are preserved.
2427 /// Thus, the ideal call sequence on AArch64 is:
2429 /// adrp x0, :tlsdesc:thread_var
2430 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2431 /// add x0, x0, :tlsdesc_lo12:thread_var
2432 /// .tlsdesccall thread_var
2434 /// (TPIDR_EL0 offset now in x0).
2436 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2437 /// relocation to help the linker relax this sequence if it turns out to be too
2440 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2442 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2443 SDValue DescAddr, SDLoc DL,
2444 SelectionDAG &DAG) const {
2445 EVT PtrVT = getPointerTy();
2447 // The function we need to call is simply the first entry in the GOT for this
2448 // descriptor, load it in preparation.
2449 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2451 // TLS calls preserve all registers except those that absolutely must be
2452 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2454 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2455 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2456 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2458 // The function takes only one argument: the address of the descriptor itself
2460 SDValue Glue, Chain;
2461 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2462 Glue = Chain.getValue(1);
2464 // We're now ready to populate the argument list, as with a normal call:
2465 SmallVector<SDValue, 6> Ops;
2466 Ops.push_back(Chain);
2467 Ops.push_back(Func);
2468 Ops.push_back(SymAddr);
2469 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2470 Ops.push_back(DAG.getRegisterMask(Mask));
2471 Ops.push_back(Glue);
2473 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2474 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, Ops);
2475 Glue = Chain.getValue(1);
2477 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2480 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2481 SelectionDAG &DAG) const {
2482 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2483 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2484 "ELF TLS only supported in small memory model");
2485 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2487 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2490 EVT PtrVT = getPointerTy();
2492 const GlobalValue *GV = GA->getGlobal();
2494 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2496 if (Model == TLSModel::LocalExec) {
2497 SDValue HiVar = DAG.getTargetGlobalAddress(
2498 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2499 SDValue LoVar = DAG.getTargetGlobalAddress(
2500 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2502 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2503 DAG.getTargetConstant(16, MVT::i32)),
2505 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2506 DAG.getTargetConstant(0, MVT::i32)),
2508 } else if (Model == TLSModel::InitialExec) {
2509 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2510 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2511 } else if (Model == TLSModel::LocalDynamic) {
2512 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2513 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2514 // the beginning of the module's TLS region, followed by a DTPREL offset
2517 // These accesses will need deduplicating if there's more than one.
2518 ARM64FunctionInfo *MFI =
2519 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2520 MFI->incNumLocalDynamicTLSAccesses();
2522 // Accesses used in this sequence go via the TLS descriptor which lives in
2523 // the GOT. Prepare an address we can use to handle this.
2524 SDValue HiDesc = DAG.getTargetExternalSymbol(
2525 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2526 SDValue LoDesc = DAG.getTargetExternalSymbol(
2527 "_TLS_MODULE_BASE_", PtrVT,
2528 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2530 // First argument to the descriptor call is the address of the descriptor
2532 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2533 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2535 // The call needs a relocation too for linker relaxation. It doesn't make
2536 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2538 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2541 // Now we can calculate the offset from TPIDR_EL0 to this module's
2542 // thread-local area.
2543 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2545 // Now use :dtprel_whatever: operations to calculate this variable's offset
2546 // in its thread-storage area.
2547 SDValue HiVar = DAG.getTargetGlobalAddress(
2548 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2549 SDValue LoVar = DAG.getTargetGlobalAddress(
2550 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2553 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2554 DAG.getTargetConstant(16, MVT::i32)),
2556 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2557 DAG.getTargetConstant(0, MVT::i32)),
2560 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2561 } else if (Model == TLSModel::GeneralDynamic) {
2562 // Accesses used in this sequence go via the TLS descriptor which lives in
2563 // the GOT. Prepare an address we can use to handle this.
2564 SDValue HiDesc = DAG.getTargetGlobalAddress(
2565 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2566 SDValue LoDesc = DAG.getTargetGlobalAddress(
2568 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2570 // First argument to the descriptor call is the address of the descriptor
2572 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2573 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2575 // The call needs a relocation too for linker relaxation. It doesn't make
2576 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2579 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2581 // Finally we can make a call to calculate the offset from tpidr_el0.
2582 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2584 llvm_unreachable("Unsupported ELF TLS access model");
2586 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2589 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2590 SelectionDAG &DAG) const {
2591 if (Subtarget->isTargetDarwin())
2592 return LowerDarwinGlobalTLSAddress(Op, DAG);
2593 else if (Subtarget->isTargetELF())
2594 return LowerELFGlobalTLSAddress(Op, DAG);
2596 llvm_unreachable("Unexpected platform trying to use TLS");
2598 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2599 SDValue Chain = Op.getOperand(0);
2600 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2601 SDValue LHS = Op.getOperand(2);
2602 SDValue RHS = Op.getOperand(3);
2603 SDValue Dest = Op.getOperand(4);
2606 // Handle f128 first, since lowering it will result in comparing the return
2607 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2608 // is expecting to deal with.
2609 if (LHS.getValueType() == MVT::f128) {
2610 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2612 // If softenSetCCOperands returned a scalar, we need to compare the result
2613 // against zero to select between true and false values.
2614 if (!RHS.getNode()) {
2615 RHS = DAG.getConstant(0, LHS.getValueType());
2620 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2622 unsigned Opc = LHS.getOpcode();
2623 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2624 cast<ConstantSDNode>(RHS)->isOne() &&
2625 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2626 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2627 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2628 "Unexpected condition code.");
2629 // Only lower legal XALUO ops.
2630 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2633 // The actual operation with overflow check.
2634 ARM64CC::CondCode OFCC;
2635 SDValue Value, Overflow;
2636 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2638 if (CC == ISD::SETNE)
2639 OFCC = getInvertedCondCode(OFCC);
2640 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2642 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2646 if (LHS.getValueType().isInteger()) {
2647 assert((LHS.getValueType() == RHS.getValueType()) &&
2648 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2650 // If the RHS of the comparison is zero, we can potentially fold this
2651 // to a specialized branch.
2652 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2653 if (RHSC && RHSC->getZExtValue() == 0) {
2654 if (CC == ISD::SETEQ) {
2655 // See if we can use a TBZ to fold in an AND as well.
2656 // TBZ has a smaller branch displacement than CBZ. If the offset is
2657 // out of bounds, a late MI-layer pass rewrites branches.
2658 // 403.gcc is an example that hits this case.
2659 if (LHS.getOpcode() == ISD::AND &&
2660 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2661 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2662 SDValue Test = LHS.getOperand(0);
2663 uint64_t Mask = LHS.getConstantOperandVal(1);
2665 // TBZ only operates on i64's, but the ext should be free.
2666 if (Test.getValueType() == MVT::i32)
2667 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2669 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
2670 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2673 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2674 } else if (CC == ISD::SETNE) {
2675 // See if we can use a TBZ to fold in an AND as well.
2676 // TBZ has a smaller branch displacement than CBZ. If the offset is
2677 // out of bounds, a late MI-layer pass rewrites branches.
2678 // 403.gcc is an example that hits this case.
2679 if (LHS.getOpcode() == ISD::AND &&
2680 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2681 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2682 SDValue Test = LHS.getOperand(0);
2683 uint64_t Mask = LHS.getConstantOperandVal(1);
2685 // TBNZ only operates on i64's, but the ext should be free.
2686 if (Test.getValueType() == MVT::i32)
2687 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2689 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2690 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2693 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2698 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2699 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2703 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2705 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2706 // clean. Some of them require two branches to implement.
2707 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2708 ARM64CC::CondCode CC1, CC2;
2709 changeFPCCToARM64CC(CC, CC1, CC2);
2710 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2712 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2713 if (CC2 != ARM64CC::AL) {
2714 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2715 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2722 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2723 SelectionDAG &DAG) const {
2724 EVT VT = Op.getValueType();
2727 SDValue In1 = Op.getOperand(0);
2728 SDValue In2 = Op.getOperand(1);
2729 EVT SrcVT = In2.getValueType();
2731 if (SrcVT == MVT::f32 && VT == MVT::f64)
2732 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2733 else if (SrcVT == MVT::f64 && VT == MVT::f32)
2734 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
2736 // FIXME: Src type is different, bail out for now. Can VT really be a
2743 SDValue EltMask, VecVal1, VecVal2;
2744 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
2747 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
2749 if (!VT.isVector()) {
2750 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2751 DAG.getUNDEF(VecVT), In1);
2752 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2753 DAG.getUNDEF(VecVT), In2);
2755 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2756 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2758 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
2762 // We want to materialize a mask with the the high bit set, but the AdvSIMD
2763 // immediate moves cannot materialize that in a single instruction for
2764 // 64-bit elements. Instead, materialize zero and then negate it.
2765 EltMask = DAG.getConstant(0, EltVT);
2767 if (!VT.isVector()) {
2768 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2769 DAG.getUNDEF(VecVT), In1);
2770 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2771 DAG.getUNDEF(VecVT), In2);
2773 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2774 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2777 llvm_unreachable("Invalid type for copysign!");
2780 std::vector<SDValue> BuildVectorOps;
2781 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
2782 BuildVectorOps.push_back(EltMask);
2784 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
2786 // If we couldn't materialize the mask above, then the mask vector will be
2787 // the zero vector, and we need to negate it here.
2788 if (VT == MVT::f64 || VT == MVT::v2f64) {
2789 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
2790 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
2791 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
2795 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
2798 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
2799 else if (VT == MVT::f64)
2800 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
2802 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
2805 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
2806 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
2807 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
2810 // While there is no integer popcount instruction, it can
2811 // be more efficiently lowered to the following sequence that uses
2812 // AdvSIMD registers/instructions as long as the copies to/from
2813 // the AdvSIMD registers are cheap.
2814 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
2815 // CNT V0.8B, V0.8B // 8xbyte pop-counts
2816 // ADDV B0, V0.8B // sum 8xbyte pop-counts
2817 // UMOV X0, V0.B[0] // copy byte result back to integer reg
2818 SDValue Val = Op.getOperand(0);
2820 EVT VT = Op.getValueType();
2821 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
2824 if (VT == MVT::i32) {
2825 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
2827 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
2829 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
2832 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
2833 SDValue UaddLV = DAG.getNode(
2834 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2835 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
2838 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
2842 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2844 if (Op.getValueType().isVector())
2845 return LowerVSETCC(Op, DAG);
2847 SDValue LHS = Op.getOperand(0);
2848 SDValue RHS = Op.getOperand(1);
2849 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2852 // We chose ZeroOrOneBooleanContents, so use zero and one.
2853 EVT VT = Op.getValueType();
2854 SDValue TVal = DAG.getConstant(1, VT);
2855 SDValue FVal = DAG.getConstant(0, VT);
2857 // Handle f128 first, since one possible outcome is a normal integer
2858 // comparison which gets picked up by the next if statement.
2859 if (LHS.getValueType() == MVT::f128) {
2860 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2862 // If softenSetCCOperands returned a scalar, use it.
2863 if (!RHS.getNode()) {
2864 assert(LHS.getValueType() == Op.getValueType() &&
2865 "Unexpected setcc expansion!");
2870 if (LHS.getValueType().isInteger()) {
2873 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
2875 // Note that we inverted the condition above, so we reverse the order of
2876 // the true and false operands here. This will allow the setcc to be
2877 // matched to a single CSINC instruction.
2878 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
2881 // Now we know we're dealing with FP values.
2882 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2884 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
2885 // and do the comparison.
2886 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2888 ARM64CC::CondCode CC1, CC2;
2889 changeFPCCToARM64CC(CC, CC1, CC2);
2890 if (CC2 == ARM64CC::AL) {
2891 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
2892 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2894 // Note that we inverted the condition above, so we reverse the order of
2895 // the true and false operands here. This will allow the setcc to be
2896 // matched to a single CSINC instruction.
2897 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
2899 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2900 // clean. Some of them require two CSELs to implement. As is in this case,
2901 // we emit the first CSEL and then emit a second using the output of the
2902 // first as the RHS. We're effectively OR'ing the two CC's together.
2904 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
2905 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2906 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2908 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2909 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
2913 /// A SELECT_CC operation is really some kind of max or min if both values being
2914 /// compared are, in some sense, equal to the results in either case. However,
2915 /// it is permissible to compare f32 values and produce directly extended f64
2918 /// Extending the comparison operands would also be allowed, but is less likely
2919 /// to happen in practice since their use is right here. Note that truncate
2920 /// operations would *not* be semantically equivalent.
2921 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
2925 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
2926 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
2927 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
2928 Result.getValueType() == MVT::f64) {
2930 APFloat CmpVal = CCmp->getValueAPF();
2931 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
2932 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
2935 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
2938 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2939 SDValue CC = Op->getOperand(0);
2940 SDValue TVal = Op->getOperand(1);
2941 SDValue FVal = Op->getOperand(2);
2944 unsigned Opc = CC.getOpcode();
2945 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
2947 if (CC.getResNo() == 1 &&
2948 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2949 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2950 // Only lower legal XALUO ops.
2951 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
2954 ARM64CC::CondCode OFCC;
2955 SDValue Value, Overflow;
2956 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
2957 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2959 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
2963 if (CC.getOpcode() == ISD::SETCC)
2964 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
2965 cast<CondCodeSDNode>(CC.getOperand(2))->get());
2967 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
2971 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
2972 SelectionDAG &DAG) const {
2973 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2974 SDValue LHS = Op.getOperand(0);
2975 SDValue RHS = Op.getOperand(1);
2976 SDValue TVal = Op.getOperand(2);
2977 SDValue FVal = Op.getOperand(3);
2980 // Handle f128 first, because it will result in a comparison of some RTLIB
2981 // call result against zero.
2982 if (LHS.getValueType() == MVT::f128) {
2983 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2985 // If softenSetCCOperands returned a scalar, we need to compare the result
2986 // against zero to select between true and false values.
2987 if (!RHS.getNode()) {
2988 RHS = DAG.getConstant(0, LHS.getValueType());
2993 // Handle integers first.
2994 if (LHS.getValueType().isInteger()) {
2995 assert((LHS.getValueType() == RHS.getValueType()) &&
2996 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2998 unsigned Opcode = ARM64ISD::CSEL;
3000 // If both the TVal and the FVal are constants, see if we can swap them in
3001 // order to for a CSINV or CSINC out of them.
3002 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3003 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3005 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3006 std::swap(TVal, FVal);
3007 std::swap(CTVal, CFVal);
3008 CC = ISD::getSetCCInverse(CC, true);
3009 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3010 std::swap(TVal, FVal);
3011 std::swap(CTVal, CFVal);
3012 CC = ISD::getSetCCInverse(CC, true);
3013 } else if (TVal.getOpcode() == ISD::XOR) {
3014 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3015 // with a CSINV rather than a CSEL.
3016 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3018 if (CVal && CVal->isAllOnesValue()) {
3019 std::swap(TVal, FVal);
3020 std::swap(CTVal, CFVal);
3021 CC = ISD::getSetCCInverse(CC, true);
3023 } else if (TVal.getOpcode() == ISD::SUB) {
3024 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3025 // that we can match with a CSNEG rather than a CSEL.
3026 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3028 if (CVal && CVal->isNullValue()) {
3029 std::swap(TVal, FVal);
3030 std::swap(CTVal, CFVal);
3031 CC = ISD::getSetCCInverse(CC, true);
3033 } else if (CTVal && CFVal) {
3034 const int64_t TrueVal = CTVal->getSExtValue();
3035 const int64_t FalseVal = CFVal->getSExtValue();
3038 // If both TVal and FVal are constants, see if FVal is the
3039 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3040 // instead of a CSEL in that case.
3041 if (TrueVal == ~FalseVal) {
3042 Opcode = ARM64ISD::CSINV;
3043 } else if (TrueVal == -FalseVal) {
3044 Opcode = ARM64ISD::CSNEG;
3045 } else if (TVal.getValueType() == MVT::i32) {
3046 // If our operands are only 32-bit wide, make sure we use 32-bit
3047 // arithmetic for the check whether we can use CSINC. This ensures that
3048 // the addition in the check will wrap around properly in case there is
3049 // an overflow (which would not be the case if we do the check with
3050 // 64-bit arithmetic).
3051 const uint32_t TrueVal32 = CTVal->getZExtValue();
3052 const uint32_t FalseVal32 = CFVal->getZExtValue();
3054 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3055 Opcode = ARM64ISD::CSINC;
3057 if (TrueVal32 > FalseVal32) {
3061 // 64-bit check whether we can use CSINC.
3062 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3063 Opcode = ARM64ISD::CSINC;
3065 if (TrueVal > FalseVal) {
3070 // Swap TVal and FVal if necessary.
3072 std::swap(TVal, FVal);
3073 std::swap(CTVal, CFVal);
3074 CC = ISD::getSetCCInverse(CC, true);
3077 if (Opcode != ARM64ISD::CSEL) {
3078 // Drop FVal since we can get its value by simply inverting/negating
3085 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3087 EVT VT = Op.getValueType();
3088 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3091 // Now we know we're dealing with FP values.
3092 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3093 assert(LHS.getValueType() == RHS.getValueType());
3094 EVT VT = Op.getValueType();
3096 // Try to match this select into a max/min operation, which have dedicated
3097 // opcode in the instruction set.
3098 // NOTE: This is not correct in the presence of NaNs, so we only enable this
3100 if (getTargetMachine().Options.NoNaNsFPMath) {
3101 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3102 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3103 CC = ISD::getSetCCSwappedOperands(CC);
3104 std::swap(TVal, FVal);
3107 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3108 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3118 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3126 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3132 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3133 // and do the comparison.
3134 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3136 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3137 // clean. Some of them require two CSELs to implement.
3138 ARM64CC::CondCode CC1, CC2;
3139 changeFPCCToARM64CC(CC, CC1, CC2);
3140 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3141 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3143 // If we need a second CSEL, emit it, using the output of the first as the
3144 // RHS. We're effectively OR'ing the two CC's together.
3145 if (CC2 != ARM64CC::AL) {
3146 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3147 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3150 // Otherwise, return the output of the first CSEL.
3154 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3155 SelectionDAG &DAG) const {
3156 // Jump table entries as PC relative offsets. No additional tweaking
3157 // is necessary here. Just get the address of the jump table.
3158 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3159 EVT PtrVT = getPointerTy();
3162 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3163 !Subtarget->isTargetMachO()) {
3164 const unsigned char MO_NC = ARM64II::MO_NC;
3166 ARM64ISD::WrapperLarge, DL, PtrVT,
3167 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G3),
3168 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G2 | MO_NC),
3169 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G1 | MO_NC),
3170 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G0 | MO_NC));
3173 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3174 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3175 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3176 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3177 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3180 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3181 SelectionDAG &DAG) const {
3182 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3183 EVT PtrVT = getPointerTy();
3186 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3187 // Use the GOT for the large code model on iOS.
3188 if (Subtarget->isTargetMachO()) {
3189 SDValue GotAddr = DAG.getTargetConstantPool(
3190 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3192 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3195 const unsigned char MO_NC = ARM64II::MO_NC;
3197 ARM64ISD::WrapperLarge, DL, PtrVT,
3198 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3199 CP->getOffset(), ARM64II::MO_G3),
3200 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3201 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3202 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3203 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3204 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3205 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3207 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3208 // ELF, the only valid one on Darwin.
3210 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3211 CP->getOffset(), ARM64II::MO_PAGE);
3212 SDValue Lo = DAG.getTargetConstantPool(
3213 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3214 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3216 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3217 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3221 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3222 SelectionDAG &DAG) const {
3223 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3224 EVT PtrVT = getPointerTy();
3226 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3227 !Subtarget->isTargetMachO()) {
3228 const unsigned char MO_NC = ARM64II::MO_NC;
3230 ARM64ISD::WrapperLarge, DL, PtrVT,
3231 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3232 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3233 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3234 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3236 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3237 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3239 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3240 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3244 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3245 SelectionDAG &DAG) const {
3246 ARM64FunctionInfo *FuncInfo =
3247 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3251 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3252 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3253 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3254 MachinePointerInfo(SV), false, false, 0);
3257 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3258 SelectionDAG &DAG) const {
3259 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3260 // Standard, section B.3.
3261 MachineFunction &MF = DAG.getMachineFunction();
3262 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3265 SDValue Chain = Op.getOperand(0);
3266 SDValue VAList = Op.getOperand(1);
3267 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3268 SmallVector<SDValue, 4> MemOps;
3270 // void *__stack at offset 0
3272 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3273 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3274 MachinePointerInfo(SV), false, false, 8));
3276 // void *__gr_top at offset 8
3277 int GPRSize = FuncInfo->getVarArgsGPRSize();
3279 SDValue GRTop, GRTopAddr;
3281 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3282 DAG.getConstant(8, getPointerTy()));
3284 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3285 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3286 DAG.getConstant(GPRSize, getPointerTy()));
3288 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3289 MachinePointerInfo(SV, 8), false, false, 8));
3292 // void *__vr_top at offset 16
3293 int FPRSize = FuncInfo->getVarArgsFPRSize();
3295 SDValue VRTop, VRTopAddr;
3296 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3297 DAG.getConstant(16, getPointerTy()));
3299 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3300 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3301 DAG.getConstant(FPRSize, getPointerTy()));
3303 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3304 MachinePointerInfo(SV, 16), false, false, 8));
3307 // int __gr_offs at offset 24
3308 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3309 DAG.getConstant(24, getPointerTy()));
3310 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3311 GROffsAddr, MachinePointerInfo(SV, 24), false,
3314 // int __vr_offs at offset 28
3315 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3316 DAG.getConstant(28, getPointerTy()));
3317 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3318 VROffsAddr, MachinePointerInfo(SV, 28), false,
3321 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3324 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3325 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3326 : LowerAAPCS_VASTART(Op, DAG);
3329 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3330 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3332 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3333 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3334 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3336 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3337 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3338 8, false, false, MachinePointerInfo(DestSV),
3339 MachinePointerInfo(SrcSV));
3342 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3343 assert(Subtarget->isTargetDarwin() &&
3344 "automatic va_arg instruction only works on Darwin");
3346 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3347 EVT VT = Op.getValueType();
3349 SDValue Chain = Op.getOperand(0);
3350 SDValue Addr = Op.getOperand(1);
3351 unsigned Align = Op.getConstantOperandVal(3);
3353 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3354 MachinePointerInfo(V), false, false, false, 0);
3355 Chain = VAList.getValue(1);
3358 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3359 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3360 DAG.getConstant(Align - 1, getPointerTy()));
3361 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3362 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3365 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3366 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3368 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3369 // up to 64 bits. At the very least, we have to increase the striding of the
3370 // vaargs list to match this, and for FP values we need to introduce
3371 // FP_ROUND nodes as well.
3372 if (VT.isInteger() && !VT.isVector())
3374 bool NeedFPTrunc = false;
3375 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3380 // Increment the pointer, VAList, to the next vaarg
3381 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3382 DAG.getConstant(ArgSize, getPointerTy()));
3383 // Store the incremented VAList to the legalized pointer
3384 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3387 // Load the actual argument out of the pointer VAList
3389 // Load the value as an f64.
3390 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3391 MachinePointerInfo(), false, false, false, 0);
3392 // Round the value down to an f32.
3393 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3394 DAG.getIntPtrConstant(1));
3395 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3396 // Merge the rounded value with the chain output of the load.
3397 return DAG.getMergeValues(Ops, DL);
3400 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3404 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3405 SelectionDAG &DAG) const {
3406 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3407 MFI->setFrameAddressIsTaken(true);
3409 EVT VT = Op.getValueType();
3411 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3412 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3414 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3415 MachinePointerInfo(), false, false, false, 0);
3419 // FIXME? Maybe this could be a TableGen attribute on some registers and
3420 // this table could be generated automatically from RegInfo.
3421 unsigned ARM64TargetLowering::getRegisterByName(const char* RegName) const {
3422 unsigned Reg = StringSwitch<unsigned>(RegName)
3423 .Case("sp", ARM64::SP)
3427 report_fatal_error("Invalid register name global variable");
3430 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3431 SelectionDAG &DAG) const {
3432 MachineFunction &MF = DAG.getMachineFunction();
3433 MachineFrameInfo *MFI = MF.getFrameInfo();
3434 MFI->setReturnAddressIsTaken(true);
3436 EVT VT = Op.getValueType();
3438 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3440 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3441 SDValue Offset = DAG.getConstant(8, getPointerTy());
3442 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3443 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3444 MachinePointerInfo(), false, false, false, 0);
3447 // Return LR, which contains the return address. Mark it an implicit live-in.
3448 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3449 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3452 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3453 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3454 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3455 SelectionDAG &DAG) const {
3456 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3457 EVT VT = Op.getValueType();
3458 unsigned VTBits = VT.getSizeInBits();
3460 SDValue ShOpLo = Op.getOperand(0);
3461 SDValue ShOpHi = Op.getOperand(1);
3462 SDValue ShAmt = Op.getOperand(2);
3464 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3466 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3468 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3469 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3470 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3471 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3472 DAG.getConstant(VTBits, MVT::i64));
3473 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3475 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3476 ISD::SETGE, dl, DAG);
3477 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3479 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3480 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3482 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3484 // ARM64 shifts larger than the register width are wrapped rather than
3485 // clamped, so we can't just emit "hi >> x".
3486 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3487 SDValue TrueValHi = Opc == ISD::SRA
3488 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3489 DAG.getConstant(VTBits - 1, MVT::i64))
3490 : DAG.getConstant(0, VT);
3492 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3494 SDValue Ops[2] = { Lo, Hi };
3495 return DAG.getMergeValues(Ops, dl);
3498 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3499 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3500 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3501 SelectionDAG &DAG) const {
3502 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3503 EVT VT = Op.getValueType();
3504 unsigned VTBits = VT.getSizeInBits();
3506 SDValue ShOpLo = Op.getOperand(0);
3507 SDValue ShOpHi = Op.getOperand(1);
3508 SDValue ShAmt = Op.getOperand(2);
3511 assert(Op.getOpcode() == ISD::SHL_PARTS);
3512 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3513 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3514 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3515 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3516 DAG.getConstant(VTBits, MVT::i64));
3517 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3518 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3520 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3522 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3523 ISD::SETGE, dl, DAG);
3524 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3525 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3527 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3528 // so we can't just emit "lo << a" if a is too big.
3529 SDValue TrueValLo = DAG.getConstant(0, VT);
3530 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3532 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3534 SDValue Ops[2] = { Lo, Hi };
3535 return DAG.getMergeValues(Ops, dl);
3539 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3540 // The ARM64 target doesn't support folding offsets into global addresses.
3544 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3545 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3546 // FIXME: We should be able to handle f128 as well with a clever lowering.
3547 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3551 return ARM64_AM::getFP64Imm(Imm) != -1;
3552 else if (VT == MVT::f32)
3553 return ARM64_AM::getFP32Imm(Imm) != -1;
3557 //===----------------------------------------------------------------------===//
3558 // ARM64 Optimization Hooks
3559 //===----------------------------------------------------------------------===//
3561 //===----------------------------------------------------------------------===//
3562 // ARM64 Inline Assembly Support
3563 //===----------------------------------------------------------------------===//
3565 // Table of Constraints
3566 // TODO: This is the current set of constraints supported by ARM for the
3567 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3569 // r - A general register
3570 // w - An FP/SIMD register of some size in the range v0-v31
3571 // x - An FP/SIMD register of some size in the range v0-v15
3572 // I - Constant that can be used with an ADD instruction
3573 // J - Constant that can be used with a SUB instruction
3574 // K - Constant that can be used with a 32-bit logical instruction
3575 // L - Constant that can be used with a 64-bit logical instruction
3576 // M - Constant that can be used as a 32-bit MOV immediate
3577 // N - Constant that can be used as a 64-bit MOV immediate
3578 // Q - A memory reference with base register and no offset
3579 // S - A symbolic address
3580 // Y - Floating point constant zero
3581 // Z - Integer constant zero
3583 // Note that general register operands will be output using their 64-bit x
3584 // register name, whatever the size of the variable, unless the asm operand
3585 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3586 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3589 /// getConstraintType - Given a constraint letter, return the type of
3590 /// constraint it is for this target.
3591 ARM64TargetLowering::ConstraintType
3592 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3593 if (Constraint.size() == 1) {
3594 switch (Constraint[0]) {
3601 return C_RegisterClass;
3602 // An address with a single base register. Due to the way we
3603 // currently handle addresses it is the same as 'r'.
3608 return TargetLowering::getConstraintType(Constraint);
3611 /// Examine constraint type and operand type and determine a weight value.
3612 /// This object must already have been set up with the operand type
3613 /// and the current alternative constraint selected.
3614 TargetLowering::ConstraintWeight
3615 ARM64TargetLowering::getSingleConstraintMatchWeight(
3616 AsmOperandInfo &info, const char *constraint) const {
3617 ConstraintWeight weight = CW_Invalid;
3618 Value *CallOperandVal = info.CallOperandVal;
3619 // If we don't have a value, we can't do a match,
3620 // but allow it at the lowest weight.
3621 if (!CallOperandVal)
3623 Type *type = CallOperandVal->getType();
3624 // Look at the constraint type.
3625 switch (*constraint) {
3627 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3631 if (type->isFloatingPointTy() || type->isVectorTy())
3632 weight = CW_Register;
3635 weight = CW_Constant;
3641 std::pair<unsigned, const TargetRegisterClass *>
3642 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3644 if (Constraint.size() == 1) {
3645 switch (Constraint[0]) {
3647 if (VT.getSizeInBits() == 64)
3648 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3649 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3652 return std::make_pair(0U, &ARM64::FPR32RegClass);
3653 if (VT.getSizeInBits() == 64)
3654 return std::make_pair(0U, &ARM64::FPR64RegClass);
3655 if (VT.getSizeInBits() == 128)
3656 return std::make_pair(0U, &ARM64::FPR128RegClass);
3658 // The instructions that this constraint is designed for can
3659 // only take 128-bit registers so just use that regclass.
3661 if (VT.getSizeInBits() == 128)
3662 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
3666 if (StringRef("{cc}").equals_lower(Constraint))
3667 return std::make_pair(unsigned(ARM64::NZCV), &ARM64::CCRRegClass);
3669 // Use the default implementation in TargetLowering to convert the register
3670 // constraint into a member of a register class.
3671 std::pair<unsigned, const TargetRegisterClass *> Res;
3672 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3674 // Not found as a standard register?
3676 unsigned Size = Constraint.size();
3677 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3678 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3679 const std::string Reg =
3680 std::string(&Constraint[2], &Constraint[Size - 1]);
3681 int RegNo = atoi(Reg.c_str());
3682 if (RegNo >= 0 && RegNo <= 31) {
3683 // v0 - v31 are aliases of q0 - q31.
3684 // By default we'll emit v0-v31 for this unless there's a modifier where
3685 // we'll emit the correct register as well.
3686 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
3687 Res.second = &ARM64::FPR128RegClass;
3695 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3696 /// vector. If it is invalid, don't add anything to Ops.
3697 void ARM64TargetLowering::LowerAsmOperandForConstraint(
3698 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3699 SelectionDAG &DAG) const {
3702 // Currently only support length 1 constraints.
3703 if (Constraint.length() != 1)
3706 char ConstraintLetter = Constraint[0];
3707 switch (ConstraintLetter) {
3711 // This set of constraints deal with valid constants for various instructions.
3712 // Validate and return a target constant for them if we can.
3714 // 'z' maps to xzr or wzr so it needs an input of 0.
3715 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3716 if (!C || C->getZExtValue() != 0)
3719 if (Op.getValueType() == MVT::i64)
3720 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
3722 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
3732 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3736 // Grab the value and do some validation.
3737 uint64_t CVal = C->getZExtValue();
3738 switch (ConstraintLetter) {
3739 // The I constraint applies only to simple ADD or SUB immediate operands:
3740 // i.e. 0 to 4095 with optional shift by 12
3741 // The J constraint applies only to ADD or SUB immediates that would be
3742 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
3743 // instruction [or vice versa], in other words -1 to -4095 with optional
3744 // left shift by 12.
3746 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
3750 uint64_t NVal = -C->getSExtValue();
3751 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
3755 // The K and L constraints apply *only* to logical immediates, including
3756 // what used to be the MOVI alias for ORR (though the MOVI alias has now
3757 // been removed and MOV should be used). So these constraints have to
3758 // distinguish between bit patterns that are valid 32-bit or 64-bit
3759 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
3760 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
3763 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3767 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3770 // The M and N constraints are a superset of K and L respectively, for use
3771 // with the MOV (immediate) alias. As well as the logical immediates they
3772 // also match 32 or 64-bit immediates that can be loaded either using a
3773 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
3774 // (M) or 64-bit 0x1234000000000000 (N) etc.
3775 // As a note some of this code is liberally stolen from the asm parser.
3777 if (!isUInt<32>(CVal))
3779 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3781 if ((CVal & 0xFFFF) == CVal)
3783 if ((CVal & 0xFFFF0000ULL) == CVal)
3785 uint64_t NCVal = ~(uint32_t)CVal;
3786 if ((NCVal & 0xFFFFULL) == NCVal)
3788 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3793 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3795 if ((CVal & 0xFFFFULL) == CVal)
3797 if ((CVal & 0xFFFF0000ULL) == CVal)
3799 if ((CVal & 0xFFFF00000000ULL) == CVal)
3801 if ((CVal & 0xFFFF000000000000ULL) == CVal)
3803 uint64_t NCVal = ~CVal;
3804 if ((NCVal & 0xFFFFULL) == NCVal)
3806 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3808 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
3810 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
3818 // All assembler immediates are 64-bit integers.
3819 Result = DAG.getTargetConstant(CVal, MVT::i64);
3823 if (Result.getNode()) {
3824 Ops.push_back(Result);
3828 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3831 //===----------------------------------------------------------------------===//
3832 // ARM64 Advanced SIMD Support
3833 //===----------------------------------------------------------------------===//
3835 /// WidenVector - Given a value in the V64 register class, produce the
3836 /// equivalent value in the V128 register class.
3837 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
3838 EVT VT = V64Reg.getValueType();
3839 unsigned NarrowSize = VT.getVectorNumElements();
3840 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3841 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
3844 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
3845 V64Reg, DAG.getConstant(0, MVT::i32));
3848 /// getExtFactor - Determine the adjustment factor for the position when
3849 /// generating an "extract from vector registers" instruction.
3850 static unsigned getExtFactor(SDValue &V) {
3851 EVT EltType = V.getValueType().getVectorElementType();
3852 return EltType.getSizeInBits() / 8;
3855 /// NarrowVector - Given a value in the V128 register class, produce the
3856 /// equivalent value in the V64 register class.
3857 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
3858 EVT VT = V128Reg.getValueType();
3859 unsigned WideSize = VT.getVectorNumElements();
3860 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3861 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
3864 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
3867 // Gather data to see if the operation can be modelled as a
3868 // shuffle in combination with VEXTs.
3869 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
3870 SelectionDAG &DAG) const {
3872 EVT VT = Op.getValueType();
3873 unsigned NumElts = VT.getVectorNumElements();
3875 SmallVector<SDValue, 2> SourceVecs;
3876 SmallVector<unsigned, 2> MinElts;
3877 SmallVector<unsigned, 2> MaxElts;
3879 for (unsigned i = 0; i < NumElts; ++i) {
3880 SDValue V = Op.getOperand(i);
3881 if (V.getOpcode() == ISD::UNDEF)
3883 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3884 // A shuffle can only come from building a vector from various
3885 // elements of other vectors.
3889 // Record this extraction against the appropriate vector if possible...
3890 SDValue SourceVec = V.getOperand(0);
3891 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3892 bool FoundSource = false;
3893 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3894 if (SourceVecs[j] == SourceVec) {
3895 if (MinElts[j] > EltNo)
3897 if (MaxElts[j] < EltNo)
3904 // Or record a new source if not...
3906 SourceVecs.push_back(SourceVec);
3907 MinElts.push_back(EltNo);
3908 MaxElts.push_back(EltNo);
3912 // Currently only do something sane when at most two source vectors
3914 if (SourceVecs.size() > 2)
3917 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3918 int VEXTOffsets[2] = { 0, 0 };
3920 // This loop extracts the usage patterns of the source vectors
3921 // and prepares appropriate SDValues for a shuffle if possible.
3922 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3923 if (SourceVecs[i].getValueType() == VT) {
3924 // No VEXT necessary
3925 ShuffleSrcs[i] = SourceVecs[i];
3928 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3929 // We can pad out the smaller vector for free, so if it's part of a
3931 ShuffleSrcs[i] = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, SourceVecs[i],
3932 DAG.getUNDEF(SourceVecs[i].getValueType()));
3936 // Don't attempt to extract subvectors from BUILD_VECTOR sources
3937 // that expand or trunc the original value.
3938 // TODO: We can try to bitcast and ANY_EXTEND the result but
3939 // we need to consider the cost of vector ANY_EXTEND, and the
3940 // legality of all the types.
3941 if (SourceVecs[i].getValueType().getVectorElementType() !=
3942 VT.getVectorElementType())
3945 // Since only 64-bit and 128-bit vectors are legal on ARM and
3946 // we've eliminated the other cases...
3947 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3948 "unexpected vector sizes in ReconstructShuffle");
3950 if (MaxElts[i] - MinElts[i] >= NumElts) {
3951 // Span too large for a VEXT to cope
3955 if (MinElts[i] >= NumElts) {
3956 // The extraction can just take the second half
3957 VEXTOffsets[i] = NumElts;
3959 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3960 DAG.getIntPtrConstant(NumElts));
3961 } else if (MaxElts[i] < NumElts) {
3962 // The extraction can just take the first half
3964 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3965 SourceVecs[i], DAG.getIntPtrConstant(0));
3967 // An actual VEXT is needed
3968 VEXTOffsets[i] = MinElts[i];
3969 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3970 SourceVecs[i], DAG.getIntPtrConstant(0));
3972 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3973 DAG.getIntPtrConstant(NumElts));
3974 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
3975 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
3976 DAG.getConstant(Imm, MVT::i32));
3980 SmallVector<int, 8> Mask;
3982 for (unsigned i = 0; i < NumElts; ++i) {
3983 SDValue Entry = Op.getOperand(i);
3984 if (Entry.getOpcode() == ISD::UNDEF) {
3989 SDValue ExtractVec = Entry.getOperand(0);
3991 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
3992 if (ExtractVec == SourceVecs[0]) {
3993 Mask.push_back(ExtractElt - VEXTOffsets[0]);
3995 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
3999 // Final check before we try to produce nonsense...
4000 if (isShuffleMaskLegal(Mask, VT))
4001 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4007 // check if an EXT instruction can handle the shuffle mask when the
4008 // vector sources of the shuffle are the same.
4009 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4010 unsigned NumElts = VT.getVectorNumElements();
4012 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4018 // If this is a VEXT shuffle, the immediate value is the index of the first
4019 // element. The other shuffle indices must be the successive elements after
4021 unsigned ExpectedElt = Imm;
4022 for (unsigned i = 1; i < NumElts; ++i) {
4023 // Increment the expected index. If it wraps around, just follow it
4024 // back to index zero and keep going.
4026 if (ExpectedElt == NumElts)
4030 continue; // ignore UNDEF indices
4031 if (ExpectedElt != static_cast<unsigned>(M[i]))
4038 // check if an EXT instruction can handle the shuffle mask when the
4039 // vector sources of the shuffle are different.
4040 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4042 // Look for the first non-undef element.
4043 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4044 [](int Elt) {return Elt >= 0;});
4046 // Benefit form APInt to handle overflow when calculating expected element.
4047 unsigned NumElts = VT.getVectorNumElements();
4048 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4049 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4050 // The following shuffle indices must be the successive elements after the
4051 // first real element.
4052 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4053 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4054 if (FirstWrongElt != M.end())
4057 // The index of an EXT is the first element if it is not UNDEF.
4058 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4059 // value of the first element.
4060 // E.g. <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4061 // <-1, -1, 0, 1, ...> is treated as <IDX, IDX+1, 0, 1, ...>. IDX is
4062 // equal to the ExpectedElt.
4063 Imm = (M[0] >= 0) ? static_cast<unsigned>(M[0]) : ExpectedElt.getZExtValue();
4065 // If no beginning UNDEFs, do swap when M[0] >= NumElts.
4066 if (M[0] >= 0 && Imm >= NumElts) {
4069 } else if (M[0] < 0) {
4070 // Only do swap when beginning UNDEFs more than the first real element,
4071 if (*FirstRealElt < FirstRealElt - M.begin())
4080 /// isREVMask - Check if a vector shuffle corresponds to a REV
4081 /// instruction with the specified blocksize. (The order of the elements
4082 /// within each block of the vector is reversed.)
4083 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4084 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4085 "Only possible block sizes for REV are: 16, 32, 64");
4087 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4091 unsigned NumElts = VT.getVectorNumElements();
4092 unsigned BlockElts = M[0] + 1;
4093 // If the first shuffle index is UNDEF, be optimistic.
4095 BlockElts = BlockSize / EltSz;
4097 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4100 for (unsigned i = 0; i < NumElts; ++i) {
4102 continue; // ignore UNDEF indices
4103 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4110 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4111 unsigned NumElts = VT.getVectorNumElements();
4112 WhichResult = (M[0] == 0 ? 0 : 1);
4113 unsigned Idx = WhichResult * NumElts / 2;
4114 for (unsigned i = 0; i != NumElts; i += 2) {
4115 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4116 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4124 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4125 unsigned NumElts = VT.getVectorNumElements();
4126 WhichResult = (M[0] == 0 ? 0 : 1);
4127 for (unsigned i = 0; i != NumElts; ++i) {
4129 continue; // ignore UNDEF indices
4130 if ((unsigned)M[i] != 2 * i + WhichResult)
4137 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4138 unsigned NumElts = VT.getVectorNumElements();
4139 WhichResult = (M[0] == 0 ? 0 : 1);
4140 for (unsigned i = 0; i < NumElts; i += 2) {
4141 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4142 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4148 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4149 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4150 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4151 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4152 unsigned NumElts = VT.getVectorNumElements();
4153 WhichResult = (M[0] == 0 ? 0 : 1);
4154 unsigned Idx = WhichResult * NumElts / 2;
4155 for (unsigned i = 0; i != NumElts; i += 2) {
4156 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4157 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4165 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4166 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4167 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4168 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4169 unsigned Half = VT.getVectorNumElements() / 2;
4170 WhichResult = (M[0] == 0 ? 0 : 1);
4171 for (unsigned j = 0; j != 2; ++j) {
4172 unsigned Idx = WhichResult;
4173 for (unsigned i = 0; i != Half; ++i) {
4174 int MIdx = M[i + j * Half];
4175 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4184 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4185 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4186 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4187 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4188 unsigned NumElts = VT.getVectorNumElements();
4189 WhichResult = (M[0] == 0 ? 0 : 1);
4190 for (unsigned i = 0; i < NumElts; i += 2) {
4191 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4192 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4198 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4199 bool &DstIsLeft, int &Anomaly) {
4200 if (M.size() != static_cast<size_t>(NumInputElements))
4203 int NumLHSMatch = 0, NumRHSMatch = 0;
4204 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4206 for (int i = 0; i < NumInputElements; ++i) {
4216 LastLHSMismatch = i;
4218 if (M[i] == i + NumInputElements)
4221 LastRHSMismatch = i;
4224 if (NumLHSMatch == NumInputElements - 1) {
4226 Anomaly = LastLHSMismatch;
4228 } else if (NumRHSMatch == NumInputElements - 1) {
4230 Anomaly = LastRHSMismatch;
4237 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4238 if (VT.getSizeInBits() != 128)
4241 unsigned NumElts = VT.getVectorNumElements();
4243 for (int I = 0, E = NumElts / 2; I != E; I++) {
4248 int Offset = NumElts / 2;
4249 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4250 if (Mask[I] != I + SplitLHS * Offset)
4257 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4259 EVT VT = Op.getValueType();
4260 SDValue V0 = Op.getOperand(0);
4261 SDValue V1 = Op.getOperand(1);
4262 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4264 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4265 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4268 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4270 if (!isConcatMask(Mask, VT, SplitV0))
4273 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4274 VT.getVectorNumElements() / 2);
4276 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4277 DAG.getConstant(0, MVT::i64));
4279 if (V1.getValueType().getSizeInBits() == 128) {
4280 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4281 DAG.getConstant(0, MVT::i64));
4283 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4286 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4287 /// the specified operations to build the shuffle.
4288 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4289 SDValue RHS, SelectionDAG &DAG,
4291 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4292 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4293 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4296 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4305 OP_VUZPL, // VUZP, left result
4306 OP_VUZPR, // VUZP, right result
4307 OP_VZIPL, // VZIP, left result
4308 OP_VZIPR, // VZIP, right result
4309 OP_VTRNL, // VTRN, left result
4310 OP_VTRNR // VTRN, right result
4313 if (OpNum == OP_COPY) {
4314 if (LHSID == (1 * 9 + 2) * 9 + 3)
4316 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4320 SDValue OpLHS, OpRHS;
4321 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4322 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4323 EVT VT = OpLHS.getValueType();
4327 llvm_unreachable("Unknown shuffle opcode!");
4329 // VREV divides the vector in half and swaps within the half.
4330 if (VT.getVectorElementType() == MVT::i32 ||
4331 VT.getVectorElementType() == MVT::f32)
4332 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4333 // vrev <4 x i16> -> REV32
4334 if (VT.getVectorElementType() == MVT::i16)
4335 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4336 // vrev <4 x i8> -> REV16
4337 assert(VT.getVectorElementType() == MVT::i8);
4338 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4343 EVT EltTy = VT.getVectorElementType();
4345 if (EltTy == MVT::i8)
4346 Opcode = ARM64ISD::DUPLANE8;
4347 else if (EltTy == MVT::i16)
4348 Opcode = ARM64ISD::DUPLANE16;
4349 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4350 Opcode = ARM64ISD::DUPLANE32;
4351 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4352 Opcode = ARM64ISD::DUPLANE64;
4354 llvm_unreachable("Invalid vector element type?");
4356 if (VT.getSizeInBits() == 64)
4357 OpLHS = WidenVector(OpLHS, DAG);
4358 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4359 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4364 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4365 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4366 DAG.getConstant(Imm, MVT::i32));
4369 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4371 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4373 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4375 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4377 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4379 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4383 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4384 SelectionDAG &DAG) {
4385 // Check to see if we can use the TBL instruction.
4386 SDValue V1 = Op.getOperand(0);
4387 SDValue V2 = Op.getOperand(1);
4390 EVT EltVT = Op.getValueType().getVectorElementType();
4391 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4393 SmallVector<SDValue, 8> TBLMask;
4394 for (int Val : ShuffleMask) {
4395 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4396 unsigned Offset = Byte + Val * BytesPerElt;
4397 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4401 MVT IndexVT = MVT::v8i8;
4402 unsigned IndexLen = 8;
4403 if (Op.getValueType().getSizeInBits() == 128) {
4404 IndexVT = MVT::v16i8;
4408 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4409 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4412 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4414 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4415 Shuffle = DAG.getNode(
4416 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4417 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4418 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4419 makeArrayRef(TBLMask.data(), IndexLen)));
4421 if (IndexLen == 8) {
4422 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4423 Shuffle = DAG.getNode(
4424 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4425 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4426 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4427 makeArrayRef(TBLMask.data(), IndexLen)));
4429 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4430 // cannot currently represent the register constraints on the input
4432 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4433 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4434 // &TBLMask[0], IndexLen));
4435 Shuffle = DAG.getNode(
4436 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4437 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4438 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4439 makeArrayRef(TBLMask.data(), IndexLen)));
4442 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4445 static unsigned getDUPLANEOp(EVT EltType) {
4446 if (EltType == MVT::i8)
4447 return ARM64ISD::DUPLANE8;
4448 if (EltType == MVT::i16)
4449 return ARM64ISD::DUPLANE16;
4450 if (EltType == MVT::i32 || EltType == MVT::f32)
4451 return ARM64ISD::DUPLANE32;
4452 if (EltType == MVT::i64 || EltType == MVT::f64)
4453 return ARM64ISD::DUPLANE64;
4455 llvm_unreachable("Invalid vector element type?");
4458 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4459 SelectionDAG &DAG) const {
4461 EVT VT = Op.getValueType();
4463 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4465 // Convert shuffles that are directly supported on NEON to target-specific
4466 // DAG nodes, instead of keeping them as shuffles and matching them again
4467 // during code selection. This is more efficient and avoids the possibility
4468 // of inconsistencies between legalization and selection.
4469 ArrayRef<int> ShuffleMask = SVN->getMask();
4471 SDValue V1 = Op.getOperand(0);
4472 SDValue V2 = Op.getOperand(1);
4474 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4475 V1.getValueType().getSimpleVT())) {
4476 int Lane = SVN->getSplatIndex();
4477 // If this is undef splat, generate it via "just" vdup, if possible.
4481 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4482 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4484 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4485 // constant. If so, we can just reference the lane's definition directly.
4486 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4487 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4488 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4490 // Otherwise, duplicate from the lane of the input vector.
4491 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4493 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4494 // to make a vector of the same size as this SHUFFLE. We can ignore the
4495 // extract entirely, and canonicalise the concat using WidenVector.
4496 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4497 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4498 V1 = V1.getOperand(0);
4499 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4500 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4501 Lane -= Idx * VT.getVectorNumElements() / 2;
4502 V1 = WidenVector(V1.getOperand(Idx), DAG);
4503 } else if (VT.getSizeInBits() == 64)
4504 V1 = WidenVector(V1, DAG);
4506 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4509 if (isREVMask(ShuffleMask, VT, 64))
4510 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4511 if (isREVMask(ShuffleMask, VT, 32))
4512 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4513 if (isREVMask(ShuffleMask, VT, 16))
4514 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4516 bool ReverseEXT = false;
4518 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4521 Imm *= getExtFactor(V1);
4522 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4523 DAG.getConstant(Imm, MVT::i32));
4524 } else if (V2->getOpcode() == ISD::UNDEF &&
4525 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4526 Imm *= getExtFactor(V1);
4527 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4528 DAG.getConstant(Imm, MVT::i32));
4531 unsigned WhichResult;
4532 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4533 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4534 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4536 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4537 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4538 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4540 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4541 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4542 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4545 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4546 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4547 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4549 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4550 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4551 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4553 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4554 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4555 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4558 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4559 if (Concat.getNode())
4564 int NumInputElements = V1.getValueType().getVectorNumElements();
4565 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4566 SDValue DstVec = DstIsLeft ? V1 : V2;
4567 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4569 SDValue SrcVec = V1;
4570 int SrcLane = ShuffleMask[Anomaly];
4571 if (SrcLane >= NumInputElements) {
4573 SrcLane -= VT.getVectorNumElements();
4575 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4577 EVT ScalarVT = VT.getVectorElementType();
4578 if (ScalarVT.getSizeInBits() < 32)
4579 ScalarVT = MVT::i32;
4582 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4583 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4587 // If the shuffle is not directly supported and it has 4 elements, use
4588 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4589 unsigned NumElts = VT.getVectorNumElements();
4591 unsigned PFIndexes[4];
4592 for (unsigned i = 0; i != 4; ++i) {
4593 if (ShuffleMask[i] < 0)
4596 PFIndexes[i] = ShuffleMask[i];
4599 // Compute the index in the perfect shuffle table.
4600 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4601 PFIndexes[2] * 9 + PFIndexes[3];
4602 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4603 unsigned Cost = (PFEntry >> 30);
4606 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4609 return GenerateTBL(Op, ShuffleMask, DAG);
4612 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4614 EVT VT = BVN->getValueType(0);
4615 APInt SplatBits, SplatUndef;
4616 unsigned SplatBitSize;
4618 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4619 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4621 for (unsigned i = 0; i < NumSplats; ++i) {
4622 CnstBits <<= SplatBitSize;
4623 UndefBits <<= SplatBitSize;
4624 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4625 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4634 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4635 SelectionDAG &DAG) const {
4636 BuildVectorSDNode *BVN =
4637 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4638 SDValue LHS = Op.getOperand(0);
4640 EVT VT = Op.getValueType();
4645 APInt CnstBits(VT.getSizeInBits(), 0);
4646 APInt UndefBits(VT.getSizeInBits(), 0);
4647 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4648 // We only have BIC vector immediate instruction, which is and-not.
4649 CnstBits = ~CnstBits;
4651 // We make use of a little bit of goto ickiness in order to avoid having to
4652 // duplicate the immediate matching logic for the undef toggled case.
4653 bool SecondTry = false;
4656 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4657 CnstBits = CnstBits.zextOrTrunc(64);
4658 uint64_t CnstVal = CnstBits.getZExtValue();
4660 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4661 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4662 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4663 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4664 DAG.getConstant(CnstVal, MVT::i32),
4665 DAG.getConstant(0, MVT::i32));
4666 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4669 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4670 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4671 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4672 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4673 DAG.getConstant(CnstVal, MVT::i32),
4674 DAG.getConstant(8, MVT::i32));
4675 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4678 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4679 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4680 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4681 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4682 DAG.getConstant(CnstVal, MVT::i32),
4683 DAG.getConstant(16, MVT::i32));
4684 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4687 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4688 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4689 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4690 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4691 DAG.getConstant(CnstVal, MVT::i32),
4692 DAG.getConstant(24, MVT::i32));
4693 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4696 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4697 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4698 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4699 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4700 DAG.getConstant(CnstVal, MVT::i32),
4701 DAG.getConstant(0, MVT::i32));
4702 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4705 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4706 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4707 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4708 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4709 DAG.getConstant(CnstVal, MVT::i32),
4710 DAG.getConstant(8, MVT::i32));
4711 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4718 CnstBits = ~UndefBits;
4722 // We can always fall back to a non-immediate AND.
4727 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4728 // consists of only the same constant int value, returned in reference arg
4730 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4731 uint64_t &ConstVal) {
4732 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4735 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4738 EVT VT = Bvec->getValueType(0);
4739 unsigned NumElts = VT.getVectorNumElements();
4740 for (unsigned i = 1; i < NumElts; ++i)
4741 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4743 ConstVal = FirstElt->getZExtValue();
4747 static unsigned getIntrinsicID(const SDNode *N) {
4748 unsigned Opcode = N->getOpcode();
4751 return Intrinsic::not_intrinsic;
4752 case ISD::INTRINSIC_WO_CHAIN: {
4753 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4754 if (IID < Intrinsic::num_intrinsics)
4756 return Intrinsic::not_intrinsic;
4761 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4762 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4763 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4764 // Also, logical shift right -> sri, with the same structure.
4765 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4766 EVT VT = N->getValueType(0);
4773 // Is the first op an AND?
4774 const SDValue And = N->getOperand(0);
4775 if (And.getOpcode() != ISD::AND)
4778 // Is the second op an shl or lshr?
4779 SDValue Shift = N->getOperand(1);
4780 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4781 // or ARM64ISD::VLSHR vector, #shift
4782 unsigned ShiftOpc = Shift.getOpcode();
4783 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4785 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4787 // Is the shift amount constant?
4788 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4792 // Is the and mask vector all constant?
4794 if (!isAllConstantBuildVector(And.getOperand(1), C1))
4797 // Is C1 == ~C2, taking into account how much one can shift elements of a
4799 uint64_t C2 = C2node->getZExtValue();
4800 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4801 if (C2 > ElemSizeInBits)
4803 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4804 if ((C1 & ElemMask) != (~C2 & ElemMask))
4807 SDValue X = And.getOperand(0);
4808 SDValue Y = Shift.getOperand(0);
4811 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4813 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4814 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4816 DEBUG(dbgs() << "arm64-lower: transformed: \n");
4817 DEBUG(N->dump(&DAG));
4818 DEBUG(dbgs() << "into: \n");
4819 DEBUG(ResultSLI->dump(&DAG));
4825 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4826 SelectionDAG &DAG) const {
4827 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4828 if (EnableARM64SlrGeneration) {
4829 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4834 BuildVectorSDNode *BVN =
4835 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4836 SDValue LHS = Op.getOperand(1);
4838 EVT VT = Op.getValueType();
4840 // OR commutes, so try swapping the operands.
4842 LHS = Op.getOperand(0);
4843 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4848 APInt CnstBits(VT.getSizeInBits(), 0);
4849 APInt UndefBits(VT.getSizeInBits(), 0);
4850 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4851 // We make use of a little bit of goto ickiness in order to avoid having to
4852 // duplicate the immediate matching logic for the undef toggled case.
4853 bool SecondTry = false;
4856 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4857 CnstBits = CnstBits.zextOrTrunc(64);
4858 uint64_t CnstVal = CnstBits.getZExtValue();
4860 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4861 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4862 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4863 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4864 DAG.getConstant(CnstVal, MVT::i32),
4865 DAG.getConstant(0, MVT::i32));
4866 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4869 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4870 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4871 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4872 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4873 DAG.getConstant(CnstVal, MVT::i32),
4874 DAG.getConstant(8, MVT::i32));
4875 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4878 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4879 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4880 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4881 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4882 DAG.getConstant(CnstVal, MVT::i32),
4883 DAG.getConstant(16, MVT::i32));
4884 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4887 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4888 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4889 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4890 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4891 DAG.getConstant(CnstVal, MVT::i32),
4892 DAG.getConstant(24, MVT::i32));
4893 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4896 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4897 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4898 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4899 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4900 DAG.getConstant(CnstVal, MVT::i32),
4901 DAG.getConstant(0, MVT::i32));
4902 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4905 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4906 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4907 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4908 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4909 DAG.getConstant(CnstVal, MVT::i32),
4910 DAG.getConstant(8, MVT::i32));
4911 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4918 CnstBits = UndefBits;
4922 // We can always fall back to a non-immediate OR.
4927 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4928 SelectionDAG &DAG) const {
4929 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4931 EVT VT = Op.getValueType();
4933 APInt CnstBits(VT.getSizeInBits(), 0);
4934 APInt UndefBits(VT.getSizeInBits(), 0);
4935 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4936 // We make use of a little bit of goto ickiness in order to avoid having to
4937 // duplicate the immediate matching logic for the undef toggled case.
4938 bool SecondTry = false;
4941 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4942 CnstBits = CnstBits.zextOrTrunc(64);
4943 uint64_t CnstVal = CnstBits.getZExtValue();
4945 // Certain magic vector constants (used to express things like NOT
4946 // and NEG) are passed through unmodified. This allows codegen patterns
4947 // for these operations to match. Special-purpose patterns will lower
4948 // these immediates to MOVIs if it proves necessary.
4949 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4952 // The many faces of MOVI...
4953 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4954 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4955 if (VT.getSizeInBits() == 128) {
4956 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4957 DAG.getConstant(CnstVal, MVT::i32));
4958 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4961 // Support the V64 version via subregister insertion.
4962 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4963 DAG.getConstant(CnstVal, MVT::i32));
4964 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4967 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4968 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4969 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4970 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4971 DAG.getConstant(CnstVal, MVT::i32),
4972 DAG.getConstant(0, MVT::i32));
4973 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4976 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4977 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4978 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4979 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4980 DAG.getConstant(CnstVal, MVT::i32),
4981 DAG.getConstant(8, MVT::i32));
4982 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4985 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4986 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4987 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4988 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4989 DAG.getConstant(CnstVal, MVT::i32),
4990 DAG.getConstant(16, MVT::i32));
4991 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4994 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4995 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4996 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4997 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4998 DAG.getConstant(CnstVal, MVT::i32),
4999 DAG.getConstant(24, MVT::i32));
5000 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5003 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5004 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5005 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5006 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5007 DAG.getConstant(CnstVal, MVT::i32),
5008 DAG.getConstant(0, MVT::i32));
5009 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5012 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5013 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5014 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5015 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5016 DAG.getConstant(CnstVal, MVT::i32),
5017 DAG.getConstant(8, MVT::i32));
5018 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5021 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5022 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5023 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5024 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5025 DAG.getConstant(CnstVal, MVT::i32),
5026 DAG.getConstant(264, MVT::i32));
5027 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5030 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5031 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5032 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5033 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5034 DAG.getConstant(CnstVal, MVT::i32),
5035 DAG.getConstant(272, MVT::i32));
5036 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5039 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
5040 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
5041 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5042 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
5043 DAG.getConstant(CnstVal, MVT::i32));
5044 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5047 // The few faces of FMOV...
5048 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
5049 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
5050 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5051 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
5052 DAG.getConstant(CnstVal, MVT::i32));
5053 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5056 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
5057 VT.getSizeInBits() == 128) {
5058 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
5059 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
5060 DAG.getConstant(CnstVal, MVT::i32));
5061 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5064 // The many faces of MVNI...
5066 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5067 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5068 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5069 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5070 DAG.getConstant(CnstVal, MVT::i32),
5071 DAG.getConstant(0, MVT::i32));
5072 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5075 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5076 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5077 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5078 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5079 DAG.getConstant(CnstVal, MVT::i32),
5080 DAG.getConstant(8, MVT::i32));
5081 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5084 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5085 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5086 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5087 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5088 DAG.getConstant(CnstVal, MVT::i32),
5089 DAG.getConstant(16, MVT::i32));
5090 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5093 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5094 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5095 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5096 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5097 DAG.getConstant(CnstVal, MVT::i32),
5098 DAG.getConstant(24, MVT::i32));
5099 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5102 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5103 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5104 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5105 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5106 DAG.getConstant(CnstVal, MVT::i32),
5107 DAG.getConstant(0, MVT::i32));
5108 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5111 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5112 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5113 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5114 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5115 DAG.getConstant(CnstVal, MVT::i32),
5116 DAG.getConstant(8, MVT::i32));
5117 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5120 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5121 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5122 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5123 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5124 DAG.getConstant(CnstVal, MVT::i32),
5125 DAG.getConstant(264, MVT::i32));
5126 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5129 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5130 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5131 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5132 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5133 DAG.getConstant(CnstVal, MVT::i32),
5134 DAG.getConstant(272, MVT::i32));
5135 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5142 CnstBits = UndefBits;
5147 // Scan through the operands to find some interesting properties we can
5149 // 1) If only one value is used, we can use a DUP, or
5150 // 2) if only the low element is not undef, we can just insert that, or
5151 // 3) if only one constant value is used (w/ some non-constant lanes),
5152 // we can splat the constant value into the whole vector then fill
5153 // in the non-constant lanes.
5154 // 4) FIXME: If different constant values are used, but we can intelligently
5155 // select the values we'll be overwriting for the non-constant
5156 // lanes such that we can directly materialize the vector
5157 // some other way (MOVI, e.g.), we can be sneaky.
5158 unsigned NumElts = VT.getVectorNumElements();
5159 bool isOnlyLowElement = true;
5160 bool usesOnlyOneValue = true;
5161 bool usesOnlyOneConstantValue = true;
5162 bool isConstant = true;
5163 unsigned NumConstantLanes = 0;
5165 SDValue ConstantValue;
5166 for (unsigned i = 0; i < NumElts; ++i) {
5167 SDValue V = Op.getOperand(i);
5168 if (V.getOpcode() == ISD::UNDEF)
5171 isOnlyLowElement = false;
5172 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5175 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5177 if (!ConstantValue.getNode())
5179 else if (ConstantValue != V)
5180 usesOnlyOneConstantValue = false;
5183 if (!Value.getNode())
5185 else if (V != Value)
5186 usesOnlyOneValue = false;
5189 if (!Value.getNode())
5190 return DAG.getUNDEF(VT);
5192 if (isOnlyLowElement)
5193 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5195 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5196 // i32 and try again.
5197 if (usesOnlyOneValue) {
5199 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5200 Value.getValueType() != VT)
5201 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5203 // This is actually a DUPLANExx operation, which keeps everything vectory.
5205 // DUPLANE works on 128-bit vectors, widen it if necessary.
5206 SDValue Lane = Value.getOperand(1);
5207 Value = Value.getOperand(0);
5208 if (Value.getValueType().getSizeInBits() == 64)
5209 Value = WidenVector(Value, DAG);
5211 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5212 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5215 if (VT.getVectorElementType().isFloatingPoint()) {
5216 SmallVector<SDValue, 8> Ops;
5218 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5219 for (unsigned i = 0; i < NumElts; ++i)
5220 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5221 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5222 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5223 Val = LowerBUILD_VECTOR(Val, DAG);
5225 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5229 // If there was only one constant value used and for more than one lane,
5230 // start by splatting that value, then replace the non-constant lanes. This
5231 // is better than the default, which will perform a separate initialization
5233 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5234 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5235 // Now insert the non-constant lanes.
5236 for (unsigned i = 0; i < NumElts; ++i) {
5237 SDValue V = Op.getOperand(i);
5238 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5239 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5240 // Note that type legalization likely mucked about with the VT of the
5241 // source operand, so we may have to convert it here before inserting.
5242 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5248 // If all elements are constants and the case above didn't get hit, fall back
5249 // to the default expansion, which will generate a load from the constant
5254 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5256 SDValue shuffle = ReconstructShuffle(Op, DAG);
5257 if (shuffle != SDValue())
5261 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5262 // know the default expansion would otherwise fall back on something even
5263 // worse. For a vector with one or two non-undef values, that's
5264 // scalar_to_vector for the elements followed by a shuffle (provided the
5265 // shuffle is valid for the target) and materialization element by element
5266 // on the stack followed by a load for everything else.
5267 if (!isConstant && !usesOnlyOneValue) {
5268 SDValue Vec = DAG.getUNDEF(VT);
5269 SDValue Op0 = Op.getOperand(0);
5270 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5272 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5273 // a) Avoid a RMW dependency on the full vector register, and
5274 // b) Allow the register coalescer to fold away the copy if the
5275 // value is already in an S or D register.
5276 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5277 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5279 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5280 DAG.getTargetConstant(SubIdx, MVT::i32));
5281 Vec = SDValue(N, 0);
5284 for (; i < NumElts; ++i) {
5285 SDValue V = Op.getOperand(i);
5286 if (V.getOpcode() == ISD::UNDEF)
5288 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5289 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5294 // Just use the default expansion. We failed to find a better alternative.
5298 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5299 SelectionDAG &DAG) const {
5300 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5302 // Check for non-constant lane.
5303 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5306 EVT VT = Op.getOperand(0).getValueType();
5308 // Insertion/extraction are legal for V128 types.
5309 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5310 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5313 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5314 VT != MVT::v1i64 && VT != MVT::v2f32)
5317 // For V64 types, we perform insertion by expanding the value
5318 // to a V128 type and perform the insertion on that.
5320 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5321 EVT WideTy = WideVec.getValueType();
5323 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5324 Op.getOperand(1), Op.getOperand(2));
5325 // Re-narrow the resultant vector.
5326 return NarrowVector(Node, DAG);
5329 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5330 SelectionDAG &DAG) const {
5331 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5333 // Check for non-constant lane.
5334 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5337 EVT VT = Op.getOperand(0).getValueType();
5339 // Insertion/extraction are legal for V128 types.
5340 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5341 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5344 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5345 VT != MVT::v1i64 && VT != MVT::v2f32)
5348 // For V64 types, we perform extraction by expanding the value
5349 // to a V128 type and perform the extraction on that.
5351 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5352 EVT WideTy = WideVec.getValueType();
5354 EVT ExtrTy = WideTy.getVectorElementType();
5355 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5358 // For extractions, we just return the result directly.
5359 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5363 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5364 SelectionDAG &DAG) const {
5365 EVT VT = Op.getOperand(0).getValueType();
5371 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5374 unsigned Val = Cst->getZExtValue();
5376 unsigned Size = Op.getValueType().getSizeInBits();
5380 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5383 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5386 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5389 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5392 llvm_unreachable("Unexpected vector type in extract_subvector!");
5395 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5397 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5403 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5405 if (VT.getVectorNumElements() == 4 &&
5406 (VT.is128BitVector() || VT.is64BitVector())) {
5407 unsigned PFIndexes[4];
5408 for (unsigned i = 0; i != 4; ++i) {
5412 PFIndexes[i] = M[i];
5415 // Compute the index in the perfect shuffle table.
5416 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5417 PFIndexes[2] * 9 + PFIndexes[3];
5418 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5419 unsigned Cost = (PFEntry >> 30);
5427 unsigned DummyUnsigned;
5429 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5430 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5431 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5432 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5433 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5434 isZIPMask(M, VT, DummyUnsigned) ||
5435 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5436 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5437 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5438 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5439 isConcatMask(M, VT, VT.getSizeInBits() == 128));
5442 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5443 /// operand of a vector shift operation, where all the elements of the
5444 /// build_vector must have the same constant integer value.
5445 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5446 // Ignore bit_converts.
5447 while (Op.getOpcode() == ISD::BITCAST)
5448 Op = Op.getOperand(0);
5449 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5450 APInt SplatBits, SplatUndef;
5451 unsigned SplatBitSize;
5453 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5454 HasAnyUndefs, ElementBits) ||
5455 SplatBitSize > ElementBits)
5457 Cnt = SplatBits.getSExtValue();
5461 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5462 /// operand of a vector shift left operation. That value must be in the range:
5463 /// 0 <= Value < ElementBits for a left shift; or
5464 /// 0 <= Value <= ElementBits for a long left shift.
5465 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5466 assert(VT.isVector() && "vector shift count is not a vector type");
5467 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5468 if (!getVShiftImm(Op, ElementBits, Cnt))
5470 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5473 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5474 /// operand of a vector shift right operation. For a shift opcode, the value
5475 /// is positive, but for an intrinsic the value count must be negative. The
5476 /// absolute value must be in the range:
5477 /// 1 <= |Value| <= ElementBits for a right shift; or
5478 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5479 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5481 assert(VT.isVector() && "vector shift count is not a vector type");
5482 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5483 if (!getVShiftImm(Op, ElementBits, Cnt))
5487 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5490 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5491 SelectionDAG &DAG) const {
5492 EVT VT = Op.getValueType();
5496 if (!Op.getOperand(1).getValueType().isVector())
5498 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5500 switch (Op.getOpcode()) {
5502 llvm_unreachable("unexpected shift opcode");
5505 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5506 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5507 DAG.getConstant(Cnt, MVT::i32));
5508 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5509 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5510 Op.getOperand(0), Op.getOperand(1));
5513 // Right shift immediate
5514 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5517 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5518 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5519 DAG.getConstant(Cnt, MVT::i32));
5522 // Right shift register. Note, there is not a shift right register
5523 // instruction, but the shift left register instruction takes a signed
5524 // value, where negative numbers specify a right shift.
5525 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5526 : Intrinsic::arm64_neon_ushl;
5527 // negate the shift amount
5528 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5529 SDValue NegShiftLeft =
5530 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5531 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5532 return NegShiftLeft;
5538 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5539 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5540 SDLoc dl, SelectionDAG &DAG) {
5541 EVT SrcVT = LHS.getValueType();
5543 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5544 APInt CnstBits(VT.getSizeInBits(), 0);
5545 APInt UndefBits(VT.getSizeInBits(), 0);
5546 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5547 bool IsZero = IsCnst && (CnstBits == 0);
5549 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5556 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5558 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5559 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5563 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5564 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5567 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5568 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5571 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5572 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5575 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5576 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5580 // If we ignore NaNs then we can use to the MI implementation.
5584 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5585 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5595 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5597 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5598 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5602 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5603 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5606 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5607 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5610 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5611 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5614 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5615 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5617 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5619 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5622 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5623 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5625 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5627 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5631 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5632 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5633 SDValue LHS = Op.getOperand(0);
5634 SDValue RHS = Op.getOperand(1);
5637 if (LHS.getValueType().getVectorElementType().isInteger()) {
5638 assert(LHS.getValueType() == RHS.getValueType());
5639 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5640 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5644 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5645 LHS.getValueType().getVectorElementType() == MVT::f64);
5647 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5648 // clean. Some of them require two branches to implement.
5649 ARM64CC::CondCode CC1, CC2;
5651 changeVectorFPCCToARM64CC(CC, CC1, CC2, ShouldInvert);
5653 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5655 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5659 if (CC2 != ARM64CC::AL) {
5661 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5662 if (!Cmp2.getNode())
5665 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
5669 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
5674 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5675 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5676 /// specified in the intrinsic calls.
5677 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5679 unsigned Intrinsic) const {
5680 switch (Intrinsic) {
5681 case Intrinsic::arm64_neon_ld2:
5682 case Intrinsic::arm64_neon_ld3:
5683 case Intrinsic::arm64_neon_ld4:
5684 case Intrinsic::arm64_neon_ld2lane:
5685 case Intrinsic::arm64_neon_ld3lane:
5686 case Intrinsic::arm64_neon_ld4lane:
5687 case Intrinsic::arm64_neon_ld2r:
5688 case Intrinsic::arm64_neon_ld3r:
5689 case Intrinsic::arm64_neon_ld4r: {
5690 Info.opc = ISD::INTRINSIC_W_CHAIN;
5691 // Conservatively set memVT to the entire set of vectors loaded.
5692 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5693 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5694 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5697 Info.vol = false; // volatile loads with NEON intrinsics not supported
5698 Info.readMem = true;
5699 Info.writeMem = false;
5702 case Intrinsic::arm64_neon_st2:
5703 case Intrinsic::arm64_neon_st3:
5704 case Intrinsic::arm64_neon_st4:
5705 case Intrinsic::arm64_neon_st2lane:
5706 case Intrinsic::arm64_neon_st3lane:
5707 case Intrinsic::arm64_neon_st4lane: {
5708 Info.opc = ISD::INTRINSIC_VOID;
5709 // Conservatively set memVT to the entire set of vectors stored.
5710 unsigned NumElts = 0;
5711 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5712 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5713 if (!ArgTy->isVectorTy())
5715 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5717 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5718 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5721 Info.vol = false; // volatile stores with NEON intrinsics not supported
5722 Info.readMem = false;
5723 Info.writeMem = true;
5726 case Intrinsic::arm64_ldaxr:
5727 case Intrinsic::arm64_ldxr: {
5728 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5729 Info.opc = ISD::INTRINSIC_W_CHAIN;
5730 Info.memVT = MVT::getVT(PtrTy->getElementType());
5731 Info.ptrVal = I.getArgOperand(0);
5733 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5735 Info.readMem = true;
5736 Info.writeMem = false;
5739 case Intrinsic::arm64_stlxr:
5740 case Intrinsic::arm64_stxr: {
5741 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5742 Info.opc = ISD::INTRINSIC_W_CHAIN;
5743 Info.memVT = MVT::getVT(PtrTy->getElementType());
5744 Info.ptrVal = I.getArgOperand(1);
5746 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5748 Info.readMem = false;
5749 Info.writeMem = true;
5752 case Intrinsic::arm64_ldaxp:
5753 case Intrinsic::arm64_ldxp: {
5754 Info.opc = ISD::INTRINSIC_W_CHAIN;
5755 Info.memVT = MVT::i128;
5756 Info.ptrVal = I.getArgOperand(0);
5760 Info.readMem = true;
5761 Info.writeMem = false;
5764 case Intrinsic::arm64_stlxp:
5765 case Intrinsic::arm64_stxp: {
5766 Info.opc = ISD::INTRINSIC_W_CHAIN;
5767 Info.memVT = MVT::i128;
5768 Info.ptrVal = I.getArgOperand(2);
5772 Info.readMem = false;
5773 Info.writeMem = true;
5783 // Truncations from 64-bit GPR to 32-bit GPR is free.
5784 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5785 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5787 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5788 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5789 if (NumBits1 <= NumBits2)
5793 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5794 if (!VT1.isInteger() || !VT2.isInteger())
5796 unsigned NumBits1 = VT1.getSizeInBits();
5797 unsigned NumBits2 = VT2.getSizeInBits();
5798 if (NumBits1 <= NumBits2)
5803 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5805 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5806 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5808 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5809 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5810 if (NumBits1 == 32 && NumBits2 == 64)
5814 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5815 if (!VT1.isInteger() || !VT2.isInteger())
5817 unsigned NumBits1 = VT1.getSizeInBits();
5818 unsigned NumBits2 = VT2.getSizeInBits();
5819 if (NumBits1 == 32 && NumBits2 == 64)
5824 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5825 EVT VT1 = Val.getValueType();
5826 if (isZExtFree(VT1, VT2)) {
5830 if (Val.getOpcode() != ISD::LOAD)
5833 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5834 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5835 VT2.isInteger() && VT1.getSizeInBits() <= 32);
5838 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5839 unsigned &RequiredAligment) const {
5840 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5842 // Cyclone supports unaligned accesses.
5843 RequiredAligment = 0;
5844 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5845 return NumBits == 32 || NumBits == 64;
5848 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5849 unsigned &RequiredAligment) const {
5850 if (!LoadedType.isSimple() ||
5851 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5853 // Cyclone supports unaligned accesses.
5854 RequiredAligment = 0;
5855 unsigned NumBits = LoadedType.getSizeInBits();
5856 return NumBits == 32 || NumBits == 64;
5859 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5860 unsigned AlignCheck) {
5861 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5862 (DstAlign == 0 || DstAlign % AlignCheck == 0));
5865 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5866 unsigned SrcAlign, bool IsMemset,
5867 bool ZeroMemset, bool MemcpyStrSrc,
5868 MachineFunction &MF) const {
5869 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5870 // instruction to materialize the v2i64 zero and one store (with restrictive
5871 // addressing mode). Just do two i64 store of zero-registers.
5873 const Function *F = MF.getFunction();
5874 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
5875 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5876 Attribute::NoImplicitFloat) &&
5877 (memOpAlign(SrcAlign, DstAlign, 16) ||
5878 (allowsUnalignedMemoryAccesses(MVT::f128, 0, &Fast) && Fast)))
5881 return Size >= 8 ? MVT::i64 : MVT::i32;
5884 // 12-bit optionally shifted immediates are legal for adds.
5885 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5886 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5891 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5892 // immediates is the same as for an add or a sub.
5893 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5896 return isLegalAddImmediate(Immed);
5899 /// isLegalAddressingMode - Return true if the addressing mode represented
5900 /// by AM is legal for this target, for a load/store of the specified type.
5901 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5903 // ARM64 has five basic addressing modes:
5905 // reg + 9-bit signed offset
5906 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
5908 // reg + SIZE_IN_BYTES * reg
5910 // No global is ever allowed as a base.
5914 // No reg+reg+imm addressing.
5915 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5918 // check reg + imm case:
5919 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5920 uint64_t NumBytes = 0;
5921 if (Ty->isSized()) {
5922 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5923 NumBytes = NumBits / 8;
5924 if (!isPowerOf2_64(NumBits))
5929 int64_t Offset = AM.BaseOffs;
5931 // 9-bit signed offset
5932 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5935 // 12-bit unsigned offset
5936 unsigned shift = Log2_64(NumBytes);
5937 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5938 // Must be a multiple of NumBytes (NumBytes is a power of 2)
5939 (Offset >> shift) << shift == Offset)
5944 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5946 if (!AM.Scale || AM.Scale == 1 ||
5947 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5952 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5954 // Scaling factors are not free at all.
5955 // Operands | Rt Latency
5956 // -------------------------------------------
5958 // -------------------------------------------
5959 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
5960 // Rt, [Xn, Wm, <extend> #imm] |
5961 if (isLegalAddressingMode(AM, Ty))
5962 // Scale represents reg2 * scale, thus account for 1 if
5963 // it is not equal to 0 or 1.
5964 return AM.Scale != 0 && AM.Scale != 1;
5968 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
5969 VT = VT.getScalarType();
5974 switch (VT.getSimpleVT().SimpleTy) {
5986 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
5987 // LR is a callee-save register, but we must treat it as clobbered by any call
5988 // site. Hence we include LR in the scratch registers, which are in turn added
5989 // as implicit-defs for stackmaps and patchpoints.
5990 static const MCPhysReg ScratchRegs[] = {
5991 ARM64::X16, ARM64::X17, ARM64::LR, 0
5996 bool ARM64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
5997 EVT VT = N->getValueType(0);
5998 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
5999 // it with shift to let it be lowered to UBFX.
6000 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6001 isa<ConstantSDNode>(N->getOperand(1))) {
6002 uint64_t TruncMask = N->getConstantOperandVal(1);
6003 if (isMask_64(TruncMask) &&
6004 N->getOperand(0).getOpcode() == ISD::SRL &&
6005 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6011 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6013 assert(Ty->isIntegerTy());
6015 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6019 int64_t Val = Imm.getSExtValue();
6020 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
6023 if ((int64_t)Val < 0)
6026 Val &= (1LL << 32) - 1;
6028 unsigned LZ = countLeadingZeros((uint64_t)Val);
6029 unsigned Shift = (63 - LZ) / 16;
6030 // MOVZ is free so return true for one or fewer MOVK.
6031 return (Shift < 3) ? true : false;
6034 // Generate SUBS and CSEL for integer abs.
6035 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6036 EVT VT = N->getValueType(0);
6038 SDValue N0 = N->getOperand(0);
6039 SDValue N1 = N->getOperand(1);
6042 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6043 // and change it to SUB and CSEL.
6044 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6045 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6046 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6047 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6048 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6049 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6051 // Generate SUBS & CSEL.
6053 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6054 N0.getOperand(0), DAG.getConstant(0, VT));
6055 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6056 DAG.getConstant(ARM64CC::PL, MVT::i32),
6057 SDValue(Cmp.getNode(), 1));
6062 // performXorCombine - Attempts to handle integer ABS.
6063 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6064 TargetLowering::DAGCombinerInfo &DCI,
6065 const ARM64Subtarget *Subtarget) {
6066 if (DCI.isBeforeLegalizeOps())
6069 return performIntegerAbsCombine(N, DAG);
6072 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6073 TargetLowering::DAGCombinerInfo &DCI,
6074 const ARM64Subtarget *Subtarget) {
6075 if (DCI.isBeforeLegalizeOps())
6078 // Multiplication of a power of two plus/minus one can be done more
6079 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6080 // future CPUs have a cheaper MADD instruction, this may need to be
6081 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6082 // 64-bit is 5 cycles, so this is always a win.
6083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6084 APInt Value = C->getAPIntValue();
6085 EVT VT = N->getValueType(0);
6086 APInt VP1 = Value + 1;
6087 if (VP1.isPowerOf2()) {
6088 // Multiplying by one less than a power of two, replace with a shift
6090 SDValue ShiftedVal =
6091 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6092 DAG.getConstant(VP1.logBase2(), MVT::i64));
6093 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6095 APInt VM1 = Value - 1;
6096 if (VM1.isPowerOf2()) {
6097 // Multiplying by one more than a power of two, replace with a shift
6099 SDValue ShiftedVal =
6100 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6101 DAG.getConstant(VM1.logBase2(), MVT::i64));
6102 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6108 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6109 EVT VT = N->getValueType(0);
6110 if (VT != MVT::f32 && VT != MVT::f64)
6112 // Only optimize when the source and destination types have the same width.
6113 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6116 // If the result of an integer load is only used by an integer-to-float
6117 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6118 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6119 SDValue N0 = N->getOperand(0);
6120 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6121 // Do not change the width of a volatile load.
6122 !cast<LoadSDNode>(N0)->isVolatile()) {
6123 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6124 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6125 LN0->getPointerInfo(), LN0->isVolatile(),
6126 LN0->isNonTemporal(), LN0->isInvariant(),
6127 LN0->getAlignment());
6129 // Make sure successors of the original load stay after it by updating them
6130 // to use the new Chain.
6131 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6134 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6135 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6141 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6142 /// searches for and classifies those shifts.
6143 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6145 if (N.getOpcode() == ISD::SHL)
6147 else if (N.getOpcode() == ISD::SRL)
6152 if (!isa<ConstantSDNode>(N.getOperand(1)))
6155 ShiftAmount = N->getConstantOperandVal(1);
6156 Src = N->getOperand(0);
6160 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6161 /// registers viewed as a high/low pair. This function looks for the pattern:
6162 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6163 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6165 static SDValue tryCombineToEXTR(SDNode *N,
6166 TargetLowering::DAGCombinerInfo &DCI) {
6167 SelectionDAG &DAG = DCI.DAG;
6169 EVT VT = N->getValueType(0);
6171 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6173 if (VT != MVT::i32 && VT != MVT::i64)
6177 uint32_t ShiftLHS = 0;
6179 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6183 uint32_t ShiftRHS = 0;
6185 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6188 // If they're both trying to come from the high part of the register, they're
6189 // not really an EXTR.
6190 if (LHSFromHi == RHSFromHi)
6193 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6197 std::swap(LHS, RHS);
6198 std::swap(ShiftLHS, ShiftRHS);
6201 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6202 DAG.getConstant(ShiftRHS, MVT::i64));
6205 static SDValue tryCombineToBSL(SDNode *N,
6206 TargetLowering::DAGCombinerInfo &DCI) {
6207 EVT VT = N->getValueType(0);
6208 SelectionDAG &DAG = DCI.DAG;
6214 SDValue N0 = N->getOperand(0);
6215 if (N0.getOpcode() != ISD::AND)
6218 SDValue N1 = N->getOperand(1);
6219 if (N1.getOpcode() != ISD::AND)
6222 // We only have to look for constant vectors here since the general, variable
6223 // case can be handled in TableGen.
6224 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6225 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6226 for (int i = 1; i >= 0; --i)
6227 for (int j = 1; j >= 0; --j) {
6228 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6229 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6233 bool FoundMatch = true;
6234 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6235 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6236 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6238 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6245 return DAG.getNode(ARM64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6246 N0->getOperand(1 - i), N1->getOperand(1 - j));
6252 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6253 const ARM64Subtarget *Subtarget) {
6254 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6255 if (!EnableARM64ExtrGeneration)
6257 SelectionDAG &DAG = DCI.DAG;
6258 EVT VT = N->getValueType(0);
6260 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6263 SDValue Res = tryCombineToEXTR(N, DCI);
6267 Res = tryCombineToBSL(N, DCI);
6274 static SDValue performBitcastCombine(SDNode *N,
6275 TargetLowering::DAGCombinerInfo &DCI,
6276 SelectionDAG &DAG) {
6277 // Wait 'til after everything is legalized to try this. That way we have
6278 // legal vector types and such.
6279 if (DCI.isBeforeLegalizeOps())
6282 // Remove extraneous bitcasts around an extract_subvector.
6284 // (v4i16 (bitconvert
6285 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6287 // (extract_subvector ((v8i16 ...), (i64 4)))
6289 // Only interested in 64-bit vectors as the ultimate result.
6290 EVT VT = N->getValueType(0);
6293 if (VT.getSimpleVT().getSizeInBits() != 64)
6295 // Is the operand an extract_subvector starting at the beginning or halfway
6296 // point of the vector? A low half may also come through as an
6297 // EXTRACT_SUBREG, so look for that, too.
6298 SDValue Op0 = N->getOperand(0);
6299 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6300 !(Op0->isMachineOpcode() &&
6301 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6303 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6304 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6305 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6307 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6308 if (idx != ARM64::dsub)
6310 // The dsub reference is equivalent to a lane zero subvector reference.
6313 // Look through the bitcast of the input to the extract.
6314 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6316 SDValue Source = Op0->getOperand(0)->getOperand(0);
6317 // If the source type has twice the number of elements as our destination
6318 // type, we know this is an extract of the high or low half of the vector.
6319 EVT SVT = Source->getValueType(0);
6320 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6323 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6325 // Create the simplified form to just extract the low or high half of the
6326 // vector directly rather than bothering with the bitcasts.
6328 unsigned NumElements = VT.getVectorNumElements();
6330 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6331 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6333 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6334 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6340 static SDValue performConcatVectorsCombine(SDNode *N,
6341 TargetLowering::DAGCombinerInfo &DCI,
6342 SelectionDAG &DAG) {
6343 // Wait 'til after everything is legalized to try this. That way we have
6344 // legal vector types and such.
6345 if (DCI.isBeforeLegalizeOps())
6349 EVT VT = N->getValueType(0);
6351 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6352 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6353 // canonicalise to that.
6354 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6355 assert(VT.getVectorElementType().getSizeInBits() == 64);
6356 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6357 WidenVector(N->getOperand(0), DAG),
6358 DAG.getConstant(0, MVT::i64));
6361 // Canonicalise concat_vectors so that the right-hand vector has as few
6362 // bit-casts as possible before its real operation. The primary matching
6363 // destination for these operations will be the narrowing "2" instructions,
6364 // which depend on the operation being performed on this right-hand vector.
6366 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6368 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6370 SDValue Op1 = N->getOperand(1);
6371 if (Op1->getOpcode() != ISD::BITCAST)
6373 SDValue RHS = Op1->getOperand(0);
6374 MVT RHSTy = RHS.getValueType().getSimpleVT();
6375 // If the RHS is not a vector, this is not the pattern we're looking for.
6376 if (!RHSTy.isVector())
6379 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6381 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6382 RHSTy.getVectorNumElements() * 2);
6384 ISD::BITCAST, dl, VT,
6385 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6386 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6389 static SDValue tryCombineFixedPointConvert(SDNode *N,
6390 TargetLowering::DAGCombinerInfo &DCI,
6391 SelectionDAG &DAG) {
6392 // Wait 'til after everything is legalized to try this. That way we have
6393 // legal vector types and such.
6394 if (DCI.isBeforeLegalizeOps())
6396 // Transform a scalar conversion of a value from a lane extract into a
6397 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6398 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6399 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6401 // The second form interacts better with instruction selection and the
6402 // register allocator to avoid cross-class register copies that aren't
6403 // coalescable due to a lane reference.
6405 // Check the operand and see if it originates from a lane extract.
6406 SDValue Op1 = N->getOperand(1);
6407 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6408 // Yep, no additional predication needed. Perform the transform.
6409 SDValue IID = N->getOperand(0);
6410 SDValue Shift = N->getOperand(2);
6411 SDValue Vec = Op1.getOperand(0);
6412 SDValue Lane = Op1.getOperand(1);
6413 EVT ResTy = N->getValueType(0);
6417 // The vector width should be 128 bits by the time we get here, even
6418 // if it started as 64 bits (the extract_vector handling will have
6420 assert(Vec.getValueType().getSizeInBits() == 128 &&
6421 "unexpected vector size on extract_vector_elt!");
6422 if (Vec.getValueType() == MVT::v4i32)
6423 VecResTy = MVT::v4f32;
6424 else if (Vec.getValueType() == MVT::v2i64)
6425 VecResTy = MVT::v2f64;
6427 assert(0 && "unexpected vector type!");
6430 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6431 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6436 // AArch64 high-vector "long" operations are formed by performing the non-high
6437 // version on an extract_subvector of each operand which gets the high half:
6439 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6441 // However, there are cases which don't have an extract_high explicitly, but
6442 // have another operation that can be made compatible with one for free. For
6445 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6447 // This routine does the actual conversion of such DUPs, once outer routines
6448 // have determined that everything else is in order.
6449 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6450 // We can handle most types of duplicate, but the lane ones have an extra
6451 // operand saying *which* lane, so we need to know.
6453 switch (N.getOpcode()) {
6457 case ARM64ISD::DUPLANE8:
6458 case ARM64ISD::DUPLANE16:
6459 case ARM64ISD::DUPLANE32:
6460 case ARM64ISD::DUPLANE64:
6467 MVT NarrowTy = N.getSimpleValueType();
6468 if (!NarrowTy.is64BitVector())
6471 MVT ElementTy = NarrowTy.getVectorElementType();
6472 unsigned NumElems = NarrowTy.getVectorNumElements();
6473 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6477 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6480 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6482 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6483 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6486 static bool isEssentiallyExtractSubvector(SDValue N) {
6487 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6490 return N.getOpcode() == ISD::BITCAST &&
6491 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6494 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6495 struct GenericSetCCInfo {
6496 const SDValue *Opnd0;
6497 const SDValue *Opnd1;
6501 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6502 struct ARM64SetCCInfo {
6504 ARM64CC::CondCode CC;
6507 /// \brief Helper structure to keep track of SetCC information.
6509 GenericSetCCInfo Generic;
6510 ARM64SetCCInfo ARM64;
6513 /// \brief Helper structure to be able to read SetCC information.
6514 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6515 /// a GenericSetCCInfo.
6516 struct SetCCInfoAndKind {
6521 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6523 /// ARM64 lowered one.
6524 /// \p SetCCInfo is filled accordingly.
6525 /// \post SetCCInfo is meanginfull only when this function returns true.
6526 /// \return True when Op is a kind of SET_CC operation.
6527 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6528 // If this is a setcc, this is straight forward.
6529 if (Op.getOpcode() == ISD::SETCC) {
6530 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6531 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6532 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6533 SetCCInfo.IsARM64 = false;
6536 // Otherwise, check if this is a matching csel instruction.
6540 if (Op.getOpcode() != ARM64ISD::CSEL)
6542 // Set the information about the operands.
6543 // TODO: we want the operands of the Cmp not the csel
6544 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6545 SetCCInfo.IsARM64 = true;
6546 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6547 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6549 // Check that the operands matches the constraints:
6550 // (1) Both operands must be constants.
6551 // (2) One must be 1 and the other must be 0.
6552 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6553 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6556 if (!TValue || !FValue)
6560 if (!TValue->isOne()) {
6561 // Update the comparison when we are interested in !cc.
6562 std::swap(TValue, FValue);
6563 SetCCInfo.Info.ARM64.CC =
6564 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6566 return TValue->isOne() && FValue->isNullValue();
6569 // The folding we want to perform is:
6570 // (add x, (setcc cc ...) )
6572 // (csel x, (add x, 1), !cc ...)
6574 // The latter will get matched to a CSINC instruction.
6575 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6576 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6577 SDValue LHS = Op->getOperand(0);
6578 SDValue RHS = Op->getOperand(1);
6579 SetCCInfoAndKind InfoAndKind;
6581 // If neither operand is a SET_CC, give up.
6582 if (!isSetCC(LHS, InfoAndKind)) {
6583 std::swap(LHS, RHS);
6584 if (!isSetCC(LHS, InfoAndKind))
6588 // FIXME: This could be generatized to work for FP comparisons.
6589 EVT CmpVT = InfoAndKind.IsARM64
6590 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6591 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6592 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6598 if (InfoAndKind.IsARM64) {
6599 CCVal = DAG.getConstant(
6600 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6601 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6603 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6604 *InfoAndKind.Info.Generic.Opnd1,
6605 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6608 EVT VT = Op->getValueType(0);
6609 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6610 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6613 // The basic add/sub long vector instructions have variants with "2" on the end
6614 // which act on the high-half of their inputs. They are normally matched by
6617 // (add (zeroext (extract_high LHS)),
6618 // (zeroext (extract_high RHS)))
6619 // -> uaddl2 vD, vN, vM
6621 // However, if one of the extracts is something like a duplicate, this
6622 // instruction can still be used profitably. This function puts the DAG into a
6623 // more appropriate form for those patterns to trigger.
6624 static SDValue performAddSubLongCombine(SDNode *N,
6625 TargetLowering::DAGCombinerInfo &DCI,
6626 SelectionDAG &DAG) {
6627 if (DCI.isBeforeLegalizeOps())
6630 MVT VT = N->getSimpleValueType(0);
6631 if (!VT.is128BitVector()) {
6632 if (N->getOpcode() == ISD::ADD)
6633 return performSetccAddFolding(N, DAG);
6637 // Make sure both branches are extended in the same way.
6638 SDValue LHS = N->getOperand(0);
6639 SDValue RHS = N->getOperand(1);
6640 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6641 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6642 LHS.getOpcode() != RHS.getOpcode())
6645 unsigned ExtType = LHS.getOpcode();
6647 // It's not worth doing if at least one of the inputs isn't already an
6648 // extract, but we don't know which it'll be so we have to try both.
6649 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6650 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6654 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6655 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6656 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6660 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6663 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6666 // Massage DAGs which we can use the high-half "long" operations on into
6667 // something isel will recognize better. E.g.
6669 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6670 // (arm64_neon_umull (extract_high (v2i64 vec)))
6671 // (extract_high (v2i64 (dup128 scalar)))))
6673 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6674 TargetLowering::DAGCombinerInfo &DCI,
6675 SelectionDAG &DAG) {
6676 if (DCI.isBeforeLegalizeOps())
6679 SDValue LHS = N->getOperand(1);
6680 SDValue RHS = N->getOperand(2);
6681 assert(LHS.getValueType().is64BitVector() &&
6682 RHS.getValueType().is64BitVector() &&
6683 "unexpected shape for long operation");
6685 // Either node could be a DUP, but it's not worth doing both of them (you'd
6686 // just as well use the non-high version) so look for a corresponding extract
6687 // operation on the other "wing".
6688 if (isEssentiallyExtractSubvector(LHS)) {
6689 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6692 } else if (isEssentiallyExtractSubvector(RHS)) {
6693 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6698 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6699 N->getOperand(0), LHS, RHS);
6702 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6703 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6704 unsigned ElemBits = ElemTy.getSizeInBits();
6706 int64_t ShiftAmount;
6707 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6708 APInt SplatValue, SplatUndef;
6709 unsigned SplatBitSize;
6711 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6712 HasAnyUndefs, ElemBits) ||
6713 SplatBitSize != ElemBits)
6716 ShiftAmount = SplatValue.getSExtValue();
6717 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6718 ShiftAmount = CVN->getSExtValue();
6726 llvm_unreachable("Unknown shift intrinsic");
6727 case Intrinsic::arm64_neon_sqshl:
6728 Opcode = ARM64ISD::SQSHL_I;
6729 IsRightShift = false;
6731 case Intrinsic::arm64_neon_uqshl:
6732 Opcode = ARM64ISD::UQSHL_I;
6733 IsRightShift = false;
6735 case Intrinsic::arm64_neon_srshl:
6736 Opcode = ARM64ISD::SRSHR_I;
6737 IsRightShift = true;
6739 case Intrinsic::arm64_neon_urshl:
6740 Opcode = ARM64ISD::URSHR_I;
6741 IsRightShift = true;
6743 case Intrinsic::arm64_neon_sqshlu:
6744 Opcode = ARM64ISD::SQSHLU_I;
6745 IsRightShift = false;
6749 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6750 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6751 DAG.getConstant(-ShiftAmount, MVT::i32));
6752 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6753 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6754 DAG.getConstant(ShiftAmount, MVT::i32));
6759 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6760 // the intrinsics must be legal and take an i32, this means there's almost
6761 // certainly going to be a zext in the DAG which we can eliminate.
6762 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6763 SDValue AndN = N->getOperand(2);
6764 if (AndN.getOpcode() != ISD::AND)
6767 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6768 if (!CMask || CMask->getZExtValue() != Mask)
6771 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6772 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6775 static SDValue performIntrinsicCombine(SDNode *N,
6776 TargetLowering::DAGCombinerInfo &DCI,
6777 const ARM64Subtarget *Subtarget) {
6778 SelectionDAG &DAG = DCI.DAG;
6779 unsigned IID = getIntrinsicID(N);
6783 case Intrinsic::arm64_neon_vcvtfxs2fp:
6784 case Intrinsic::arm64_neon_vcvtfxu2fp:
6785 return tryCombineFixedPointConvert(N, DCI, DAG);
6787 case Intrinsic::arm64_neon_fmax:
6788 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6789 N->getOperand(1), N->getOperand(2));
6790 case Intrinsic::arm64_neon_fmin:
6791 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6792 N->getOperand(1), N->getOperand(2));
6793 case Intrinsic::arm64_neon_smull:
6794 case Intrinsic::arm64_neon_umull:
6795 case Intrinsic::arm64_neon_pmull:
6796 case Intrinsic::arm64_neon_sqdmull:
6797 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6798 case Intrinsic::arm64_neon_sqshl:
6799 case Intrinsic::arm64_neon_uqshl:
6800 case Intrinsic::arm64_neon_sqshlu:
6801 case Intrinsic::arm64_neon_srshl:
6802 case Intrinsic::arm64_neon_urshl:
6803 return tryCombineShiftImm(IID, N, DAG);
6804 case Intrinsic::arm64_crc32b:
6805 case Intrinsic::arm64_crc32cb:
6806 return tryCombineCRC32(0xff, N, DAG);
6807 case Intrinsic::arm64_crc32h:
6808 case Intrinsic::arm64_crc32ch:
6809 return tryCombineCRC32(0xffff, N, DAG);
6814 static SDValue performExtendCombine(SDNode *N,
6815 TargetLowering::DAGCombinerInfo &DCI,
6816 SelectionDAG &DAG) {
6817 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6818 // we can convert that DUP into another extract_high (of a bigger DUP), which
6819 // helps the backend to decide that an sabdl2 would be useful, saving a real
6820 // extract_high operation.
6821 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6822 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6823 SDNode *ABDNode = N->getOperand(0).getNode();
6824 unsigned IID = getIntrinsicID(ABDNode);
6825 if (IID == Intrinsic::arm64_neon_sabd ||
6826 IID == Intrinsic::arm64_neon_uabd) {
6827 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6828 if (!NewABD.getNode())
6831 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6836 // This is effectively a custom type legalization for ARM64.
6838 // Type legalization will split an extend of a small, legal, type to a larger
6839 // illegal type by first splitting the destination type, often creating
6840 // illegal source types, which then get legalized in isel-confusing ways,
6841 // leading to really terrible codegen. E.g.,
6842 // %result = v8i32 sext v8i8 %value
6844 // %losrc = extract_subreg %value, ...
6845 // %hisrc = extract_subreg %value, ...
6846 // %lo = v4i32 sext v4i8 %losrc
6847 // %hi = v4i32 sext v4i8 %hisrc
6848 // Things go rapidly downhill from there.
6850 // For ARM64, the [sz]ext vector instructions can only go up one element
6851 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6852 // take two instructions.
6854 // This implies that the most efficient way to do the extend from v8i8
6855 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6856 // the normal splitting to happen for the v8i16->v8i32.
6858 // This is pre-legalization to catch some cases where the default
6859 // type legalization will create ill-tempered code.
6860 if (!DCI.isBeforeLegalizeOps())
6863 // We're only interested in cleaning things up for non-legal vector types
6864 // here. If both the source and destination are legal, things will just
6865 // work naturally without any fiddling.
6866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6867 EVT ResVT = N->getValueType(0);
6868 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6870 // If the vector type isn't a simple VT, it's beyond the scope of what
6871 // we're worried about here. Let legalization do its thing and hope for
6873 if (!ResVT.isSimple())
6876 SDValue Src = N->getOperand(0);
6877 MVT SrcVT = Src->getValueType(0).getSimpleVT();
6878 // If the source VT is a 64-bit vector, we can play games and get the
6879 // better results we want.
6880 if (SrcVT.getSizeInBits() != 64)
6883 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6884 unsigned ElementCount = SrcVT.getVectorNumElements();
6885 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6887 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6889 // Now split the rest of the operation into two halves, each with a 64
6893 unsigned NumElements = ResVT.getVectorNumElements();
6894 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6895 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6896 ResVT.getVectorElementType(), NumElements / 2);
6898 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6899 LoVT.getVectorNumElements());
6900 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6901 DAG.getIntPtrConstant(0));
6902 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6903 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6904 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6905 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6907 // Now combine the parts back together so we still have a single result
6908 // like the combiner expects.
6909 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6912 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6913 /// value. The load store optimizer pass will merge them to store pair stores.
6914 /// This has better performance than a splat of the scalar followed by a split
6915 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6916 /// followed by an ext.b and two stores.
6917 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6918 SDValue StVal = St->getValue();
6919 EVT VT = StVal.getValueType();
6921 // Don't replace floating point stores, they possibly won't be transformed to
6922 // stp because of the store pair suppress pass.
6923 if (VT.isFloatingPoint())
6926 // Check for insert vector elements.
6927 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6930 // We can express a splat as store pair(s) for 2 or 4 elements.
6931 unsigned NumVecElts = VT.getVectorNumElements();
6932 if (NumVecElts != 4 && NumVecElts != 2)
6934 SDValue SplatVal = StVal.getOperand(1);
6935 unsigned RemainInsertElts = NumVecElts - 1;
6937 // Check that this is a splat.
6938 while (--RemainInsertElts) {
6939 SDValue NextInsertElt = StVal.getOperand(0);
6940 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6942 if (NextInsertElt.getOperand(1) != SplatVal)
6944 StVal = NextInsertElt;
6946 unsigned OrigAlignment = St->getAlignment();
6947 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6948 unsigned Alignment = std::min(OrigAlignment, EltOffset);
6950 // Create scalar stores. This is at least as good as the code sequence for a
6951 // split unaligned store wich is a dup.s, ext.b, and two stores.
6952 // Most of the time the three stores should be replaced by store pair
6953 // instructions (stp).
6955 SDValue BasePtr = St->getBasePtr();
6957 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6958 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6960 unsigned Offset = EltOffset;
6961 while (--NumVecElts) {
6962 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6963 DAG.getConstant(Offset, MVT::i64));
6964 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6965 St->getPointerInfo(), St->isVolatile(),
6966 St->isNonTemporal(), Alignment);
6967 Offset += EltOffset;
6972 static SDValue performSTORECombine(SDNode *N,
6973 TargetLowering::DAGCombinerInfo &DCI,
6975 const ARM64Subtarget *Subtarget) {
6976 if (!DCI.isBeforeLegalize())
6979 StoreSDNode *S = cast<StoreSDNode>(N);
6980 if (S->isVolatile())
6983 // Cyclone has bad performance on unaligned 16B stores when crossing line and
6984 // page boundries. We want to split such stores.
6985 if (!Subtarget->isCyclone())
6988 // Don't split at Oz.
6989 MachineFunction &MF = DAG.getMachineFunction();
6990 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
6991 AttributeSet::FunctionIndex, Attribute::MinSize);
6995 SDValue StVal = S->getValue();
6996 EVT VT = StVal.getValueType();
6998 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
6999 // those up regresses performance on micro-benchmarks and olden/bh.
7000 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7003 // Split unaligned 16B stores. They are terrible for performance.
7004 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7005 // extensions can use this to mark that it does not want splitting to happen
7006 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7007 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7008 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7009 S->getAlignment() <= 2)
7012 // If we get a splat of a scalar convert this vector store to a store of
7013 // scalars. They will be merged into store pairs thereby removing two
7015 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7016 if (ReplacedSplat != SDValue())
7017 return ReplacedSplat;
7020 unsigned NumElts = VT.getVectorNumElements() / 2;
7021 // Split VT into two.
7023 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7024 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7025 DAG.getIntPtrConstant(0));
7026 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7027 DAG.getIntPtrConstant(NumElts));
7028 SDValue BasePtr = S->getBasePtr();
7030 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7031 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7032 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7033 DAG.getConstant(8, MVT::i64));
7034 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7035 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7039 // Optimize compare with zero and branch.
7040 static SDValue performBRCONDCombine(SDNode *N,
7041 TargetLowering::DAGCombinerInfo &DCI,
7042 SelectionDAG &DAG) {
7043 SDValue Chain = N->getOperand(0);
7044 SDValue Dest = N->getOperand(1);
7045 SDValue CCVal = N->getOperand(2);
7046 SDValue Cmp = N->getOperand(3);
7048 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7049 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7050 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
7053 unsigned CmpOpc = Cmp.getOpcode();
7054 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
7057 // Only attempt folding if there is only one use of the flag and no use of the
7059 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7062 SDValue LHS = Cmp.getOperand(0);
7063 SDValue RHS = Cmp.getOperand(1);
7065 assert(LHS.getValueType() == RHS.getValueType() &&
7066 "Expected the value type to be the same for both operands!");
7067 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7070 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7071 std::swap(LHS, RHS);
7073 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7076 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7077 LHS.getOpcode() == ISD::SRL)
7080 // Fold the compare into the branch instruction.
7082 if (CC == ARM64CC::EQ)
7083 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7085 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7087 // Do not add new nodes to DAG combiner worklist.
7088 DCI.CombineTo(N, BR, false);
7093 // vselect (v1i1 setcc) ->
7094 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
7095 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7096 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7098 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7099 SDValue N0 = N->getOperand(0);
7100 EVT CCVT = N0.getValueType();
7102 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7103 CCVT.getVectorElementType() != MVT::i1)
7106 EVT ResVT = N->getValueType(0);
7107 EVT CmpVT = N0.getOperand(0).getValueType();
7108 // Only combine when the result type is of the same size as the compared
7110 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7113 SDValue IfTrue = N->getOperand(1);
7114 SDValue IfFalse = N->getOperand(2);
7116 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7117 N0.getOperand(0), N0.getOperand(1),
7118 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7119 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7123 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7124 DAGCombinerInfo &DCI) const {
7125 SelectionDAG &DAG = DCI.DAG;
7126 switch (N->getOpcode()) {
7131 return performAddSubLongCombine(N, DCI, DAG);
7133 return performXorCombine(N, DAG, DCI, Subtarget);
7135 return performMulCombine(N, DAG, DCI, Subtarget);
7136 case ISD::SINT_TO_FP:
7137 case ISD::UINT_TO_FP:
7138 return performIntToFpCombine(N, DAG);
7140 return performORCombine(N, DCI, Subtarget);
7141 case ISD::INTRINSIC_WO_CHAIN:
7142 return performIntrinsicCombine(N, DCI, Subtarget);
7143 case ISD::ANY_EXTEND:
7144 case ISD::ZERO_EXTEND:
7145 case ISD::SIGN_EXTEND:
7146 return performExtendCombine(N, DCI, DAG);
7148 return performBitcastCombine(N, DCI, DAG);
7149 case ISD::CONCAT_VECTORS:
7150 return performConcatVectorsCombine(N, DCI, DAG);
7152 return performVSelectCombine(N, DCI.DAG);
7154 return performSTORECombine(N, DCI, DAG, Subtarget);
7155 case ARM64ISD::BRCOND:
7156 return performBRCONDCombine(N, DCI, DAG);
7161 // Check if the return value is used as only a return value, as otherwise
7162 // we can't perform a tail-call. In particular, we need to check for
7163 // target ISD nodes that are returns and any other "odd" constructs
7164 // that the generic analysis code won't necessarily catch.
7165 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7166 if (N->getNumValues() != 1)
7168 if (!N->hasNUsesOfValue(1, 0))
7171 SDValue TCChain = Chain;
7172 SDNode *Copy = *N->use_begin();
7173 if (Copy->getOpcode() == ISD::CopyToReg) {
7174 // If the copy has a glue operand, we conservatively assume it isn't safe to
7175 // perform a tail call.
7176 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7179 TCChain = Copy->getOperand(0);
7180 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7183 bool HasRet = false;
7184 for (SDNode *Node : Copy->uses()) {
7185 if (Node->getOpcode() != ARM64ISD::RET_FLAG)
7197 // Return whether the an instruction can potentially be optimized to a tail
7198 // call. This will cause the optimizers to attempt to move, or duplicate,
7199 // return instructions to help enable tail call optimizations for this
7201 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7202 if (!EnableARM64TailCalls)
7205 if (!CI->isTailCall())
7211 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7213 ISD::MemIndexedMode &AM,
7215 SelectionDAG &DAG) const {
7216 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7219 Base = Op->getOperand(0);
7220 // All of the indexed addressing mode instructions take a signed
7221 // 9 bit immediate offset.
7222 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7223 int64_t RHSC = (int64_t)RHS->getZExtValue();
7224 if (RHSC >= 256 || RHSC <= -256)
7226 IsInc = (Op->getOpcode() == ISD::ADD);
7227 Offset = Op->getOperand(1);
7233 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7235 ISD::MemIndexedMode &AM,
7236 SelectionDAG &DAG) const {
7239 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7240 VT = LD->getMemoryVT();
7241 Ptr = LD->getBasePtr();
7242 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7243 VT = ST->getMemoryVT();
7244 Ptr = ST->getBasePtr();
7249 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7251 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7255 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7258 ISD::MemIndexedMode &AM,
7259 SelectionDAG &DAG) const {
7262 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7263 VT = LD->getMemoryVT();
7264 Ptr = LD->getBasePtr();
7265 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7266 VT = ST->getMemoryVT();
7267 Ptr = ST->getBasePtr();
7272 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7274 // Post-indexing updates the base, so it's not a valid transform
7275 // if that's not the same as the load's pointer.
7278 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7282 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7283 SmallVectorImpl<SDValue> &Results,
7284 SelectionDAG &DAG) const {
7285 switch (N->getOpcode()) {
7287 llvm_unreachable("Don't know how to custom expand this");
7288 case ISD::FP_TO_UINT:
7289 case ISD::FP_TO_SINT:
7290 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7291 // Let normal code take care of it by not adding anything to Results.
7296 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
7297 // Loads and stores less than 128-bits are already atomic; ones above that
7298 // are doomed anyway, so defer to the default libcall and blame the OS when
7300 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
7301 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
7302 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
7303 return LI->getType()->getPrimitiveSizeInBits() == 128;
7305 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
7306 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
7309 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
7310 AtomicOrdering Ord) const {
7311 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7312 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
7314 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7316 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
7317 // intrinsic must return {i64, i64} and we have to recombine them into a
7318 // single i128 here.
7319 if (ValTy->getPrimitiveSizeInBits() == 128) {
7321 IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
7322 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
7324 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7325 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
7327 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
7328 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
7329 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
7330 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
7331 return Builder.CreateOr(
7332 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
7335 Type *Tys[] = { Addr->getType() };
7337 IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
7338 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
7340 return Builder.CreateTruncOrBitCast(
7341 Builder.CreateCall(Ldxr, Addr),
7342 cast<PointerType>(Addr->getType())->getElementType());
7345 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
7346 Value *Val, Value *Addr,
7347 AtomicOrdering Ord) const {
7348 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7350 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7352 // Since the intrinsics must have legal type, the i128 intrinsics take two
7353 // parameters: "i64, i64". We must marshal Val into the appropriate form
7355 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7357 IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7358 Function *Stxr = Intrinsic::getDeclaration(M, Int);
7359 Type *Int64Ty = Type::getInt64Ty(M->getContext());
7361 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7362 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7363 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7364 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7368 IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7369 Type *Tys[] = { Addr->getType() };
7370 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7372 return Builder.CreateCall2(
7373 Stxr, Builder.CreateZExtOrBitCast(
7374 Val, Stxr->getFunctionType()->getParamType(0)),