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 #define DEBUG_TYPE "arm64-lower"
16 #include "ARM64ISelLowering.h"
17 #include "ARM64PerfectShuffle.h"
18 #include "ARM64Subtarget.h"
19 #include "ARM64CallingConv.h"
20 #include "ARM64MachineFunctionInfo.h"
21 #include "ARM64TargetMachine.h"
22 #include "ARM64TargetObjectFile.h"
23 #include "MCTargetDesc/ARM64AddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
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)."),
49 StrictAlign("arm64-strict-align", cl::Hidden,
50 cl::desc("Disallow all unaligned memory accesses"));
52 // Place holder until extr generation is tested fully.
54 EnableARM64ExtrGeneration("arm64-extr-generation", cl::Hidden,
55 cl::desc("Allow ARM64 (or (shift)(shift))->extract"),
59 EnableARM64SlrGeneration("arm64-shift-insert-generation", cl::Hidden,
60 cl::desc("Allow ARM64 SLI/SRI formation"),
63 //===----------------------------------------------------------------------===//
64 // ARM64 Lowering public interface.
65 //===----------------------------------------------------------------------===//
66 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
67 if (TM.getSubtarget<ARM64Subtarget>().isTargetDarwin())
68 return new ARM64_MachoTargetObjectFile();
70 return new ARM64_ELFTargetObjectFile();
73 ARM64TargetLowering::ARM64TargetLowering(ARM64TargetMachine &TM)
74 : TargetLowering(TM, createTLOF(TM)) {
75 Subtarget = &TM.getSubtarget<ARM64Subtarget>();
77 // ARM64 doesn't have comparisons which set GPRs or setcc instructions, so
78 // we have to make something up. Arbitrarily, choose ZeroOrOne.
79 setBooleanContents(ZeroOrOneBooleanContent);
80 // When comparing vectors the result sets the different elements in the
81 // vector to all-one or all-zero.
82 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84 // Set up the register classes.
85 addRegisterClass(MVT::i32, &ARM64::GPR32allRegClass);
86 addRegisterClass(MVT::i64, &ARM64::GPR64allRegClass);
87 addRegisterClass(MVT::f32, &ARM64::FPR32RegClass);
88 addRegisterClass(MVT::f64, &ARM64::FPR64RegClass);
89 addRegisterClass(MVT::f128, &ARM64::FPR128RegClass);
90 addRegisterClass(MVT::v16i8, &ARM64::FPR8RegClass);
91 addRegisterClass(MVT::v8i16, &ARM64::FPR16RegClass);
93 // Someone set us up the NEON.
94 addDRTypeForNEON(MVT::v2f32);
95 addDRTypeForNEON(MVT::v8i8);
96 addDRTypeForNEON(MVT::v4i16);
97 addDRTypeForNEON(MVT::v2i32);
98 addDRTypeForNEON(MVT::v1i64);
99 addDRTypeForNEON(MVT::v1f64);
101 addQRTypeForNEON(MVT::v4f32);
102 addQRTypeForNEON(MVT::v2f64);
103 addQRTypeForNEON(MVT::v16i8);
104 addQRTypeForNEON(MVT::v8i16);
105 addQRTypeForNEON(MVT::v4i32);
106 addQRTypeForNEON(MVT::v2i64);
108 // Compute derived properties from the register classes
109 computeRegisterProperties();
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
142 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
143 // silliness like this:
144 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
145 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
146 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
147 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
148 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
149 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
150 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
151 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
152 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
153 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
154 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
155 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
156 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
157 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
158 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
159 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
160 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
161 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
162 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
163 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
164 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
165 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
166 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
167 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
168 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
170 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
171 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
172 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
173 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
174 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
176 // Custom lowering hooks are needed for XOR
177 // to fold it into CSINC/CSINV.
178 setOperationAction(ISD::XOR, MVT::i32, Custom);
179 setOperationAction(ISD::XOR, MVT::i64, Custom);
181 // Virtually no operation on f128 is legal, but LLVM can't expand them when
182 // there's a valid register class, so we need custom operations in most cases.
183 setOperationAction(ISD::FABS, MVT::f128, Expand);
184 setOperationAction(ISD::FADD, MVT::f128, Custom);
185 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
186 setOperationAction(ISD::FCOS, MVT::f128, Expand);
187 setOperationAction(ISD::FDIV, MVT::f128, Custom);
188 setOperationAction(ISD::FMA, MVT::f128, Expand);
189 setOperationAction(ISD::FMUL, MVT::f128, Custom);
190 setOperationAction(ISD::FNEG, MVT::f128, Expand);
191 setOperationAction(ISD::FPOW, MVT::f128, Expand);
192 setOperationAction(ISD::FREM, MVT::f128, Expand);
193 setOperationAction(ISD::FRINT, MVT::f128, Expand);
194 setOperationAction(ISD::FSIN, MVT::f128, Expand);
195 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
196 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
197 setOperationAction(ISD::FSUB, MVT::f128, Custom);
198 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
199 setOperationAction(ISD::SETCC, MVT::f128, Custom);
200 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
201 setOperationAction(ISD::SELECT, MVT::f128, Custom);
202 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
203 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
205 // Lowering for many of the conversions is actually specified by the non-f128
206 // type. The LowerXXX function will be trivial when f128 isn't involved.
207 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
208 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
209 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
210 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
211 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
212 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
213 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
214 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
215 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
216 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
217 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
218 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
219 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
220 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
223 setOperationAction(ISD::ATOMIC_SWAP, MVT::i128, Custom);
224 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i128, Custom);
225 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
226 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i128, Custom);
227 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i128, Custom);
228 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i128, Custom);
229 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i128, Custom);
230 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i128, Custom);
231 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i128, Custom);
232 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i128, Custom);
233 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i128, Custom);
234 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i128, Custom);
235 // These are surprisingly difficult. The only single-copy atomic 128-bit
236 // instruction on AArch64 is stxp (when it succeeds). So a store can safely
237 // become a simple swap, but a load can only be determined to have been atomic
238 // if storing the same value back succeeds.
239 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
240 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Expand);
242 // Variable arguments.
243 setOperationAction(ISD::VASTART, MVT::Other, Custom);
244 setOperationAction(ISD::VAARG, MVT::Other, Custom);
245 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
246 setOperationAction(ISD::VAEND, MVT::Other, Expand);
248 // Variable-sized objects.
249 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
250 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
251 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
253 // Exception handling.
254 // FIXME: These are guesses. Has this been defined yet?
255 setExceptionPointerRegister(ARM64::X0);
256 setExceptionSelectorRegister(ARM64::X1);
258 // Constant pool entries
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
262 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
264 // Add/Sub overflow ops with MVT::Glues are lowered to CPSR dependences.
265 setOperationAction(ISD::ADDC, MVT::i32, Custom);
266 setOperationAction(ISD::ADDE, MVT::i32, Custom);
267 setOperationAction(ISD::SUBC, MVT::i32, Custom);
268 setOperationAction(ISD::SUBE, MVT::i32, Custom);
269 setOperationAction(ISD::ADDC, MVT::i64, Custom);
270 setOperationAction(ISD::ADDE, MVT::i64, Custom);
271 setOperationAction(ISD::SUBC, MVT::i64, Custom);
272 setOperationAction(ISD::SUBE, MVT::i64, Custom);
274 // ARM64 lacks both left-rotate and popcount instructions.
275 setOperationAction(ISD::ROTL, MVT::i32, Expand);
276 setOperationAction(ISD::ROTL, MVT::i64, Expand);
278 // ARM64 doesn't have a direct vector ->f32 conversion instructions for
279 // elements smaller than i32, so promote the input to i32 first.
280 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
281 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
282 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
283 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
284 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
285 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
286 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
287 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
288 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
290 // ARM64 doesn't have {U|S}MUL_LOHI.
291 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
292 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
294 // ARM64 doesn't have MUL.2d:
295 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
297 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
298 // counterparts, which ARM64 supports directly.
299 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
300 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
301 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
302 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
304 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
305 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
307 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
308 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
309 setOperationAction(ISD::SREM, MVT::i32, Expand);
310 setOperationAction(ISD::SREM, MVT::i64, Expand);
311 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
312 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
313 setOperationAction(ISD::UREM, MVT::i32, Expand);
314 setOperationAction(ISD::UREM, MVT::i64, Expand);
316 // Custom lower Add/Sub/Mul with overflow.
317 setOperationAction(ISD::SADDO, MVT::i32, Custom);
318 setOperationAction(ISD::SADDO, MVT::i64, Custom);
319 setOperationAction(ISD::UADDO, MVT::i32, Custom);
320 setOperationAction(ISD::UADDO, MVT::i64, Custom);
321 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
322 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
323 setOperationAction(ISD::USUBO, MVT::i32, Custom);
324 setOperationAction(ISD::USUBO, MVT::i64, Custom);
325 setOperationAction(ISD::SMULO, MVT::i32, Custom);
326 setOperationAction(ISD::SMULO, MVT::i64, Custom);
327 setOperationAction(ISD::UMULO, MVT::i32, Custom);
328 setOperationAction(ISD::UMULO, MVT::i64, Custom);
330 setOperationAction(ISD::FSIN, MVT::f32, Expand);
331 setOperationAction(ISD::FSIN, MVT::f64, Expand);
332 setOperationAction(ISD::FCOS, MVT::f32, Expand);
333 setOperationAction(ISD::FCOS, MVT::f64, Expand);
334 setOperationAction(ISD::FPOW, MVT::f32, Expand);
335 setOperationAction(ISD::FPOW, MVT::f64, Expand);
336 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
337 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
339 // ARM64 has implementations of a lot of rounding-like FP operations.
340 static MVT RoundingTypes[] = { MVT::f32, MVT::f64, MVT::v2f32,
341 MVT::v4f32, MVT::v2f64 };
342 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
343 MVT Ty = RoundingTypes[I];
344 setOperationAction(ISD::FFLOOR, Ty, Legal);
345 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
346 setOperationAction(ISD::FCEIL, Ty, Legal);
347 setOperationAction(ISD::FRINT, Ty, Legal);
348 setOperationAction(ISD::FTRUNC, Ty, Legal);
349 setOperationAction(ISD::FROUND, Ty, Legal);
352 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
354 if (Subtarget->isTargetMachO()) {
355 // For iOS, we don't want to the normal expansion of a libcall to
356 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
358 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
359 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
361 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
362 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
365 // ARM64 does not have floating-point extending loads, i1 sign-extending load,
366 // floating-point truncating stores, or v2i32->v2i16 truncating store.
367 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
368 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
369 setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
370 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
371 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
372 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
373 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
374 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
375 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
376 // Indexed loads and stores are supported.
377 for (unsigned im = (unsigned)ISD::PRE_INC;
378 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
379 setIndexedLoadAction(im, MVT::i8, Legal);
380 setIndexedLoadAction(im, MVT::i16, Legal);
381 setIndexedLoadAction(im, MVT::i32, Legal);
382 setIndexedLoadAction(im, MVT::i64, Legal);
383 setIndexedLoadAction(im, MVT::f64, Legal);
384 setIndexedLoadAction(im, MVT::f32, Legal);
385 setIndexedStoreAction(im, MVT::i8, Legal);
386 setIndexedStoreAction(im, MVT::i16, Legal);
387 setIndexedStoreAction(im, MVT::i32, Legal);
388 setIndexedStoreAction(im, MVT::i64, Legal);
389 setIndexedStoreAction(im, MVT::f64, Legal);
390 setIndexedStoreAction(im, MVT::f32, Legal);
393 // Likewise, narrowing and extending vector loads/stores aren't handled
395 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
396 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
398 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
401 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
402 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
403 setTruncStoreAction((MVT::SimpleValueType)VT,
404 (MVT::SimpleValueType)InnerVT, Expand);
405 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
406 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
407 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
411 setOperationAction(ISD::TRAP, MVT::Other, Legal);
412 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
414 // We combine OR nodes for bitfield operations.
415 setTargetDAGCombine(ISD::OR);
417 // Vector add and sub nodes may conceal a high-half opportunity.
418 // Also, try to fold ADD into CSINC/CSINV..
419 setTargetDAGCombine(ISD::ADD);
420 setTargetDAGCombine(ISD::SUB);
422 setTargetDAGCombine(ISD::XOR);
423 setTargetDAGCombine(ISD::SINT_TO_FP);
424 setTargetDAGCombine(ISD::UINT_TO_FP);
426 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
428 setTargetDAGCombine(ISD::ANY_EXTEND);
429 setTargetDAGCombine(ISD::ZERO_EXTEND);
430 setTargetDAGCombine(ISD::SIGN_EXTEND);
431 setTargetDAGCombine(ISD::BITCAST);
432 setTargetDAGCombine(ISD::CONCAT_VECTORS);
433 setTargetDAGCombine(ISD::STORE);
435 setTargetDAGCombine(ISD::MUL);
437 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
438 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
439 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
441 setStackPointerRegisterToSaveRestore(ARM64::SP);
443 setSchedulingPreference(Sched::Hybrid);
446 MaskAndBranchFoldingIsLegal = true;
448 setMinFunctionAlignment(2);
450 RequireStrictAlign = StrictAlign;
453 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
454 if (VT == MVT::v2f32) {
455 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
456 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
458 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
459 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
460 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
461 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
462 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
464 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
465 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
468 // Mark vector float intrinsics as expand.
469 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
470 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
471 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
472 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
473 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
474 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
475 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
476 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
477 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
478 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
481 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
482 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
483 setOperationAction(ISD::SCALAR_TO_VECTOR, VT.getSimpleVT(), Custom);
484 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
485 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
486 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
487 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
488 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
489 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
490 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
491 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
492 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
493 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
495 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
496 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
497 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
498 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
500 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
501 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
502 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
503 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
504 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
506 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
507 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
510 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
511 addRegisterClass(VT, &ARM64::FPR64RegClass);
512 addTypeForNEON(VT, MVT::v2i32);
515 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
516 addRegisterClass(VT, &ARM64::FPR128RegClass);
517 addTypeForNEON(VT, MVT::v4i32);
520 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
523 return VT.changeVectorElementTypeToInteger();
526 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
527 /// Mask are known to be either zero or one and return them in the
528 /// KnownZero/KnownOne bitsets.
529 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
530 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
531 const SelectionDAG &DAG, unsigned Depth) const {
532 switch (Op.getOpcode()) {
535 case ARM64ISD::CSEL: {
536 APInt KnownZero2, KnownOne2;
537 DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
538 DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
539 KnownZero &= KnownZero2;
540 KnownOne &= KnownOne2;
543 case ISD::INTRINSIC_W_CHAIN:
545 case ISD::INTRINSIC_WO_CHAIN:
546 case ISD::INTRINSIC_VOID: {
547 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
551 case Intrinsic::arm64_neon_umaxv:
552 case Intrinsic::arm64_neon_uminv: {
553 // Figure out the datatype of the vector operand. The UMINV instruction
554 // will zero extend the result, so we can mark as known zero all the
555 // bits larger than the element datatype. 32-bit or larget doesn't need
556 // this as those are legal types and will be handled by isel directly.
557 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
558 unsigned BitWidth = KnownZero.getBitWidth();
559 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
560 assert(BitWidth >= 8 && "Unexpected width!");
561 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
563 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
564 assert(BitWidth >= 16 && "Unexpected width!");
565 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
575 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
579 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
580 // FIXME: On ARM64, this depends on the type.
581 // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
582 // and the offset has to be a multiple of the related size in bytes.
587 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
588 const TargetLibraryInfo *libInfo) const {
589 return ARM64::createFastISel(funcInfo, libInfo);
592 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
596 case ARM64ISD::CALL: return "ARM64ISD::CALL";
597 case ARM64ISD::ADRP: return "ARM64ISD::ADRP";
598 case ARM64ISD::ADDlow: return "ARM64ISD::ADDlow";
599 case ARM64ISD::LOADgot: return "ARM64ISD::LOADgot";
600 case ARM64ISD::RET_FLAG: return "ARM64ISD::RET_FLAG";
601 case ARM64ISD::BRCOND: return "ARM64ISD::BRCOND";
602 case ARM64ISD::CSEL: return "ARM64ISD::CSEL";
603 case ARM64ISD::FCSEL: return "ARM64ISD::FCSEL";
604 case ARM64ISD::CSINV: return "ARM64ISD::CSINV";
605 case ARM64ISD::CSNEG: return "ARM64ISD::CSNEG";
606 case ARM64ISD::CSINC: return "ARM64ISD::CSINC";
607 case ARM64ISD::THREAD_POINTER: return "ARM64ISD::THREAD_POINTER";
608 case ARM64ISD::TLSDESC_CALL: return "ARM64ISD::TLSDESC_CALL";
609 case ARM64ISD::ADC: return "ARM64ISD::ADC";
610 case ARM64ISD::SBC: return "ARM64ISD::SBC";
611 case ARM64ISD::ADDS: return "ARM64ISD::ADDS";
612 case ARM64ISD::SUBS: return "ARM64ISD::SUBS";
613 case ARM64ISD::ADCS: return "ARM64ISD::ADCS";
614 case ARM64ISD::SBCS: return "ARM64ISD::SBCS";
615 case ARM64ISD::ANDS: return "ARM64ISD::ANDS";
616 case ARM64ISD::FCMP: return "ARM64ISD::FCMP";
617 case ARM64ISD::FMIN: return "ARM64ISD::FMIN";
618 case ARM64ISD::FMAX: return "ARM64ISD::FMAX";
619 case ARM64ISD::DUP: return "ARM64ISD::DUP";
620 case ARM64ISD::DUPLANE8: return "ARM64ISD::DUPLANE8";
621 case ARM64ISD::DUPLANE16: return "ARM64ISD::DUPLANE16";
622 case ARM64ISD::DUPLANE32: return "ARM64ISD::DUPLANE32";
623 case ARM64ISD::DUPLANE64: return "ARM64ISD::DUPLANE64";
624 case ARM64ISD::MOVI: return "ARM64ISD::MOVI";
625 case ARM64ISD::MOVIshift: return "ARM64ISD::MOVIshift";
626 case ARM64ISD::MOVIedit: return "ARM64ISD::MOVIedit";
627 case ARM64ISD::MOVImsl: return "ARM64ISD::MOVImsl";
628 case ARM64ISD::FMOV: return "ARM64ISD::FMOV";
629 case ARM64ISD::MVNIshift: return "ARM64ISD::MVNIshift";
630 case ARM64ISD::MVNImsl: return "ARM64ISD::MVNImsl";
631 case ARM64ISD::BICi: return "ARM64ISD::BICi";
632 case ARM64ISD::ORRi: return "ARM64ISD::ORRi";
633 case ARM64ISD::NEG: return "ARM64ISD::NEG";
634 case ARM64ISD::EXTR: return "ARM64ISD::EXTR";
635 case ARM64ISD::ZIP1: return "ARM64ISD::ZIP1";
636 case ARM64ISD::ZIP2: return "ARM64ISD::ZIP2";
637 case ARM64ISD::UZP1: return "ARM64ISD::UZP1";
638 case ARM64ISD::UZP2: return "ARM64ISD::UZP2";
639 case ARM64ISD::TRN1: return "ARM64ISD::TRN1";
640 case ARM64ISD::TRN2: return "ARM64ISD::TRN2";
641 case ARM64ISD::REV16: return "ARM64ISD::REV16";
642 case ARM64ISD::REV32: return "ARM64ISD::REV32";
643 case ARM64ISD::REV64: return "ARM64ISD::REV64";
644 case ARM64ISD::EXT: return "ARM64ISD::EXT";
645 case ARM64ISD::VSHL: return "ARM64ISD::VSHL";
646 case ARM64ISD::VLSHR: return "ARM64ISD::VLSHR";
647 case ARM64ISD::VASHR: return "ARM64ISD::VASHR";
648 case ARM64ISD::CMEQ: return "ARM64ISD::CMEQ";
649 case ARM64ISD::CMGE: return "ARM64ISD::CMGE";
650 case ARM64ISD::CMGT: return "ARM64ISD::CMGT";
651 case ARM64ISD::CMHI: return "ARM64ISD::CMHI";
652 case ARM64ISD::CMHS: return "ARM64ISD::CMHS";
653 case ARM64ISD::FCMEQ: return "ARM64ISD::FCMEQ";
654 case ARM64ISD::FCMGE: return "ARM64ISD::FCMGE";
655 case ARM64ISD::FCMGT: return "ARM64ISD::FCMGT";
656 case ARM64ISD::CMEQz: return "ARM64ISD::CMEQz";
657 case ARM64ISD::CMGEz: return "ARM64ISD::CMGEz";
658 case ARM64ISD::CMGTz: return "ARM64ISD::CMGTz";
659 case ARM64ISD::CMLEz: return "ARM64ISD::CMLEz";
660 case ARM64ISD::CMLTz: return "ARM64ISD::CMLTz";
661 case ARM64ISD::FCMEQz: return "ARM64ISD::FCMEQz";
662 case ARM64ISD::FCMGEz: return "ARM64ISD::FCMGEz";
663 case ARM64ISD::FCMGTz: return "ARM64ISD::FCMGTz";
664 case ARM64ISD::FCMLEz: return "ARM64ISD::FCMLEz";
665 case ARM64ISD::FCMLTz: return "ARM64ISD::FCMLTz";
666 case ARM64ISD::NOT: return "ARM64ISD::NOT";
667 case ARM64ISD::BIT: return "ARM64ISD::BIT";
668 case ARM64ISD::CBZ: return "ARM64ISD::CBZ";
669 case ARM64ISD::CBNZ: return "ARM64ISD::CBNZ";
670 case ARM64ISD::TBZ: return "ARM64ISD::TBZ";
671 case ARM64ISD::TBNZ: return "ARM64ISD::TBNZ";
672 case ARM64ISD::TC_RETURN: return "ARM64ISD::TC_RETURN";
673 case ARM64ISD::SITOF: return "ARM64ISD::SITOF";
674 case ARM64ISD::UITOF: return "ARM64ISD::UITOF";
675 case ARM64ISD::SQSHL_I: return "ARM64ISD::SQSHL_I";
676 case ARM64ISD::UQSHL_I: return "ARM64ISD::UQSHL_I";
677 case ARM64ISD::SRSHR_I: return "ARM64ISD::SRSHR_I";
678 case ARM64ISD::URSHR_I: return "ARM64ISD::URSHR_I";
679 case ARM64ISD::SQSHLU_I: return "ARM64ISD::SQSHLU_I";
680 case ARM64ISD::WrapperLarge: return "ARM64ISD::WrapperLarge";
684 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
685 unsigned &LdrOpc, unsigned &StrOpc) {
686 static unsigned LoadBares[] = { ARM64::LDXRB, ARM64::LDXRH, ARM64::LDXRW,
687 ARM64::LDXRX, ARM64::LDXPX };
688 static unsigned LoadAcqs[] = { ARM64::LDAXRB, ARM64::LDAXRH, ARM64::LDAXRW,
689 ARM64::LDAXRX, ARM64::LDAXPX };
690 static unsigned StoreBares[] = { ARM64::STXRB, ARM64::STXRH, ARM64::STXRW,
691 ARM64::STXRX, ARM64::STXPX };
692 static unsigned StoreRels[] = { ARM64::STLXRB, ARM64::STLXRH, ARM64::STLXRW,
693 ARM64::STLXRX, ARM64::STLXPX };
695 unsigned *LoadOps, *StoreOps;
696 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
701 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
702 StoreOps = StoreRels;
704 StoreOps = StoreBares;
706 assert(isPowerOf2_32(Size) && Size <= 16 &&
707 "unsupported size for atomic binary op!");
709 LdrOpc = LoadOps[Log2_32(Size)];
710 StrOpc = StoreOps[Log2_32(Size)];
713 MachineBasicBlock *ARM64TargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
714 MachineBasicBlock *BB,
715 unsigned Size) const {
716 unsigned dest = MI->getOperand(0).getReg();
717 unsigned ptr = MI->getOperand(1).getReg();
718 unsigned oldval = MI->getOperand(2).getReg();
719 unsigned newval = MI->getOperand(3).getReg();
720 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
721 unsigned scratch = BB->getParent()->getRegInfo().createVirtualRegister(
722 &ARM64::GPR32RegClass);
723 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
724 DebugLoc dl = MI->getDebugLoc();
726 // FIXME: We currently always generate a seq_cst operation; we should
727 // be able to relax this in some cases.
728 unsigned ldrOpc, strOpc;
729 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
731 MachineFunction *MF = BB->getParent();
732 const BasicBlock *LLVM_BB = BB->getBasicBlock();
733 MachineFunction::iterator It = BB;
734 ++It; // insert the new blocks after the current block
736 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
737 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
738 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
739 MF->insert(It, loop1MBB);
740 MF->insert(It, loop2MBB);
741 MF->insert(It, exitMBB);
743 // Transfer the remainder of BB and its successor edges to exitMBB.
744 exitMBB->splice(exitMBB->begin(), BB,
745 std::next(MachineBasicBlock::iterator(MI)), BB->end());
746 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
750 // fallthrough --> loop1MBB
751 BB->addSuccessor(loop1MBB);
758 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
759 BuildMI(BB, dl, TII->get(Size == 8 ? ARM64::SUBSXrr : ARM64::SUBSWrr))
760 .addReg(Size == 8 ? ARM64::XZR : ARM64::WZR, RegState::Define)
763 BuildMI(BB, dl, TII->get(ARM64::Bcc)).addImm(ARM64CC::NE).addMBB(exitMBB);
764 BB->addSuccessor(loop2MBB);
765 BB->addSuccessor(exitMBB);
768 // strex scratch, newval, [ptr]
772 BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
773 BuildMI(BB, dl, TII->get(ARM64::CBNZW)).addReg(scratch).addMBB(loop1MBB);
774 BB->addSuccessor(loop1MBB);
775 BB->addSuccessor(exitMBB);
781 MI->eraseFromParent(); // The instruction is gone now.
787 ARM64TargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
788 unsigned Size, unsigned BinOpcode) const {
789 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
790 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
792 const BasicBlock *LLVM_BB = BB->getBasicBlock();
793 MachineFunction *MF = BB->getParent();
794 MachineFunction::iterator It = BB;
797 unsigned dest = MI->getOperand(0).getReg();
798 unsigned ptr = MI->getOperand(1).getReg();
799 unsigned incr = MI->getOperand(2).getReg();
800 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
801 DebugLoc dl = MI->getDebugLoc();
803 unsigned ldrOpc, strOpc;
804 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
806 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
807 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
808 MF->insert(It, loopMBB);
809 MF->insert(It, exitMBB);
811 // Transfer the remainder of BB and its successor edges to exitMBB.
812 exitMBB->splice(exitMBB->begin(), BB,
813 std::next(MachineBasicBlock::iterator(MI)), BB->end());
814 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
816 MachineRegisterInfo &RegInfo = MF->getRegInfo();
817 unsigned scratch = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
821 : RegInfo.createVirtualRegister(Size == 8 ? &ARM64::GPR64RegClass
822 : &ARM64::GPR32RegClass);
826 // fallthrough --> loopMBB
827 BB->addSuccessor(loopMBB);
831 // <binop> scratch2, dest, incr
832 // stxr scratch, scratch2, ptr
833 // cbnz scratch, loopMBB
834 // fallthrough --> exitMBB
836 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
838 // operand order needs to go the other way for NAND
839 if (BinOpcode == ARM64::BICWrr || BinOpcode == ARM64::BICXrr)
840 BuildMI(BB, dl, TII->get(BinOpcode), scratch2).addReg(incr).addReg(dest);
842 BuildMI(BB, dl, TII->get(BinOpcode), scratch2).addReg(dest).addReg(incr);
845 BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
846 BuildMI(BB, dl, TII->get(ARM64::CBNZW)).addReg(scratch).addMBB(loopMBB);
848 BB->addSuccessor(loopMBB);
849 BB->addSuccessor(exitMBB);
855 MI->eraseFromParent(); // The instruction is gone now.
860 MachineBasicBlock *ARM64TargetLowering::EmitAtomicBinary128(
861 MachineInstr *MI, MachineBasicBlock *BB, unsigned BinOpcodeLo,
862 unsigned BinOpcodeHi) const {
863 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
864 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
866 const BasicBlock *LLVM_BB = BB->getBasicBlock();
867 MachineFunction *MF = BB->getParent();
868 MachineFunction::iterator It = BB;
871 unsigned DestLo = MI->getOperand(0).getReg();
872 unsigned DestHi = MI->getOperand(1).getReg();
873 unsigned Ptr = MI->getOperand(2).getReg();
874 unsigned IncrLo = MI->getOperand(3).getReg();
875 unsigned IncrHi = MI->getOperand(4).getReg();
876 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(5).getImm());
877 DebugLoc DL = MI->getDebugLoc();
879 unsigned LdrOpc, StrOpc;
880 getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
882 MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
883 MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
884 MF->insert(It, LoopMBB);
885 MF->insert(It, ExitMBB);
887 // Transfer the remainder of BB and its successor edges to exitMBB.
888 ExitMBB->splice(ExitMBB->begin(), BB,
889 std::next(MachineBasicBlock::iterator(MI)), BB->end());
890 ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
892 MachineRegisterInfo &RegInfo = MF->getRegInfo();
893 unsigned ScratchRes = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
894 unsigned ScratchLo = IncrLo, ScratchHi = IncrHi;
896 assert(BinOpcodeHi && "Expect neither or both opcodes to be defined");
897 ScratchLo = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
898 ScratchHi = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
903 // fallthrough --> LoopMBB
904 BB->addSuccessor(LoopMBB);
907 // ldxp DestLo, DestHi, Ptr
908 // <binoplo> ScratchLo, DestLo, IncrLo
909 // <binophi> ScratchHi, DestHi, IncrHi
910 // stxp ScratchRes, ScratchLo, ScratchHi, ptr
911 // cbnz ScratchRes, LoopMBB
912 // fallthrough --> ExitMBB
914 BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
915 .addReg(DestHi, RegState::Define)
918 // operand order needs to go the other way for NAND
919 if (BinOpcodeLo == ARM64::BICXrr) {
920 std::swap(IncrLo, DestLo);
921 std::swap(IncrHi, DestHi);
924 BuildMI(BB, DL, TII->get(BinOpcodeLo), ScratchLo).addReg(DestLo).addReg(
926 BuildMI(BB, DL, TII->get(BinOpcodeHi), ScratchHi).addReg(DestHi).addReg(
930 BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
934 BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(LoopMBB);
936 BB->addSuccessor(LoopMBB);
937 BB->addSuccessor(ExitMBB);
943 MI->eraseFromParent(); // The instruction is gone now.
949 ARM64TargetLowering::EmitAtomicCmpSwap128(MachineInstr *MI,
950 MachineBasicBlock *BB) const {
951 unsigned DestLo = MI->getOperand(0).getReg();
952 unsigned DestHi = MI->getOperand(1).getReg();
953 unsigned Ptr = MI->getOperand(2).getReg();
954 unsigned OldValLo = MI->getOperand(3).getReg();
955 unsigned OldValHi = MI->getOperand(4).getReg();
956 unsigned NewValLo = MI->getOperand(5).getReg();
957 unsigned NewValHi = MI->getOperand(6).getReg();
958 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(7).getImm());
959 unsigned ScratchRes = BB->getParent()->getRegInfo().createVirtualRegister(
960 &ARM64::GPR32RegClass);
961 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
962 DebugLoc DL = MI->getDebugLoc();
964 unsigned LdrOpc, StrOpc;
965 getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
967 MachineFunction *MF = BB->getParent();
968 const BasicBlock *LLVM_BB = BB->getBasicBlock();
969 MachineFunction::iterator It = BB;
970 ++It; // insert the new blocks after the current block
972 MachineBasicBlock *Loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
973 MachineBasicBlock *Loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
974 MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
975 MF->insert(It, Loop1MBB);
976 MF->insert(It, Loop2MBB);
977 MF->insert(It, ExitMBB);
979 // Transfer the remainder of BB and its successor edges to exitMBB.
980 ExitMBB->splice(ExitMBB->begin(), BB,
981 std::next(MachineBasicBlock::iterator(MI)), BB->end());
982 ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
986 // fallthrough --> Loop1MBB
987 BB->addSuccessor(Loop1MBB);
990 // ldxp DestLo, DestHi, [Ptr]
991 // cmp DestLo, OldValLo
992 // sbc xzr, DestHi, OldValHi
995 BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
996 .addReg(DestHi, RegState::Define)
998 BuildMI(BB, DL, TII->get(ARM64::SUBSXrr), ARM64::XZR).addReg(DestLo).addReg(
1000 BuildMI(BB, DL, TII->get(ARM64::SBCXr), ARM64::XZR).addReg(DestHi).addReg(
1003 BuildMI(BB, DL, TII->get(ARM64::Bcc)).addImm(ARM64CC::NE).addMBB(ExitMBB);
1004 BB->addSuccessor(Loop2MBB);
1005 BB->addSuccessor(ExitMBB);
1008 // stxp ScratchRes, NewValLo, NewValHi, [Ptr]
1009 // cbnz ScratchRes, Loop1MBB
1011 BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
1015 BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(Loop1MBB);
1016 BB->addSuccessor(Loop1MBB);
1017 BB->addSuccessor(ExitMBB);
1023 MI->eraseFromParent(); // The instruction is gone now.
1028 MachineBasicBlock *ARM64TargetLowering::EmitAtomicMinMax128(
1029 MachineInstr *MI, MachineBasicBlock *BB, unsigned CondCode) const {
1030 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
1031 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1033 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1034 MachineFunction *MF = BB->getParent();
1035 MachineFunction::iterator It = BB;
1038 unsigned DestLo = MI->getOperand(0).getReg();
1039 unsigned DestHi = MI->getOperand(1).getReg();
1040 unsigned Ptr = MI->getOperand(2).getReg();
1041 unsigned IncrLo = MI->getOperand(3).getReg();
1042 unsigned IncrHi = MI->getOperand(4).getReg();
1043 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(5).getImm());
1044 DebugLoc DL = MI->getDebugLoc();
1046 unsigned LdrOpc, StrOpc;
1047 getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
1049 MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1050 MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1051 MF->insert(It, LoopMBB);
1052 MF->insert(It, ExitMBB);
1054 // Transfer the remainder of BB and its successor edges to exitMBB.
1055 ExitMBB->splice(ExitMBB->begin(), BB,
1056 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1057 ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
1059 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1060 unsigned ScratchRes = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
1061 unsigned ScratchLo = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
1062 unsigned ScratchHi = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
1066 // fallthrough --> LoopMBB
1067 BB->addSuccessor(LoopMBB);
1070 // ldxp DestLo, DestHi, Ptr
1071 // cmp ScratchLo, DestLo, IncrLo
1072 // sbc xzr, ScratchHi, DestHi, IncrHi
1073 // csel ScratchLo, DestLo, IncrLo, <cmp-op>
1074 // csel ScratchHi, DestHi, IncrHi, <cmp-op>
1075 // stxp ScratchRes, ScratchLo, ScratchHi, ptr
1076 // cbnz ScratchRes, LoopMBB
1077 // fallthrough --> ExitMBB
1079 BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
1080 .addReg(DestHi, RegState::Define)
1083 BuildMI(BB, DL, TII->get(ARM64::SUBSXrr), ARM64::XZR).addReg(DestLo).addReg(
1085 BuildMI(BB, DL, TII->get(ARM64::SBCXr), ARM64::XZR).addReg(DestHi).addReg(
1088 BuildMI(BB, DL, TII->get(ARM64::CSELXr), ScratchLo)
1092 BuildMI(BB, DL, TII->get(ARM64::CSELXr), ScratchHi)
1097 BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
1101 BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(LoopMBB);
1103 BB->addSuccessor(LoopMBB);
1104 BB->addSuccessor(ExitMBB);
1110 MI->eraseFromParent(); // The instruction is gone now.
1116 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
1117 MachineBasicBlock *MBB) const {
1118 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1122 // [... previous instrs leading to comparison ...]
1128 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1130 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1131 MachineFunction *MF = MBB->getParent();
1132 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1133 DebugLoc DL = MI->getDebugLoc();
1134 MachineFunction::iterator It = MBB;
1137 unsigned DestReg = MI->getOperand(0).getReg();
1138 unsigned IfTrueReg = MI->getOperand(1).getReg();
1139 unsigned IfFalseReg = MI->getOperand(2).getReg();
1140 unsigned CondCode = MI->getOperand(3).getImm();
1141 bool CPSRKilled = MI->getOperand(4).isKill();
1143 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1144 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1145 MF->insert(It, TrueBB);
1146 MF->insert(It, EndBB);
1148 // Transfer rest of current basic-block to EndBB
1149 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1151 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1153 BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1154 BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
1155 MBB->addSuccessor(TrueBB);
1156 MBB->addSuccessor(EndBB);
1158 // TrueBB falls through to the end.
1159 TrueBB->addSuccessor(EndBB);
1162 TrueBB->addLiveIn(ARM64::CPSR);
1163 EndBB->addLiveIn(ARM64::CPSR);
1166 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
1172 MI->eraseFromParent();
1177 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1178 MachineBasicBlock *BB) const {
1179 switch (MI->getOpcode()) {
1184 assert(0 && "Unexpected instruction for custom inserter!");
1187 case ARM64::ATOMIC_LOAD_ADD_I8:
1188 return EmitAtomicBinary(MI, BB, 1, ARM64::ADDWrr);
1189 case ARM64::ATOMIC_LOAD_ADD_I16:
1190 return EmitAtomicBinary(MI, BB, 2, ARM64::ADDWrr);
1191 case ARM64::ATOMIC_LOAD_ADD_I32:
1192 return EmitAtomicBinary(MI, BB, 4, ARM64::ADDWrr);
1193 case ARM64::ATOMIC_LOAD_ADD_I64:
1194 return EmitAtomicBinary(MI, BB, 8, ARM64::ADDXrr);
1195 case ARM64::ATOMIC_LOAD_ADD_I128:
1196 return EmitAtomicBinary128(MI, BB, ARM64::ADDSXrr, ARM64::ADCXr);
1198 case ARM64::ATOMIC_LOAD_AND_I8:
1199 return EmitAtomicBinary(MI, BB, 1, ARM64::ANDWrr);
1200 case ARM64::ATOMIC_LOAD_AND_I16:
1201 return EmitAtomicBinary(MI, BB, 2, ARM64::ANDWrr);
1202 case ARM64::ATOMIC_LOAD_AND_I32:
1203 return EmitAtomicBinary(MI, BB, 4, ARM64::ANDWrr);
1204 case ARM64::ATOMIC_LOAD_AND_I64:
1205 return EmitAtomicBinary(MI, BB, 8, ARM64::ANDXrr);
1206 case ARM64::ATOMIC_LOAD_AND_I128:
1207 return EmitAtomicBinary128(MI, BB, ARM64::ANDXrr, ARM64::ANDXrr);
1209 case ARM64::ATOMIC_LOAD_OR_I8:
1210 return EmitAtomicBinary(MI, BB, 1, ARM64::ORRWrr);
1211 case ARM64::ATOMIC_LOAD_OR_I16:
1212 return EmitAtomicBinary(MI, BB, 2, ARM64::ORRWrr);
1213 case ARM64::ATOMIC_LOAD_OR_I32:
1214 return EmitAtomicBinary(MI, BB, 4, ARM64::ORRWrr);
1215 case ARM64::ATOMIC_LOAD_OR_I64:
1216 return EmitAtomicBinary(MI, BB, 8, ARM64::ORRXrr);
1217 case ARM64::ATOMIC_LOAD_OR_I128:
1218 return EmitAtomicBinary128(MI, BB, ARM64::ORRXrr, ARM64::ORRXrr);
1220 case ARM64::ATOMIC_LOAD_XOR_I8:
1221 return EmitAtomicBinary(MI, BB, 1, ARM64::EORWrr);
1222 case ARM64::ATOMIC_LOAD_XOR_I16:
1223 return EmitAtomicBinary(MI, BB, 2, ARM64::EORWrr);
1224 case ARM64::ATOMIC_LOAD_XOR_I32:
1225 return EmitAtomicBinary(MI, BB, 4, ARM64::EORWrr);
1226 case ARM64::ATOMIC_LOAD_XOR_I64:
1227 return EmitAtomicBinary(MI, BB, 8, ARM64::EORXrr);
1228 case ARM64::ATOMIC_LOAD_XOR_I128:
1229 return EmitAtomicBinary128(MI, BB, ARM64::EORXrr, ARM64::EORXrr);
1231 case ARM64::ATOMIC_LOAD_NAND_I8:
1232 return EmitAtomicBinary(MI, BB, 1, ARM64::BICWrr);
1233 case ARM64::ATOMIC_LOAD_NAND_I16:
1234 return EmitAtomicBinary(MI, BB, 2, ARM64::BICWrr);
1235 case ARM64::ATOMIC_LOAD_NAND_I32:
1236 return EmitAtomicBinary(MI, BB, 4, ARM64::BICWrr);
1237 case ARM64::ATOMIC_LOAD_NAND_I64:
1238 return EmitAtomicBinary(MI, BB, 8, ARM64::BICXrr);
1239 case ARM64::ATOMIC_LOAD_NAND_I128:
1240 return EmitAtomicBinary128(MI, BB, ARM64::BICXrr, ARM64::BICXrr);
1242 case ARM64::ATOMIC_LOAD_SUB_I8:
1243 return EmitAtomicBinary(MI, BB, 1, ARM64::SUBWrr);
1244 case ARM64::ATOMIC_LOAD_SUB_I16:
1245 return EmitAtomicBinary(MI, BB, 2, ARM64::SUBWrr);
1246 case ARM64::ATOMIC_LOAD_SUB_I32:
1247 return EmitAtomicBinary(MI, BB, 4, ARM64::SUBWrr);
1248 case ARM64::ATOMIC_LOAD_SUB_I64:
1249 return EmitAtomicBinary(MI, BB, 8, ARM64::SUBXrr);
1250 case ARM64::ATOMIC_LOAD_SUB_I128:
1251 return EmitAtomicBinary128(MI, BB, ARM64::SUBSXrr, ARM64::SBCXr);
1253 case ARM64::ATOMIC_LOAD_MIN_I128:
1254 return EmitAtomicMinMax128(MI, BB, ARM64CC::LT);
1256 case ARM64::ATOMIC_LOAD_MAX_I128:
1257 return EmitAtomicMinMax128(MI, BB, ARM64CC::GT);
1259 case ARM64::ATOMIC_LOAD_UMIN_I128:
1260 return EmitAtomicMinMax128(MI, BB, ARM64CC::CC);
1262 case ARM64::ATOMIC_LOAD_UMAX_I128:
1263 return EmitAtomicMinMax128(MI, BB, ARM64CC::HI);
1265 case ARM64::ATOMIC_SWAP_I8:
1266 return EmitAtomicBinary(MI, BB, 1, 0);
1267 case ARM64::ATOMIC_SWAP_I16:
1268 return EmitAtomicBinary(MI, BB, 2, 0);
1269 case ARM64::ATOMIC_SWAP_I32:
1270 return EmitAtomicBinary(MI, BB, 4, 0);
1271 case ARM64::ATOMIC_SWAP_I64:
1272 return EmitAtomicBinary(MI, BB, 8, 0);
1273 case ARM64::ATOMIC_SWAP_I128:
1274 return EmitAtomicBinary128(MI, BB, 0, 0);
1276 case ARM64::ATOMIC_CMP_SWAP_I8:
1277 return EmitAtomicCmpSwap(MI, BB, 1);
1278 case ARM64::ATOMIC_CMP_SWAP_I16:
1279 return EmitAtomicCmpSwap(MI, BB, 2);
1280 case ARM64::ATOMIC_CMP_SWAP_I32:
1281 return EmitAtomicCmpSwap(MI, BB, 4);
1282 case ARM64::ATOMIC_CMP_SWAP_I64:
1283 return EmitAtomicCmpSwap(MI, BB, 8);
1284 case ARM64::ATOMIC_CMP_SWAP_I128:
1285 return EmitAtomicCmpSwap128(MI, BB);
1287 case ARM64::F128CSEL:
1288 return EmitF128CSEL(MI, BB);
1290 case TargetOpcode::STACKMAP:
1291 case TargetOpcode::PATCHPOINT:
1292 return emitPatchPoint(MI, BB);
1294 llvm_unreachable("Unexpected instruction for custom inserter!");
1297 //===----------------------------------------------------------------------===//
1298 // ARM64 Lowering private implementation.
1299 //===----------------------------------------------------------------------===//
1301 //===----------------------------------------------------------------------===//
1303 //===----------------------------------------------------------------------===//
1305 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
1306 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
1309 llvm_unreachable("Unknown condition code!");
1333 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
1334 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
1335 ARM64CC::CondCode &CondCode2) {
1336 CondCode2 = ARM64CC::AL;
1339 llvm_unreachable("Unknown FP condition!");
1342 CondCode = ARM64CC::EQ;
1346 CondCode = ARM64CC::GT;
1350 CondCode = ARM64CC::GE;
1353 CondCode = ARM64CC::MI;
1356 CondCode = ARM64CC::LS;
1359 CondCode = ARM64CC::MI;
1360 CondCode2 = ARM64CC::GT;
1363 CondCode = ARM64CC::VC;
1366 CondCode = ARM64CC::VS;
1369 CondCode = ARM64CC::EQ;
1370 CondCode2 = ARM64CC::VS;
1373 CondCode = ARM64CC::HI;
1376 CondCode = ARM64CC::PL;
1380 CondCode = ARM64CC::LT;
1384 CondCode = ARM64CC::LE;
1388 CondCode = ARM64CC::NE;
1393 static bool isLegalArithImmed(uint64_t C) {
1394 // Matches ARM64DAGToDAGISel::SelectArithImmed().
1395 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1398 static SDValue emitComparison(SDValue LHS, SDValue RHS, SDLoc dl,
1399 SelectionDAG &DAG) {
1400 EVT VT = LHS.getValueType();
1402 if (VT.isFloatingPoint())
1403 return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
1405 // The CMP instruction is just an alias for SUBS, and representing it as
1406 // SUBS means that it's possible to get CSE with subtract operations.
1407 // A later phase can perform the optimization of setting the destination
1408 // register to WZR/XZR if it ends up being unused.
1409 return DAG.getNode(ARM64ISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1413 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1414 SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
1415 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1416 EVT VT = RHS.getValueType();
1417 uint64_t C = RHSC->getZExtValue();
1418 if (!isLegalArithImmed(C)) {
1419 // Constant does not fit, try adjusting it by one?
1425 if ((VT == MVT::i32 && C != 0x80000000 &&
1426 isLegalArithImmed((uint32_t)(C - 1))) ||
1427 (VT == MVT::i64 && C != 0x80000000ULL &&
1428 isLegalArithImmed(C - 1ULL))) {
1429 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1430 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1431 RHS = DAG.getConstant(C, VT);
1436 if ((VT == MVT::i32 && C != 0 &&
1437 isLegalArithImmed((uint32_t)(C - 1))) ||
1438 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1439 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1440 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1441 RHS = DAG.getConstant(C, VT);
1446 if ((VT == MVT::i32 && C != 0x7fffffff &&
1447 isLegalArithImmed((uint32_t)(C + 1))) ||
1448 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1449 isLegalArithImmed(C + 1ULL))) {
1450 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1451 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1452 RHS = DAG.getConstant(C, VT);
1457 if ((VT == MVT::i32 && C != 0xffffffff &&
1458 isLegalArithImmed((uint32_t)(C + 1))) ||
1459 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1460 isLegalArithImmed(C + 1ULL))) {
1461 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1462 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1463 RHS = DAG.getConstant(C, VT);
1470 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
1471 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
1472 ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1476 static std::pair<SDValue, SDValue>
1477 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1478 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1479 "Unsupported value type");
1480 SDValue Value, Overflow;
1482 SDValue LHS = Op.getOperand(0);
1483 SDValue RHS = Op.getOperand(1);
1485 switch (Op.getOpcode()) {
1487 llvm_unreachable("Unknown overflow instruction!");
1489 Opc = ARM64ISD::ADDS;
1493 Opc = ARM64ISD::ADDS;
1497 Opc = ARM64ISD::SUBS;
1501 Opc = ARM64ISD::SUBS;
1504 // Multiply needs a little bit extra work.
1508 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1509 if (Op.getValueType() == MVT::i32) {
1510 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1511 // For a 32 bit multiply with overflow check we want the instruction
1512 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1513 // need to generate the following pattern:
1514 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1515 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1516 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1517 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1518 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1519 DAG.getConstant(0, MVT::i64));
1520 // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1521 // operation. We need to clear out the upper 32 bits, because we used a
1522 // widening multiply that wrote all 64 bits. In the end this should be a
1524 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1526 // The signed overflow check requires more than just a simple check for
1527 // any bit set in the upper 32 bits of the result. These bits could be
1528 // just the sign bits of a negative number. To perform the overflow
1529 // check we have to arithmetic shift right the 32nd bit of the result by
1530 // 31 bits. Then we compare the result to the upper 32 bits.
1531 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1532 DAG.getConstant(32, MVT::i64));
1533 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1534 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1535 DAG.getConstant(31, MVT::i64));
1536 // It is important that LowerBits is last, otherwise the arithmetic
1537 // shift will not be folded into the compare (SUBS).
1538 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1539 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1542 // The overflow check for unsigned multiply is easy. We only need to
1543 // check if any of the upper 32 bits are set. This can be done with a
1544 // CMP (shifted register). For that we need to generate the following
1546 // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1547 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1548 DAG.getConstant(32, MVT::i64));
1549 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1551 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1552 UpperBits).getValue(1);
1556 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1557 // For the 64 bit multiply
1558 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1560 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1561 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1562 DAG.getConstant(63, MVT::i64));
1563 // It is important that LowerBits is last, otherwise the arithmetic
1564 // shift will not be folded into the compare (SUBS).
1565 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1566 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1569 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1570 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1572 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1573 UpperBits).getValue(1);
1580 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1582 // Emit the ARM64 operation with overflow check.
1583 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1584 Overflow = Value.getValue(1);
1586 return std::make_pair(Value, Overflow);
1589 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1590 RTLIB::Libcall Call) const {
1591 SmallVector<SDValue, 2> Ops;
1592 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1593 Ops.push_back(Op.getOperand(i));
1595 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1599 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1600 SDValue Sel = Op.getOperand(0);
1601 SDValue Other = Op.getOperand(1);
1603 // If neither operand is a SELECT_CC, give up.
1604 if (Sel.getOpcode() != ISD::SELECT_CC)
1605 std::swap(Sel, Other);
1606 if (Sel.getOpcode() != ISD::SELECT_CC)
1609 // The folding we want to perform is:
1610 // (xor x, (select_cc a, b, cc, 0, -1) )
1612 // (csel x, (xor x, -1), cc ...)
1614 // The latter will get matched to a CSINV instruction.
1616 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1617 SDValue LHS = Sel.getOperand(0);
1618 SDValue RHS = Sel.getOperand(1);
1619 SDValue TVal = Sel.getOperand(2);
1620 SDValue FVal = Sel.getOperand(3);
1623 // FIXME: This could be generalized to non-integer comparisons.
1624 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1627 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1628 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1630 // The the values aren't constants, this isn't the pattern we're looking for.
1631 if (!CFVal || !CTVal)
1634 // We can commute the SELECT_CC by inverting the condition. This
1635 // might be needed to make this fit into a CSINV pattern.
1636 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1637 std::swap(TVal, FVal);
1638 std::swap(CTVal, CFVal);
1639 CC = ISD::getSetCCInverse(CC, true);
1642 // If the constants line up, perform the transform!
1643 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1645 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1648 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1649 DAG.getConstant(-1ULL, Other.getValueType()));
1651 return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1658 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1659 EVT VT = Op.getValueType();
1661 // Let legalize expand this if it isn't a legal type yet.
1662 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1665 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1668 bool ExtraOp = false;
1669 switch (Op.getOpcode()) {
1671 assert(0 && "Invalid code");
1673 Opc = ARM64ISD::ADDS;
1676 Opc = ARM64ISD::SUBS;
1679 Opc = ARM64ISD::ADCS;
1683 Opc = ARM64ISD::SBCS;
1689 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1690 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1694 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1695 // Let legalize expand this if it isn't a legal type yet.
1696 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1699 ARM64CC::CondCode CC;
1700 // The actual operation that sets the overflow or carry flag.
1701 SDValue Value, Overflow;
1702 std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1704 // We use 0 and 1 as false and true values.
1705 SDValue TVal = DAG.getConstant(1, MVT::i32);
1706 SDValue FVal = DAG.getConstant(0, MVT::i32);
1708 // We use an inverted condition, because the conditional select is inverted
1709 // too. This will allow it to be selected to a single instruction:
1710 // CSINC Wd, WZR, WZR, invert(cond).
1711 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1712 Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1715 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1716 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1719 // Prefetch operands are:
1720 // 1: Address to prefetch
1722 // 3: int locality (0 = no locality ... 3 = extreme locality)
1723 // 4: bool isDataCache
1724 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1726 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1727 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1728 // The data thing is not used.
1729 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1731 bool IsStream = !Locality;
1732 // When the locality number is set
1734 // The front-end should have filtered out the out-of-range values
1735 assert(Locality <= 3 && "Prefetch locality out-of-range");
1736 // The locality degree is the opposite of the cache speed.
1737 // Put the number the other way around.
1738 // The encoding starts at 0 for level 1
1739 Locality = 3 - Locality;
1742 // built the mask value encoding the expected behavior.
1743 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1744 (Locality << 1) | // Cache level bits
1745 (unsigned)IsStream; // Stream bit
1746 return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1747 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1750 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1751 SelectionDAG &DAG) const {
1752 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1755 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1757 return LowerF128Call(Op, DAG, LC);
1760 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1761 SelectionDAG &DAG) const {
1762 if (Op.getOperand(0).getValueType() != MVT::f128) {
1763 // It's legal except when f128 is involved
1768 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1770 // FP_ROUND node has a second operand indicating whether it is known to be
1771 // precise. That doesn't take part in the LibCall so we can't directly use
1773 SDValue SrcVal = Op.getOperand(0);
1774 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1775 /*isSigned*/ false, SDLoc(Op)).first;
1778 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1779 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1780 // Any additional optimization in this function should be recorded
1781 // in the cost tables.
1782 EVT InVT = Op.getOperand(0).getValueType();
1783 EVT VT = Op.getValueType();
1785 // FP_TO_XINT conversion from the same type are legal.
1786 if (VT.getSizeInBits() == InVT.getSizeInBits())
1789 if (InVT == MVT::v2f64) {
1791 SDValue Cv = DAG.getNode(Op.getOpcode(), dl, MVT::v2i64, Op.getOperand(0));
1792 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1795 // Type changing conversions are illegal.
1799 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1800 SelectionDAG &DAG) const {
1801 if (Op.getOperand(0).getValueType().isVector())
1802 return LowerVectorFP_TO_INT(Op, DAG);
1804 if (Op.getOperand(0).getValueType() != MVT::f128) {
1805 // It's legal except when f128 is involved
1810 if (Op.getOpcode() == ISD::FP_TO_SINT)
1811 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1813 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1815 SmallVector<SDValue, 2> Ops;
1816 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1817 Ops.push_back(Op.getOperand(i));
1819 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1823 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1824 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1825 // Any additional optimization in this function should be recorded
1826 // in the cost tables.
1827 EVT VT = Op.getValueType();
1829 SDValue In = Op.getOperand(0);
1830 EVT InVT = In.getValueType();
1832 // v2i32 to v2f32 is legal.
1833 if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1836 // This function only handles v2f64 outputs.
1837 if (VT == MVT::v2f64) {
1838 // Extend the input argument to a v2i64 that we can feed into the
1839 // floating point conversion. Zero or sign extend based on whether
1840 // we're doing a signed or unsigned float conversion.
1842 Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1843 assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1844 SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1845 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1848 // Scalarize v2i64 to v2f32 conversions.
1849 std::vector<SDValue> BuildVectorOps;
1850 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1851 SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1852 DAG.getConstant(i, MVT::i64));
1853 Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1854 BuildVectorOps.push_back(Sclr);
1857 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &BuildVectorOps[0],
1858 BuildVectorOps.size());
1861 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1862 SelectionDAG &DAG) const {
1863 if (Op.getValueType().isVector())
1864 return LowerVectorINT_TO_FP(Op, DAG);
1866 // i128 conversions are libcalls.
1867 if (Op.getOperand(0).getValueType() == MVT::i128)
1870 // Other conversions are legal, unless it's to the completely software-based
1872 if (Op.getValueType() != MVT::f128)
1876 if (Op.getOpcode() == ISD::SINT_TO_FP)
1877 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1879 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1881 return LowerF128Call(Op, DAG, LC);
1884 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1885 // For iOS, we want to call an alternative entry point: __sincos_stret,
1886 // which returns the values in two S / D registers.
1888 SDValue Arg = Op.getOperand(0);
1889 EVT ArgVT = Arg.getValueType();
1890 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1897 Entry.isSExt = false;
1898 Entry.isZExt = false;
1899 Args.push_back(Entry);
1901 const char *LibcallName =
1902 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1903 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1905 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1906 TargetLowering::CallLoweringInfo CLI(
1907 DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1908 CallingConv::Fast, /*isTaillCall=*/false,
1909 /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1910 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1911 return CallResult.first;
1914 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1915 SelectionDAG &DAG) const {
1916 switch (Op.getOpcode()) {
1918 llvm_unreachable("unimplemented operand");
1920 case ISD::GlobalAddress:
1921 return LowerGlobalAddress(Op, DAG);
1922 case ISD::GlobalTLSAddress:
1923 return LowerGlobalTLSAddress(Op, DAG);
1925 return LowerSETCC(Op, DAG);
1927 return LowerBR_CC(Op, DAG);
1929 return LowerSELECT(Op, DAG);
1930 case ISD::SELECT_CC:
1931 return LowerSELECT_CC(Op, DAG);
1932 case ISD::JumpTable:
1933 return LowerJumpTable(Op, DAG);
1934 case ISD::ConstantPool:
1935 return LowerConstantPool(Op, DAG);
1936 case ISD::BlockAddress:
1937 return LowerBlockAddress(Op, DAG);
1939 return LowerVASTART(Op, DAG);
1941 return LowerVACOPY(Op, DAG);
1943 return LowerVAARG(Op, DAG);
1948 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1955 return LowerXALUO(Op, DAG);
1957 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1959 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1961 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1963 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1965 return LowerFP_ROUND(Op, DAG);
1966 case ISD::FP_EXTEND:
1967 return LowerFP_EXTEND(Op, DAG);
1968 case ISD::FRAMEADDR:
1969 return LowerFRAMEADDR(Op, DAG);
1970 case ISD::RETURNADDR:
1971 return LowerRETURNADDR(Op, DAG);
1972 case ISD::INSERT_VECTOR_ELT:
1973 return LowerINSERT_VECTOR_ELT(Op, DAG);
1974 case ISD::EXTRACT_VECTOR_ELT:
1975 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1976 case ISD::SCALAR_TO_VECTOR:
1977 return LowerSCALAR_TO_VECTOR(Op, DAG);
1978 case ISD::BUILD_VECTOR:
1979 return LowerBUILD_VECTOR(Op, DAG);
1980 case ISD::VECTOR_SHUFFLE:
1981 return LowerVECTOR_SHUFFLE(Op, DAG);
1982 case ISD::EXTRACT_SUBVECTOR:
1983 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1987 return LowerVectorSRA_SRL_SHL(Op, DAG);
1988 case ISD::SHL_PARTS:
1989 return LowerShiftLeftParts(Op, DAG);
1990 case ISD::SRL_PARTS:
1991 case ISD::SRA_PARTS:
1992 return LowerShiftRightParts(Op, DAG);
1994 return LowerCTPOP(Op, DAG);
1995 case ISD::FCOPYSIGN:
1996 return LowerFCOPYSIGN(Op, DAG);
1998 return LowerVectorAND(Op, DAG);
2000 return LowerVectorOR(Op, DAG);
2002 return LowerXOR(Op, DAG);
2004 return LowerPREFETCH(Op, DAG);
2005 case ISD::SINT_TO_FP:
2006 case ISD::UINT_TO_FP:
2007 return LowerINT_TO_FP(Op, DAG);
2008 case ISD::FP_TO_SINT:
2009 case ISD::FP_TO_UINT:
2010 return LowerFP_TO_INT(Op, DAG);
2012 return LowerFSINCOS(Op, DAG);
2016 /// getFunctionAlignment - Return the Log2 alignment of this function.
2017 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
2021 //===----------------------------------------------------------------------===//
2022 // Calling Convention Implementation
2023 //===----------------------------------------------------------------------===//
2025 #include "ARM64GenCallingConv.inc"
2027 /// Selects the correct CCAssignFn for a the given CallingConvention
2029 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2030 bool IsVarArg) const {
2033 llvm_unreachable("Unsupported calling convention.");
2034 case CallingConv::WebKit_JS:
2035 return CC_ARM64_WebKit_JS;
2036 case CallingConv::C:
2037 case CallingConv::Fast:
2038 if (!Subtarget->isTargetDarwin())
2039 return CC_ARM64_AAPCS;
2040 return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
2044 SDValue ARM64TargetLowering::LowerFormalArguments(
2045 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2046 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2047 SmallVectorImpl<SDValue> &InVals) const {
2048 MachineFunction &MF = DAG.getMachineFunction();
2049 MachineFrameInfo *MFI = MF.getFrameInfo();
2051 // Assign locations to all of the incoming arguments.
2052 SmallVector<CCValAssign, 16> ArgLocs;
2053 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2054 getTargetMachine(), ArgLocs, *DAG.getContext());
2056 // At this point, Ins[].VT may already be promoted to i32. To correctly
2057 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2058 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2059 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2060 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2062 unsigned NumArgs = Ins.size();
2063 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2064 unsigned CurArgIdx = 0;
2065 for (unsigned i = 0; i != NumArgs; ++i) {
2066 MVT ValVT = Ins[i].VT;
2067 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
2068 CurArgIdx = Ins[i].OrigArgIndex;
2070 // Get type of the original argument.
2071 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2072 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2073 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2075 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2077 else if (ActualMVT == MVT::i16)
2080 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2082 AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2083 assert(!Res && "Call operand has unhandled type");
2087 SmallVector<SDValue, 16> ArgValues;
2088 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2089 CCValAssign &VA = ArgLocs[i];
2091 // Arguments stored in registers.
2092 if (VA.isRegLoc()) {
2093 EVT RegVT = VA.getLocVT();
2096 const TargetRegisterClass *RC;
2098 if (RegVT == MVT::i32)
2099 RC = &ARM64::GPR32RegClass;
2100 else if (RegVT == MVT::i64)
2101 RC = &ARM64::GPR64RegClass;
2102 else if (RegVT == MVT::f32)
2103 RC = &ARM64::FPR32RegClass;
2104 else if (RegVT == MVT::f64 || RegVT == MVT::v1i64 ||
2105 RegVT == MVT::v1f64 || RegVT == MVT::v2i32 ||
2106 RegVT == MVT::v4i16 || RegVT == MVT::v8i8)
2107 RC = &ARM64::FPR64RegClass;
2108 else if (RegVT == MVT::v2i64 || RegVT == MVT::v4i32 ||
2109 RegVT == MVT::v8i16 || RegVT == MVT::v16i8)
2110 RC = &ARM64::FPR128RegClass;
2112 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2114 // Transform the arguments in physical registers into virtual ones.
2115 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2116 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2118 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2119 // to 64 bits. Insert an assert[sz]ext to capture this, then
2120 // truncate to the right size.
2121 switch (VA.getLocInfo()) {
2123 llvm_unreachable("Unknown loc info!");
2124 case CCValAssign::Full:
2126 case CCValAssign::BCvt:
2127 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2129 case CCValAssign::SExt:
2130 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2131 DAG.getValueType(VA.getValVT()));
2132 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
2134 case CCValAssign::ZExt:
2135 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2136 DAG.getValueType(VA.getValVT()));
2137 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
2141 InVals.push_back(ArgValue);
2143 } else { // VA.isRegLoc()
2144 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2145 unsigned ArgOffset = VA.getLocMemOffset();
2146 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
2147 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
2149 // Create load nodes to retrieve arguments from the stack.
2150 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2151 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
2152 MachinePointerInfo::getFixedStack(FI), false,
2159 if (!Subtarget->isTargetDarwin()) {
2160 // The AAPCS variadic function ABI is identical to the non-variadic
2161 // one. As a result there may be more arguments in registers and we should
2162 // save them for future reference.
2163 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2166 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
2167 // This will point to the next argument passed via stack.
2168 unsigned StackOffset = CCInfo.getNextStackOffset();
2169 // We currently pass all varargs at 8-byte alignment.
2170 StackOffset = ((StackOffset + 7) & ~7);
2171 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2177 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2178 SelectionDAG &DAG, SDLoc DL,
2179 SDValue &Chain) const {
2180 MachineFunction &MF = DAG.getMachineFunction();
2181 MachineFrameInfo *MFI = MF.getFrameInfo();
2182 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
2184 SmallVector<SDValue, 8> MemOps;
2186 static const uint16_t GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
2187 ARM64::X3, ARM64::X4, ARM64::X5,
2188 ARM64::X6, ARM64::X7 };
2189 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2190 unsigned FirstVariadicGPR =
2191 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
2193 static const uint16_t FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
2194 ARM64::Q3, ARM64::Q4, ARM64::Q5,
2195 ARM64::Q6, ARM64::Q7 };
2196 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2197 unsigned FirstVariadicFPR =
2198 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
2200 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2202 if (GPRSaveSize != 0) {
2203 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2205 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2207 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2208 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
2209 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2211 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2212 MachinePointerInfo::getStack(i * 8), false, false, 0);
2213 MemOps.push_back(Store);
2214 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2215 DAG.getConstant(8, getPointerTy()));
2219 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2221 if (FPRSaveSize != 0) {
2222 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2224 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2226 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2227 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
2228 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
2230 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2231 MachinePointerInfo::getStack(i * 16), false, false, 0);
2232 MemOps.push_back(Store);
2233 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2234 DAG.getConstant(16, getPointerTy()));
2238 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2239 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2240 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2241 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2243 if (!MemOps.empty()) {
2244 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2249 /// LowerCallResult - Lower the result values of a call into the
2250 /// appropriate copies out of appropriate physical registers.
2251 SDValue ARM64TargetLowering::LowerCallResult(
2252 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2253 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2254 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2255 SDValue ThisVal) const {
2256 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2257 : RetCC_ARM64_AAPCS;
2258 // Assign locations to each value returned by this call.
2259 SmallVector<CCValAssign, 16> RVLocs;
2260 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2261 getTargetMachine(), RVLocs, *DAG.getContext());
2262 CCInfo.AnalyzeCallResult(Ins, RetCC);
2264 // Copy all of the result registers out of their specified physreg.
2265 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2266 CCValAssign VA = RVLocs[i];
2268 // Pass 'this' value directly from the argument to return value, to avoid
2269 // reg unit interference
2270 if (i == 0 && isThisReturn) {
2271 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2272 "unexpected return calling convention register assignment");
2273 InVals.push_back(ThisVal);
2278 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2279 Chain = Val.getValue(1);
2280 InFlag = Val.getValue(2);
2282 switch (VA.getLocInfo()) {
2284 llvm_unreachable("Unknown loc info!");
2285 case CCValAssign::Full:
2287 case CCValAssign::BCvt:
2288 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2292 InVals.push_back(Val);
2298 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
2299 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2300 bool isCalleeStructRet, bool isCallerStructRet,
2301 const SmallVectorImpl<ISD::OutputArg> &Outs,
2302 const SmallVectorImpl<SDValue> &OutVals,
2303 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2304 // Look for obvious safe cases to perform tail call optimization that do not
2305 // require ABI changes. This is what gcc calls sibcall.
2307 // Do not sibcall optimize vararg calls unless the call site is not passing
2309 if (isVarArg && !Outs.empty())
2312 // Also avoid sibcall optimization if either caller or callee uses struct
2313 // return semantics.
2314 if (isCalleeStructRet || isCallerStructRet)
2317 // Note that currently ARM64 "C" calling convention and "Fast" calling
2318 // convention are compatible. If/when that ever changes, we'll need to
2319 // add checks here to make sure any interactions are OK.
2321 // If the callee takes no arguments then go on to check the results of the
2323 if (!Outs.empty()) {
2324 // Check if stack adjustment is needed. For now, do not do this if any
2325 // argument is passed on the stack.
2326 SmallVector<CCValAssign, 16> ArgLocs;
2327 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2328 getTargetMachine(), ArgLocs, *DAG.getContext());
2329 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
2330 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2331 if (CCInfo.getNextStackOffset()) {
2332 // Check if the arguments are already laid out in the right way as
2333 // the caller's fixed stack objects.
2334 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2335 ++i, ++realArgIdx) {
2336 CCValAssign &VA = ArgLocs[i];
2337 if (VA.getLocInfo() == CCValAssign::Indirect)
2339 if (VA.needsCustom()) {
2340 // Just don't handle anything that needs custom adjustments for now.
2341 // If need be, we can revisit later, but we shouldn't ever end up
2344 } else if (!VA.isRegLoc()) {
2345 // Likewise, don't try to handle stack based arguments for the
2355 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2356 /// and add input and output parameter nodes.
2357 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2358 SmallVectorImpl<SDValue> &InVals) const {
2359 SelectionDAG &DAG = CLI.DAG;
2361 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2362 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2363 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2364 SDValue Chain = CLI.Chain;
2365 SDValue Callee = CLI.Callee;
2366 bool &IsTailCall = CLI.IsTailCall;
2367 CallingConv::ID CallConv = CLI.CallConv;
2368 bool IsVarArg = CLI.IsVarArg;
2370 MachineFunction &MF = DAG.getMachineFunction();
2371 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2372 bool IsThisReturn = false;
2374 // If tail calls are explicitly disabled, make sure not to use them.
2375 if (!EnableARM64TailCalls)
2379 // Check if it's really possible to do a tail call.
2380 IsTailCall = isEligibleForTailCallOptimization(
2381 Callee, CallConv, IsVarArg, IsStructRet,
2382 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2383 // We don't support GuaranteedTailCallOpt, only automatically
2384 // detected sibcalls.
2385 // FIXME: Re-evaluate. Is this true? Should it be true?
2390 // Analyze operands of the call, assigning locations to each operand.
2391 SmallVector<CCValAssign, 16> ArgLocs;
2392 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2393 getTargetMachine(), ArgLocs, *DAG.getContext());
2396 // Handle fixed and variable vector arguments differently.
2397 // Variable vector arguments always go into memory.
2398 unsigned NumArgs = Outs.size();
2400 for (unsigned i = 0; i != NumArgs; ++i) {
2401 MVT ArgVT = Outs[i].VT;
2402 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2403 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2404 /*IsVarArg=*/ !Outs[i].IsFixed);
2405 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2406 assert(!Res && "Call operand has unhandled type");
2410 // At this point, Outs[].VT may already be promoted to i32. To correctly
2411 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2412 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2413 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2414 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2416 unsigned NumArgs = Outs.size();
2417 for (unsigned i = 0; i != NumArgs; ++i) {
2418 MVT ValVT = Outs[i].VT;
2419 // Get type of the original argument.
2420 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
2421 /*AllowUnknown*/ true);
2422 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2423 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2424 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2426 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2428 else if (ActualMVT == MVT::i16)
2431 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2432 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
2433 assert(!Res && "Call operand has unhandled type");
2438 // Get a count of how many bytes are to be pushed on the stack.
2439 unsigned NumBytes = CCInfo.getNextStackOffset();
2441 // Adjust the stack pointer for the new arguments...
2442 // These operations are automatically eliminated by the prolog/epilog pass
2445 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2447 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
2449 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2450 SmallVector<SDValue, 8> MemOpChains;
2452 // Walk the register/memloc assignments, inserting copies/loads.
2453 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2454 ++i, ++realArgIdx) {
2455 CCValAssign &VA = ArgLocs[i];
2456 SDValue Arg = OutVals[realArgIdx];
2457 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2459 // Promote the value if needed.
2460 switch (VA.getLocInfo()) {
2462 llvm_unreachable("Unknown loc info!");
2463 case CCValAssign::Full:
2465 case CCValAssign::SExt:
2466 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2468 case CCValAssign::ZExt:
2469 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2471 case CCValAssign::AExt:
2472 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2474 case CCValAssign::BCvt:
2475 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2477 case CCValAssign::FPExt:
2478 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2482 if (VA.isRegLoc()) {
2483 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2484 assert(VA.getLocVT() == MVT::i64 &&
2485 "unexpected calling convention register assignment");
2486 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2487 "unexpected use of 'returned'");
2488 IsThisReturn = true;
2490 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2492 assert(VA.isMemLoc());
2493 // There's no reason we can't support stack args w/ tailcall, but
2494 // we currently don't, so assert if we see one.
2495 assert(!IsTailCall && "stack argument with tail call!?");
2496 unsigned LocMemOffset = VA.getLocMemOffset();
2497 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2498 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2500 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2501 // promoted to a legal register type i32, we should truncate Arg back to
2503 if (Arg.getValueType().isSimple() &&
2504 Arg.getValueType().getSimpleVT() == MVT::i32 &&
2505 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2506 VA.getLocVT() == MVT::i16))
2507 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2509 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2510 MachinePointerInfo::getStack(LocMemOffset),
2512 MemOpChains.push_back(Store);
2516 if (!MemOpChains.empty())
2517 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOpChains[0],
2518 MemOpChains.size());
2520 // Build a sequence of copy-to-reg nodes chained together with token chain
2521 // and flag operands which copy the outgoing args into the appropriate regs.
2523 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2524 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2525 RegsToPass[i].second, InFlag);
2526 InFlag = Chain.getValue(1);
2529 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2530 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2531 // node so that legalize doesn't hack it.
2532 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2533 Subtarget->isTargetMachO()) {
2534 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2535 const GlobalValue *GV = G->getGlobal();
2536 bool InternalLinkage = GV->hasInternalLinkage();
2537 if (InternalLinkage)
2538 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2540 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2542 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2544 } else if (ExternalSymbolSDNode *S =
2545 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2546 const char *Sym = S->getSymbol();
2548 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2549 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2551 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2552 const GlobalValue *GV = G->getGlobal();
2553 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2554 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2555 const char *Sym = S->getSymbol();
2556 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2559 std::vector<SDValue> Ops;
2560 Ops.push_back(Chain);
2561 Ops.push_back(Callee);
2563 // Add argument registers to the end of the list so that they are known live
2565 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2566 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2567 RegsToPass[i].second.getValueType()));
2569 // Add a register mask operand representing the call-preserved registers.
2570 const uint32_t *Mask;
2571 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2572 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2574 // For 'this' returns, use the X0-preserving mask if applicable
2575 Mask = ARI->getThisReturnPreservedMask(CallConv);
2577 IsThisReturn = false;
2578 Mask = ARI->getCallPreservedMask(CallConv);
2581 Mask = ARI->getCallPreservedMask(CallConv);
2583 assert(Mask && "Missing call preserved mask for calling convention");
2584 Ops.push_back(DAG.getRegisterMask(Mask));
2586 if (InFlag.getNode())
2587 Ops.push_back(InFlag);
2589 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2591 // If we're doing a tall call, use a TC_RETURN here rather than an
2592 // actual call instruction.
2594 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, &Ops[0], Ops.size());
2596 // Returns a chain and a flag for retval copy to use.
2597 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
2598 InFlag = Chain.getValue(1);
2600 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2601 DAG.getIntPtrConstant(0, true), InFlag, DL);
2603 InFlag = Chain.getValue(1);
2605 // Handle result values, copying them out of physregs into vregs that we
2607 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2608 InVals, IsThisReturn,
2609 IsThisReturn ? OutVals[0] : SDValue());
2612 bool ARM64TargetLowering::CanLowerReturn(
2613 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2614 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2615 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2616 : RetCC_ARM64_AAPCS;
2617 SmallVector<CCValAssign, 16> RVLocs;
2618 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2619 return CCInfo.CheckReturn(Outs, RetCC);
2623 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2625 const SmallVectorImpl<ISD::OutputArg> &Outs,
2626 const SmallVectorImpl<SDValue> &OutVals,
2627 SDLoc DL, SelectionDAG &DAG) const {
2628 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2629 : RetCC_ARM64_AAPCS;
2630 SmallVector<CCValAssign, 16> RVLocs;
2631 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2632 getTargetMachine(), RVLocs, *DAG.getContext());
2633 CCInfo.AnalyzeReturn(Outs, RetCC);
2635 // Copy the result values into the output registers.
2637 SmallVector<SDValue, 4> RetOps(1, Chain);
2638 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2639 ++i, ++realRVLocIdx) {
2640 CCValAssign &VA = RVLocs[i];
2641 assert(VA.isRegLoc() && "Can only return in registers!");
2642 SDValue Arg = OutVals[realRVLocIdx];
2644 switch (VA.getLocInfo()) {
2646 llvm_unreachable("Unknown loc info!");
2647 case CCValAssign::Full:
2649 case CCValAssign::BCvt:
2650 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2654 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2655 Flag = Chain.getValue(1);
2656 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2659 RetOps[0] = Chain; // Update chain.
2661 // Add the flag if we have it.
2663 RetOps.push_back(Flag);
2665 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, &RetOps[0],
2669 //===----------------------------------------------------------------------===//
2670 // Other Lowering Code
2671 //===----------------------------------------------------------------------===//
2673 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2674 SelectionDAG &DAG) const {
2675 EVT PtrVT = getPointerTy();
2677 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2678 unsigned char OpFlags =
2679 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2681 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2682 "unexpected offset in global node");
2684 // This also catched the large code model case for Darwin.
2685 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2686 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2687 // FIXME: Once remat is capable of dealing with instructions with register
2688 // operands, expand this into two nodes instead of using a wrapper node.
2689 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2692 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2693 const unsigned char MO_NC = ARM64II::MO_NC;
2695 ARM64ISD::WrapperLarge, DL, PtrVT,
2696 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2697 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2698 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2699 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2701 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2702 // the only correct model on Darwin.
2703 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2704 OpFlags | ARM64II::MO_PAGE);
2705 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2706 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2708 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2709 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2713 /// \brief Convert a TLS address reference into the correct sequence of loads
2714 /// and calls to compute the variable's address (for Darwin, currently) and
2715 /// return an SDValue containing the final node.
2717 /// Darwin only has one TLS scheme which must be capable of dealing with the
2718 /// fully general situation, in the worst case. This means:
2719 /// + "extern __thread" declaration.
2720 /// + Defined in a possibly unknown dynamic library.
2722 /// The general system is that each __thread variable has a [3 x i64] descriptor
2723 /// which contains information used by the runtime to calculate the address. The
2724 /// only part of this the compiler needs to know about is the first xword, which
2725 /// contains a function pointer that must be called with the address of the
2726 /// entire descriptor in "x0".
2728 /// Since this descriptor may be in a different unit, in general even the
2729 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2731 /// adrp x0, _var@TLVPPAGE
2732 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2733 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2734 /// ; the function pointer
2735 /// blr x1 ; Uses descriptor address in x0
2736 /// ; Address of _var is now in x0.
2738 /// If the address of _var's descriptor *is* known to the linker, then it can
2739 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2740 /// a slight efficiency gain.
2742 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2743 SelectionDAG &DAG) const {
2744 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2747 MVT PtrVT = getPointerTy();
2748 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2751 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2752 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2754 // The first entry in the descriptor is a function pointer that we must call
2755 // to obtain the address of the variable.
2756 SDValue Chain = DAG.getEntryNode();
2757 SDValue FuncTLVGet =
2758 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2759 false, true, true, 8);
2760 Chain = FuncTLVGet.getValue(1);
2762 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2763 MFI->setAdjustsStack(true);
2765 // TLS calls preserve all registers except those that absolutely must be
2766 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2768 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2769 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2770 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2772 // Finally, we can make the call. This is just a degenerate version of a
2773 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2774 // the address of the variable in this thread.
2775 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2776 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2777 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2778 DAG.getRegisterMask(Mask), Chain.getValue(1));
2779 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2782 /// When accessing thread-local variables under either the general-dynamic or
2783 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2784 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2785 /// is a function pointer to carry out the resolution. This function takes the
2786 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2787 /// other registers (except LR, CPSR) are preserved.
2789 /// Thus, the ideal call sequence on AArch64 is:
2791 /// adrp x0, :tlsdesc:thread_var
2792 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2793 /// add x0, x0, :tlsdesc_lo12:thread_var
2794 /// .tlsdesccall thread_var
2796 /// (TPIDR_EL0 offset now in x0).
2798 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2799 /// relocation to help the linker relax this sequence if it turns out to be too
2802 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2804 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2805 SDValue DescAddr, SDLoc DL,
2806 SelectionDAG &DAG) const {
2807 EVT PtrVT = getPointerTy();
2809 // The function we need to call is simply the first entry in the GOT for this
2810 // descriptor, load it in preparation.
2811 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2813 // TLS calls preserve all registers except those that absolutely must be
2814 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2816 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2817 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2818 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2820 // The function takes only one argument: the address of the descriptor itself
2822 SDValue Glue, Chain;
2823 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2824 Glue = Chain.getValue(1);
2826 // We're now ready to populate the argument list, as with a normal call:
2827 SmallVector<SDValue, 6> Ops;
2828 Ops.push_back(Chain);
2829 Ops.push_back(Func);
2830 Ops.push_back(SymAddr);
2831 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2832 Ops.push_back(DAG.getRegisterMask(Mask));
2833 Ops.push_back(Glue);
2835 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2836 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, &Ops[0], Ops.size());
2837 Glue = Chain.getValue(1);
2839 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2842 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2843 SelectionDAG &DAG) const {
2844 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2845 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2846 "ELF TLS only supported in small memory model");
2847 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2849 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2852 EVT PtrVT = getPointerTy();
2854 const GlobalValue *GV = GA->getGlobal();
2856 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2858 if (Model == TLSModel::LocalExec) {
2859 SDValue HiVar = DAG.getTargetGlobalAddress(
2860 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2861 SDValue LoVar = DAG.getTargetGlobalAddress(
2862 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2864 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2865 DAG.getTargetConstant(16, MVT::i32)),
2867 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2868 DAG.getTargetConstant(0, MVT::i32)),
2870 } else if (Model == TLSModel::InitialExec) {
2871 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2872 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2873 } else if (Model == TLSModel::LocalDynamic) {
2874 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2875 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2876 // the beginning of the module's TLS region, followed by a DTPREL offset
2879 // These accesses will need deduplicating if there's more than one.
2880 ARM64FunctionInfo *MFI =
2881 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2882 MFI->incNumLocalDynamicTLSAccesses();
2884 // Accesses used in this sequence go via the TLS descriptor which lives in
2885 // the GOT. Prepare an address we can use to handle this.
2886 SDValue HiDesc = DAG.getTargetExternalSymbol(
2887 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2888 SDValue LoDesc = DAG.getTargetExternalSymbol(
2889 "_TLS_MODULE_BASE_", PtrVT,
2890 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2892 // First argument to the descriptor call is the address of the descriptor
2894 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2895 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2897 // The call needs a relocation too for linker relaxation. It doesn't make
2898 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2900 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2903 // Now we can calculate the offset from TPIDR_EL0 to this module's
2904 // thread-local area.
2905 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2907 // Now use :dtprel_whatever: operations to calculate this variable's offset
2908 // in its thread-storage area.
2909 SDValue HiVar = DAG.getTargetGlobalAddress(
2910 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2911 SDValue LoVar = DAG.getTargetGlobalAddress(
2912 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2915 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2916 DAG.getTargetConstant(16, MVT::i32)),
2918 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2919 DAG.getTargetConstant(0, MVT::i32)),
2922 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2923 } else if (Model == TLSModel::GeneralDynamic) {
2924 // Accesses used in this sequence go via the TLS descriptor which lives in
2925 // the GOT. Prepare an address we can use to handle this.
2926 SDValue HiDesc = DAG.getTargetGlobalAddress(
2927 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2928 SDValue LoDesc = DAG.getTargetGlobalAddress(
2930 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2932 // First argument to the descriptor call is the address of the descriptor
2934 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2935 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2937 // The call needs a relocation too for linker relaxation. It doesn't make
2938 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2941 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2943 // Finally we can make a call to calculate the offset from tpidr_el0.
2944 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2946 llvm_unreachable("Unsupported ELF TLS access model");
2948 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2951 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2952 SelectionDAG &DAG) const {
2953 if (Subtarget->isTargetDarwin())
2954 return LowerDarwinGlobalTLSAddress(Op, DAG);
2955 else if (Subtarget->isTargetELF())
2956 return LowerELFGlobalTLSAddress(Op, DAG);
2958 llvm_unreachable("Unexpected platform trying to use TLS");
2960 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2961 SDValue Chain = Op.getOperand(0);
2962 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2963 SDValue LHS = Op.getOperand(2);
2964 SDValue RHS = Op.getOperand(3);
2965 SDValue Dest = Op.getOperand(4);
2968 // Handle f128 first, since lowering it will result in comparing the return
2969 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2970 // is expecting to deal with.
2971 if (LHS.getValueType() == MVT::f128) {
2972 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2974 // If softenSetCCOperands returned a scalar, we need to compare the result
2975 // against zero to select between true and false values.
2976 if (RHS.getNode() == 0) {
2977 RHS = DAG.getConstant(0, LHS.getValueType());
2982 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2984 unsigned Opc = LHS.getOpcode();
2985 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2986 cast<ConstantSDNode>(RHS)->isOne() &&
2987 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2988 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2989 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2990 "Unexpected condition code.");
2991 // Only lower legal XALUO ops.
2992 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2995 // The actual operation with overflow check.
2996 ARM64CC::CondCode OFCC;
2997 SDValue Value, Overflow;
2998 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
3000 if (CC == ISD::SETNE)
3001 OFCC = getInvertedCondCode(OFCC);
3002 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3004 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
3008 if (LHS.getValueType().isInteger()) {
3009 assert((LHS.getValueType() == RHS.getValueType()) &&
3010 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3012 // If the RHS of the comparison is zero, we can potentially fold this
3013 // to a specialized branch.
3014 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3015 if (RHSC && RHSC->getZExtValue() == 0) {
3016 if (CC == ISD::SETEQ) {
3017 // See if we can use a TBZ to fold in an AND as well.
3018 // TBZ has a smaller branch displacement than CBZ. If the offset is
3019 // out of bounds, a late MI-layer pass rewrites branches.
3020 // 403.gcc is an example that hits this case.
3021 if (LHS.getOpcode() == ISD::AND &&
3022 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3023 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3024 SDValue Test = LHS.getOperand(0);
3025 uint64_t Mask = LHS.getConstantOperandVal(1);
3027 // TBZ only operates on i64's, but the ext should be free.
3028 if (Test.getValueType() == MVT::i32)
3029 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
3031 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
3032 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3035 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3036 } else if (CC == ISD::SETNE) {
3037 // See if we can use a TBZ to fold in an AND as well.
3038 // TBZ has a smaller branch displacement than CBZ. If the offset is
3039 // out of bounds, a late MI-layer pass rewrites branches.
3040 // 403.gcc is an example that hits this case.
3041 if (LHS.getOpcode() == ISD::AND &&
3042 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3043 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3044 SDValue Test = LHS.getOperand(0);
3045 uint64_t Mask = LHS.getConstantOperandVal(1);
3047 // TBNZ only operates on i64's, but the ext should be free.
3048 if (Test.getValueType() == MVT::i32)
3049 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
3051 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3052 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3055 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3060 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3061 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3065 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3067 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3068 // clean. Some of them require two branches to implement.
3069 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3070 ARM64CC::CondCode CC1, CC2;
3071 changeFPCCToARM64CC(CC, CC1, CC2);
3072 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3074 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3075 if (CC2 != ARM64CC::AL) {
3076 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3077 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3084 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3085 SelectionDAG &DAG) const {
3086 EVT VT = Op.getValueType();
3089 SDValue In1 = Op.getOperand(0);
3090 SDValue In2 = Op.getOperand(1);
3091 EVT SrcVT = In2.getValueType();
3093 if (SrcVT == MVT::f32 && VT == MVT::f64)
3094 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3095 else if (SrcVT == MVT::f64 && VT == MVT::f32)
3096 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3098 // FIXME: Src type is different, bail out for now. Can VT really be a
3105 SDValue EltMask, VecVal1, VecVal2;
3106 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3109 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
3111 if (!VT.isVector()) {
3112 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
3113 DAG.getUNDEF(VecVT), In1);
3114 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
3115 DAG.getUNDEF(VecVT), In2);
3117 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3118 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3120 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3124 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3125 // immediate moves cannot materialize that in a single instruction for
3126 // 64-bit elements. Instead, materialize zero and then negate it.
3127 EltMask = DAG.getConstant(0, EltVT);
3129 if (!VT.isVector()) {
3130 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
3131 DAG.getUNDEF(VecVT), In1);
3132 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
3133 DAG.getUNDEF(VecVT), In2);
3135 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3136 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3139 llvm_unreachable("Invalid type for copysign!");
3142 std::vector<SDValue> BuildVectorOps;
3143 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
3144 BuildVectorOps.push_back(EltMask);
3146 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT,
3147 &BuildVectorOps[0], BuildVectorOps.size());
3149 // If we couldn't materialize the mask above, then the mask vector will be
3150 // the zero vector, and we need to negate it here.
3151 if (VT == MVT::f64 || VT == MVT::v2f64) {
3152 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3153 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3154 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3158 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3161 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
3162 else if (VT == MVT::f64)
3163 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
3165 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3168 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3169 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
3170 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
3173 // While there is no integer popcount instruction, it can
3174 // be more efficiently lowered to the following sequence that uses
3175 // AdvSIMD registers/instructions as long as the copies to/from
3176 // the AdvSIMD registers are cheap.
3177 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3178 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3179 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3180 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3181 SDValue Val = Op.getOperand(0);
3183 EVT VT = Op.getValueType();
3184 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
3187 if (VT == MVT::i32) {
3188 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
3190 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
3192 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3195 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
3196 SDValue UaddLV = DAG.getNode(
3197 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3198 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
3201 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3205 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3207 if (Op.getValueType().isVector())
3208 return LowerVSETCC(Op, DAG);
3210 SDValue LHS = Op.getOperand(0);
3211 SDValue RHS = Op.getOperand(1);
3212 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3215 // We chose ZeroOrOneBooleanContents, so use zero and one.
3216 EVT VT = Op.getValueType();
3217 SDValue TVal = DAG.getConstant(1, VT);
3218 SDValue FVal = DAG.getConstant(0, VT);
3220 // Handle f128 first, since one possible outcome is a normal integer
3221 // comparison which gets picked up by the next if statement.
3222 if (LHS.getValueType() == MVT::f128) {
3223 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3225 // If softenSetCCOperands returned a scalar, use it.
3226 if (RHS.getNode() == 0) {
3227 assert(LHS.getValueType() == Op.getValueType() &&
3228 "Unexpected setcc expansion!");
3233 if (LHS.getValueType().isInteger()) {
3236 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3238 // Note that we inverted the condition above, so we reverse the order of
3239 // the true and false operands here. This will allow the setcc to be
3240 // matched to a single CSINC instruction.
3241 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3244 // Now we know we're dealing with FP values.
3245 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3247 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3248 // and do the comparison.
3249 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3251 ARM64CC::CondCode CC1, CC2;
3252 changeFPCCToARM64CC(CC, CC1, CC2);
3253 if (CC2 == ARM64CC::AL) {
3254 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3255 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3257 // Note that we inverted the condition above, so we reverse the order of
3258 // the true and false operands here. This will allow the setcc to be
3259 // matched to a single CSINC instruction.
3260 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3262 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3263 // clean. Some of them require two CSELs to implement. As is in this case,
3264 // we emit the first CSEL and then emit a second using the output of the
3265 // first as the RHS. We're effectively OR'ing the two CC's together.
3267 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3268 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3269 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3271 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3272 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3276 /// A SELECT_CC operation is really some kind of max or min if both values being
3277 /// compared are, in some sense, equal to the results in either case. However,
3278 /// it is permissible to compare f32 values and produce directly extended f64
3281 /// Extending the comparison operands would also be allowed, but is less likely
3282 /// to happen in practice since their use is right here. Note that truncate
3283 /// operations would *not* be semantically equivalent.
3284 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3288 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3289 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3290 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3291 Result.getValueType() == MVT::f64) {
3293 APFloat CmpVal = CCmp->getValueAPF();
3294 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3295 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3298 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3301 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3302 SDValue CC = Op->getOperand(0);
3303 SDValue TVal = Op->getOperand(1);
3304 SDValue FVal = Op->getOperand(2);
3307 unsigned Opc = CC.getOpcode();
3308 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3310 if (CC.getResNo() == 1 &&
3311 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3312 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3313 // Only lower legal XALUO ops.
3314 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3317 ARM64CC::CondCode OFCC;
3318 SDValue Value, Overflow;
3319 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
3320 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3322 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
3326 if (CC.getOpcode() == ISD::SETCC)
3327 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3328 cast<CondCodeSDNode>(CC.getOperand(2))->get());
3330 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3334 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
3335 SelectionDAG &DAG) const {
3336 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3337 SDValue LHS = Op.getOperand(0);
3338 SDValue RHS = Op.getOperand(1);
3339 SDValue TVal = Op.getOperand(2);
3340 SDValue FVal = Op.getOperand(3);
3343 // Handle f128 first, because it will result in a comparison of some RTLIB
3344 // call result against zero.
3345 if (LHS.getValueType() == MVT::f128) {
3346 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3348 // If softenSetCCOperands returned a scalar, we need to compare the result
3349 // against zero to select between true and false values.
3350 if (RHS.getNode() == 0) {
3351 RHS = DAG.getConstant(0, LHS.getValueType());
3356 // Handle integers first.
3357 if (LHS.getValueType().isInteger()) {
3358 assert((LHS.getValueType() == RHS.getValueType()) &&
3359 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3361 unsigned Opcode = ARM64ISD::CSEL;
3363 // If both the TVal and the FVal are constants, see if we can swap them in
3364 // order to for a CSINV or CSINC out of them.
3365 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3366 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3368 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3369 std::swap(TVal, FVal);
3370 std::swap(CTVal, CFVal);
3371 CC = ISD::getSetCCInverse(CC, true);
3372 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3373 std::swap(TVal, FVal);
3374 std::swap(CTVal, CFVal);
3375 CC = ISD::getSetCCInverse(CC, true);
3376 } else if (TVal.getOpcode() == ISD::XOR) {
3377 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3378 // with a CSINV rather than a CSEL.
3379 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3381 if (CVal && CVal->isAllOnesValue()) {
3382 std::swap(TVal, FVal);
3383 std::swap(CTVal, CFVal);
3384 CC = ISD::getSetCCInverse(CC, true);
3386 } else if (TVal.getOpcode() == ISD::SUB) {
3387 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3388 // that we can match with a CSNEG rather than a CSEL.
3389 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3391 if (CVal && CVal->isNullValue()) {
3392 std::swap(TVal, FVal);
3393 std::swap(CTVal, CFVal);
3394 CC = ISD::getSetCCInverse(CC, true);
3396 } else if (CTVal && CFVal) {
3397 const int64_t TrueVal = CTVal->getSExtValue();
3398 const int64_t FalseVal = CFVal->getSExtValue();
3401 // If both TVal and FVal are constants, see if FVal is the
3402 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3403 // instead of a CSEL in that case.
3404 if (TrueVal == ~FalseVal) {
3405 Opcode = ARM64ISD::CSINV;
3406 } else if (TrueVal == -FalseVal) {
3407 Opcode = ARM64ISD::CSNEG;
3408 } else if (TVal.getValueType() == MVT::i32) {
3409 // If our operands are only 32-bit wide, make sure we use 32-bit
3410 // arithmetic for the check whether we can use CSINC. This ensures that
3411 // the addition in the check will wrap around properly in case there is
3412 // an overflow (which would not be the case if we do the check with
3413 // 64-bit arithmetic).
3414 const uint32_t TrueVal32 = CTVal->getZExtValue();
3415 const uint32_t FalseVal32 = CFVal->getZExtValue();
3417 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3418 Opcode = ARM64ISD::CSINC;
3420 if (TrueVal32 > FalseVal32) {
3424 // 64-bit check whether we can use CSINC.
3425 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3426 Opcode = ARM64ISD::CSINC;
3428 if (TrueVal > FalseVal) {
3433 // Swap TVal and FVal if necessary.
3435 std::swap(TVal, FVal);
3436 std::swap(CTVal, CFVal);
3437 CC = ISD::getSetCCInverse(CC, true);
3440 if (Opcode != ARM64ISD::CSEL) {
3441 // Drop FVal since we can get its value by simply inverting/negating
3448 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3450 EVT VT = Op.getValueType();
3451 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3454 // Now we know we're dealing with FP values.
3455 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3456 assert(LHS.getValueType() == RHS.getValueType());
3457 EVT VT = Op.getValueType();
3459 // Try to match this select into a max/min operation, which have dedicated
3460 // opcode in the instruction set.
3461 // NOTE: This is not correct in the presence of NaNs, so we only enable this
3463 if (getTargetMachine().Options.NoNaNsFPMath) {
3464 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3465 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3466 CC = ISD::getSetCCSwappedOperands(CC);
3467 std::swap(TVal, FVal);
3470 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3471 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3481 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3489 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3495 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3496 // and do the comparison.
3497 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3499 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3500 // clean. Some of them require two CSELs to implement.
3501 ARM64CC::CondCode CC1, CC2;
3502 changeFPCCToARM64CC(CC, CC1, CC2);
3503 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3504 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3506 // If we need a second CSEL, emit it, using the output of the first as the
3507 // RHS. We're effectively OR'ing the two CC's together.
3508 if (CC2 != ARM64CC::AL) {
3509 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3510 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3513 // Otherwise, return the output of the first CSEL.
3517 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3518 SelectionDAG &DAG) const {
3519 // Jump table entries as PC relative offsets. No additional tweaking
3520 // is necessary here. Just get the address of the jump table.
3521 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3522 EVT PtrVT = getPointerTy();
3525 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3526 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3527 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3528 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3529 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3532 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3533 SelectionDAG &DAG) const {
3534 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3535 EVT PtrVT = getPointerTy();
3538 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3539 // Use the GOT for the large code model on iOS.
3540 if (Subtarget->isTargetMachO()) {
3541 SDValue GotAddr = DAG.getTargetConstantPool(
3542 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3544 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3547 const unsigned char MO_NC = ARM64II::MO_NC;
3549 ARM64ISD::WrapperLarge, DL, PtrVT,
3550 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3551 CP->getOffset(), ARM64II::MO_G3),
3552 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3553 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3554 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3555 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3556 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3557 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3559 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3560 // ELF, the only valid one on Darwin.
3562 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3563 CP->getOffset(), ARM64II::MO_PAGE);
3564 SDValue Lo = DAG.getTargetConstantPool(
3565 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3566 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3568 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3569 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3573 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3574 SelectionDAG &DAG) const {
3575 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3576 EVT PtrVT = getPointerTy();
3578 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3579 !Subtarget->isTargetMachO()) {
3580 const unsigned char MO_NC = ARM64II::MO_NC;
3582 ARM64ISD::WrapperLarge, DL, PtrVT,
3583 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3584 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3585 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3586 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3588 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3589 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3591 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3592 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3596 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3597 SelectionDAG &DAG) const {
3598 ARM64FunctionInfo *FuncInfo =
3599 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3603 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3604 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3605 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3606 MachinePointerInfo(SV), false, false, 0);
3609 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3610 SelectionDAG &DAG) const {
3611 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3612 // Standard, section B.3.
3613 MachineFunction &MF = DAG.getMachineFunction();
3614 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3617 SDValue Chain = Op.getOperand(0);
3618 SDValue VAList = Op.getOperand(1);
3619 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3620 SmallVector<SDValue, 4> MemOps;
3622 // void *__stack at offset 0
3624 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3625 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3626 MachinePointerInfo(SV), false, false, 8));
3628 // void *__gr_top at offset 8
3629 int GPRSize = FuncInfo->getVarArgsGPRSize();
3631 SDValue GRTop, GRTopAddr;
3633 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3634 DAG.getConstant(8, getPointerTy()));
3636 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3637 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3638 DAG.getConstant(GPRSize, getPointerTy()));
3640 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3641 MachinePointerInfo(SV, 8), false, false, 8));
3644 // void *__vr_top at offset 16
3645 int FPRSize = FuncInfo->getVarArgsFPRSize();
3647 SDValue VRTop, VRTopAddr;
3648 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3649 DAG.getConstant(16, getPointerTy()));
3651 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3652 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3653 DAG.getConstant(FPRSize, getPointerTy()));
3655 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3656 MachinePointerInfo(SV, 16), false, false, 8));
3659 // int __gr_offs at offset 24
3660 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3661 DAG.getConstant(24, getPointerTy()));
3662 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3663 GROffsAddr, MachinePointerInfo(SV, 24), false,
3666 // int __vr_offs at offset 28
3667 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3668 DAG.getConstant(28, getPointerTy()));
3669 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3670 VROffsAddr, MachinePointerInfo(SV, 28), false,
3673 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
3677 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3678 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3679 : LowerAAPCS_VASTART(Op, DAG);
3682 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3683 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3685 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3686 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3687 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3689 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3690 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3691 8, false, false, MachinePointerInfo(DestSV),
3692 MachinePointerInfo(SrcSV));
3695 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3696 assert(Subtarget->isTargetDarwin() &&
3697 "automatic va_arg instruction only works on Darwin");
3699 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3700 EVT VT = Op.getValueType();
3702 SDValue Chain = Op.getOperand(0);
3703 SDValue Addr = Op.getOperand(1);
3704 unsigned Align = Op.getConstantOperandVal(3);
3706 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3707 MachinePointerInfo(V), false, false, false, 0);
3708 Chain = VAList.getValue(1);
3711 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3712 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3713 DAG.getConstant(Align - 1, getPointerTy()));
3714 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3715 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3718 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3719 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3721 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3722 // up to 64 bits. At the very least, we have to increase the striding of the
3723 // vaargs list to match this, and for FP values we need to introduce
3724 // FP_ROUND nodes as well.
3725 if (VT.isInteger() && !VT.isVector())
3727 bool NeedFPTrunc = false;
3728 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3733 // Increment the pointer, VAList, to the next vaarg
3734 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3735 DAG.getConstant(ArgSize, getPointerTy()));
3736 // Store the incremented VAList to the legalized pointer
3737 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3740 // Load the actual argument out of the pointer VAList
3742 // Load the value as an f64.
3743 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3744 MachinePointerInfo(), false, false, false, 0);
3745 // Round the value down to an f32.
3746 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3747 DAG.getIntPtrConstant(1));
3748 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3749 // Merge the rounded value with the chain output of the load.
3750 return DAG.getMergeValues(Ops, 2, DL);
3753 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3757 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3758 SelectionDAG &DAG) const {
3759 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3760 MFI->setFrameAddressIsTaken(true);
3762 EVT VT = Op.getValueType();
3764 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3765 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3767 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3768 MachinePointerInfo(), false, false, false, 0);
3772 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3773 SelectionDAG &DAG) const {
3774 MachineFunction &MF = DAG.getMachineFunction();
3775 MachineFrameInfo *MFI = MF.getFrameInfo();
3776 MFI->setReturnAddressIsTaken(true);
3778 EVT VT = Op.getValueType();
3780 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3782 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3783 SDValue Offset = DAG.getConstant(8, getPointerTy());
3784 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3785 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3786 MachinePointerInfo(), false, false, false, 0);
3789 // Return LR, which contains the return address. Mark it an implicit live-in.
3790 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3791 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3794 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3795 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3796 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3797 SelectionDAG &DAG) const {
3798 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3799 EVT VT = Op.getValueType();
3800 unsigned VTBits = VT.getSizeInBits();
3802 SDValue ShOpLo = Op.getOperand(0);
3803 SDValue ShOpHi = Op.getOperand(1);
3804 SDValue ShAmt = Op.getOperand(2);
3806 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3808 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3810 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3811 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3812 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3813 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3814 DAG.getConstant(VTBits, MVT::i64));
3815 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3818 emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64), dl, DAG);
3819 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3821 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3822 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3824 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3826 // ARM64 shifts larger than the register width are wrapped rather than
3827 // clamped, so we can't just emit "hi >> x".
3828 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3829 SDValue TrueValHi = Opc == ISD::SRA
3830 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3831 DAG.getConstant(VTBits - 1, MVT::i64))
3832 : DAG.getConstant(0, VT);
3834 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3836 SDValue Ops[2] = { Lo, Hi };
3837 return DAG.getMergeValues(Ops, 2, dl);
3840 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3841 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3842 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3843 SelectionDAG &DAG) const {
3844 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3845 EVT VT = Op.getValueType();
3846 unsigned VTBits = VT.getSizeInBits();
3848 SDValue ShOpLo = Op.getOperand(0);
3849 SDValue ShOpHi = Op.getOperand(1);
3850 SDValue ShAmt = Op.getOperand(2);
3853 assert(Op.getOpcode() == ISD::SHL_PARTS);
3854 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3855 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3856 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3857 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3858 DAG.getConstant(VTBits, MVT::i64));
3859 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3860 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3862 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3865 emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64), dl, DAG);
3866 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3867 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3869 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3870 // so we can't just emit "lo << a" if a is too big.
3871 SDValue TrueValLo = DAG.getConstant(0, VT);
3872 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3874 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3876 SDValue Ops[2] = { Lo, Hi };
3877 return DAG.getMergeValues(Ops, 2, dl);
3881 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3882 // The ARM64 target doesn't support folding offsets into global addresses.
3886 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3887 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3888 // FIXME: We should be able to handle f128 as well with a clever lowering.
3889 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3893 return ARM64_AM::getFP64Imm(Imm) != -1;
3894 else if (VT == MVT::f32)
3895 return ARM64_AM::getFP32Imm(Imm) != -1;
3899 //===----------------------------------------------------------------------===//
3900 // ARM64 Optimization Hooks
3901 //===----------------------------------------------------------------------===//
3903 //===----------------------------------------------------------------------===//
3904 // ARM64 Inline Assembly Support
3905 //===----------------------------------------------------------------------===//
3907 // Table of Constraints
3908 // TODO: This is the current set of constraints supported by ARM for the
3909 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3911 // r - A general register
3912 // w - An FP/SIMD register of some size in the range v0-v31
3913 // x - An FP/SIMD register of some size in the range v0-v15
3914 // I - Constant that can be used with an ADD instruction
3915 // J - Constant that can be used with a SUB instruction
3916 // K - Constant that can be used with a 32-bit logical instruction
3917 // L - Constant that can be used with a 64-bit logical instruction
3918 // M - Constant that can be used as a 32-bit MOV immediate
3919 // N - Constant that can be used as a 64-bit MOV immediate
3920 // Q - A memory reference with base register and no offset
3921 // S - A symbolic address
3922 // Y - Floating point constant zero
3923 // Z - Integer constant zero
3925 // Note that general register operands will be output using their 64-bit x
3926 // register name, whatever the size of the variable, unless the asm operand
3927 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3928 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3931 /// getConstraintType - Given a constraint letter, return the type of
3932 /// constraint it is for this target.
3933 ARM64TargetLowering::ConstraintType
3934 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3935 if (Constraint.size() == 1) {
3936 switch (Constraint[0]) {
3943 return C_RegisterClass;
3944 // An address with a single base register. Due to the way we
3945 // currently handle addresses it is the same as 'r'.
3950 return TargetLowering::getConstraintType(Constraint);
3953 /// Examine constraint type and operand type and determine a weight value.
3954 /// This object must already have been set up with the operand type
3955 /// and the current alternative constraint selected.
3956 TargetLowering::ConstraintWeight
3957 ARM64TargetLowering::getSingleConstraintMatchWeight(
3958 AsmOperandInfo &info, const char *constraint) const {
3959 ConstraintWeight weight = CW_Invalid;
3960 Value *CallOperandVal = info.CallOperandVal;
3961 // If we don't have a value, we can't do a match,
3962 // but allow it at the lowest weight.
3963 if (CallOperandVal == NULL)
3965 Type *type = CallOperandVal->getType();
3966 // Look at the constraint type.
3967 switch (*constraint) {
3969 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3973 if (type->isFloatingPointTy() || type->isVectorTy())
3974 weight = CW_Register;
3977 weight = CW_Constant;
3983 std::pair<unsigned, const TargetRegisterClass *>
3984 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3986 if (Constraint.size() == 1) {
3987 switch (Constraint[0]) {
3989 if (VT.getSizeInBits() == 64)
3990 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3991 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3994 return std::make_pair(0U, &ARM64::FPR32RegClass);
3995 if (VT.getSizeInBits() == 64)
3996 return std::make_pair(0U, &ARM64::FPR64RegClass);
3997 if (VT.getSizeInBits() == 128)
3998 return std::make_pair(0U, &ARM64::FPR128RegClass);
4000 // The instructions that this constraint is designed for can
4001 // only take 128-bit registers so just use that regclass.
4003 if (VT.getSizeInBits() == 128)
4004 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
4008 if (StringRef("{cc}").equals_lower(Constraint))
4009 return std::make_pair(unsigned(ARM64::CPSR), &ARM64::CCRRegClass);
4011 // Use the default implementation in TargetLowering to convert the register
4012 // constraint into a member of a register class.
4013 std::pair<unsigned, const TargetRegisterClass *> Res;
4014 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4016 // Not found as a standard register?
4017 if (Res.second == 0) {
4018 unsigned Size = Constraint.size();
4019 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4020 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4021 const std::string Reg =
4022 std::string(&Constraint[2], &Constraint[Size - 1]);
4023 int RegNo = atoi(Reg.c_str());
4024 if (RegNo >= 0 && RegNo <= 31) {
4025 // v0 - v31 are aliases of q0 - q31.
4026 // By default we'll emit v0-v31 for this unless there's a modifier where
4027 // we'll emit the correct register as well.
4028 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
4029 Res.second = &ARM64::FPR128RegClass;
4037 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4038 /// vector. If it is invalid, don't add anything to Ops.
4039 void ARM64TargetLowering::LowerAsmOperandForConstraint(
4040 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4041 SelectionDAG &DAG) const {
4042 SDValue Result(0, 0);
4044 // Currently only support length 1 constraints.
4045 if (Constraint.length() != 1)
4048 char ConstraintLetter = Constraint[0];
4049 switch (ConstraintLetter) {
4053 // This set of constraints deal with valid constants for various instructions.
4054 // Validate and return a target constant for them if we can.
4056 // 'z' maps to xzr or wzr so it needs an input of 0.
4057 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4058 if (!C || C->getZExtValue() != 0)
4061 if (Op.getValueType() == MVT::i64)
4062 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
4064 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
4074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4078 // Grab the value and do some validation.
4079 uint64_t CVal = C->getZExtValue();
4080 switch (ConstraintLetter) {
4081 // The I constraint applies only to simple ADD or SUB immediate operands:
4082 // i.e. 0 to 4095 with optional shift by 12
4083 // The J constraint applies only to ADD or SUB immediates that would be
4084 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4085 // instruction [or vice versa], in other words -1 to -4095 with optional
4086 // left shift by 12.
4088 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4092 uint64_t NVal = -C->getSExtValue();
4093 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
4097 // The K and L constraints apply *only* to logical immediates, including
4098 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4099 // been removed and MOV should be used). So these constraints have to
4100 // distinguish between bit patterns that are valid 32-bit or 64-bit
4101 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4102 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4105 if (ARM64_AM::isLogicalImmediate(CVal, 32))
4109 if (ARM64_AM::isLogicalImmediate(CVal, 64))
4112 // The M and N constraints are a superset of K and L respectively, for use
4113 // with the MOV (immediate) alias. As well as the logical immediates they
4114 // also match 32 or 64-bit immediates that can be loaded either using a
4115 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4116 // (M) or 64-bit 0x1234000000000000 (N) etc.
4117 // As a note some of this code is liberally stolen from the asm parser.
4119 if (!isUInt<32>(CVal))
4121 if (ARM64_AM::isLogicalImmediate(CVal, 32))
4123 if ((CVal & 0xFFFF) == CVal)
4125 if ((CVal & 0xFFFF0000ULL) == CVal)
4127 uint64_t NCVal = ~(uint32_t)CVal;
4128 if ((NCVal & 0xFFFFULL) == NCVal)
4130 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4135 if (ARM64_AM::isLogicalImmediate(CVal, 64))
4137 if ((CVal & 0xFFFFULL) == CVal)
4139 if ((CVal & 0xFFFF0000ULL) == CVal)
4141 if ((CVal & 0xFFFF00000000ULL) == CVal)
4143 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4145 uint64_t NCVal = ~CVal;
4146 if ((NCVal & 0xFFFFULL) == NCVal)
4148 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4150 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4152 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4160 // All assembler immediates are 64-bit integers.
4161 Result = DAG.getTargetConstant(CVal, MVT::i64);
4165 if (Result.getNode()) {
4166 Ops.push_back(Result);
4170 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4173 //===----------------------------------------------------------------------===//
4174 // ARM64 Advanced SIMD Support
4175 //===----------------------------------------------------------------------===//
4177 /// WidenVector - Given a value in the V64 register class, produce the
4178 /// equivalent value in the V128 register class.
4179 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4180 EVT VT = V64Reg.getValueType();
4181 unsigned NarrowSize = VT.getVectorNumElements();
4182 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4183 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4186 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4187 V64Reg, DAG.getConstant(0, MVT::i32));
4190 /// getExtFactor - Determine the adjustment factor for the position when
4191 /// generating an "extract from vector registers" instruction.
4192 static unsigned getExtFactor(SDValue &V) {
4193 EVT EltType = V.getValueType().getVectorElementType();
4194 return EltType.getSizeInBits() / 8;
4197 /// NarrowVector - Given a value in the V128 register class, produce the
4198 /// equivalent value in the V64 register class.
4199 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4200 EVT VT = V128Reg.getValueType();
4201 unsigned WideSize = VT.getVectorNumElements();
4202 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4203 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4206 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
4209 // Gather data to see if the operation can be modelled as a
4210 // shuffle in combination with VEXTs.
4211 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
4212 SelectionDAG &DAG) const {
4214 EVT VT = Op.getValueType();
4215 unsigned NumElts = VT.getVectorNumElements();
4217 SmallVector<SDValue, 2> SourceVecs;
4218 SmallVector<unsigned, 2> MinElts;
4219 SmallVector<unsigned, 2> MaxElts;
4221 for (unsigned i = 0; i < NumElts; ++i) {
4222 SDValue V = Op.getOperand(i);
4223 if (V.getOpcode() == ISD::UNDEF)
4225 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4226 // A shuffle can only come from building a vector from various
4227 // elements of other vectors.
4231 // Record this extraction against the appropriate vector if possible...
4232 SDValue SourceVec = V.getOperand(0);
4233 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4234 bool FoundSource = false;
4235 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4236 if (SourceVecs[j] == SourceVec) {
4237 if (MinElts[j] > EltNo)
4239 if (MaxElts[j] < EltNo)
4246 // Or record a new source if not...
4248 SourceVecs.push_back(SourceVec);
4249 MinElts.push_back(EltNo);
4250 MaxElts.push_back(EltNo);
4254 // Currently only do something sane when at most two source vectors
4256 if (SourceVecs.size() > 2)
4259 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4260 int VEXTOffsets[2] = { 0, 0 };
4262 // This loop extracts the usage patterns of the source vectors
4263 // and prepares appropriate SDValues for a shuffle if possible.
4264 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4265 if (SourceVecs[i].getValueType() == VT) {
4266 // No VEXT necessary
4267 ShuffleSrcs[i] = SourceVecs[i];
4270 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4271 // It probably isn't worth padding out a smaller vector just to
4272 // break it down again in a shuffle.
4276 // Don't attempt to extract subvectors from BUILD_VECTOR sources
4277 // that expand or trunc the original value.
4278 // TODO: We can try to bitcast and ANY_EXTEND the result but
4279 // we need to consider the cost of vector ANY_EXTEND, and the
4280 // legality of all the types.
4281 if (SourceVecs[i].getValueType().getVectorElementType() !=
4282 VT.getVectorElementType())
4285 // Since only 64-bit and 128-bit vectors are legal on ARM and
4286 // we've eliminated the other cases...
4287 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
4288 "unexpected vector sizes in ReconstructShuffle");
4290 if (MaxElts[i] - MinElts[i] >= NumElts) {
4291 // Span too large for a VEXT to cope
4295 if (MinElts[i] >= NumElts) {
4296 // The extraction can just take the second half
4297 VEXTOffsets[i] = NumElts;
4299 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
4300 DAG.getIntPtrConstant(NumElts));
4301 } else if (MaxElts[i] < NumElts) {
4302 // The extraction can just take the first half
4304 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4305 SourceVecs[i], DAG.getIntPtrConstant(0));
4307 // An actual VEXT is needed
4308 VEXTOffsets[i] = MinElts[i];
4309 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4310 SourceVecs[i], DAG.getIntPtrConstant(0));
4312 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
4313 DAG.getIntPtrConstant(NumElts));
4314 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
4315 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
4316 DAG.getConstant(Imm, MVT::i32));
4320 SmallVector<int, 8> Mask;
4322 for (unsigned i = 0; i < NumElts; ++i) {
4323 SDValue Entry = Op.getOperand(i);
4324 if (Entry.getOpcode() == ISD::UNDEF) {
4329 SDValue ExtractVec = Entry.getOperand(0);
4331 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
4332 if (ExtractVec == SourceVecs[0]) {
4333 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4335 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4339 // Final check before we try to produce nonsense...
4340 if (isShuffleMaskLegal(Mask, VT))
4341 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4347 // check if an EXT instruction can handle the shuffle mask when the
4348 // vector sources of the shuffle are the same.
4349 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4350 unsigned NumElts = VT.getVectorNumElements();
4352 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4358 // If this is a VEXT shuffle, the immediate value is the index of the first
4359 // element. The other shuffle indices must be the successive elements after
4361 unsigned ExpectedElt = Imm;
4362 for (unsigned i = 1; i < NumElts; ++i) {
4363 // Increment the expected index. If it wraps around, just follow it
4364 // back to index zero and keep going.
4366 if (ExpectedElt == NumElts)
4370 continue; // ignore UNDEF indices
4371 if (ExpectedElt != static_cast<unsigned>(M[i]))
4378 // check if an EXT instruction can handle the shuffle mask when the
4379 // vector sources of the shuffle are different.
4380 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4382 unsigned NumElts = VT.getVectorNumElements();
4385 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4391 // If this is a VEXT shuffle, the immediate value is the index of the first
4392 // element. The other shuffle indices must be the successive elements after
4394 unsigned ExpectedElt = Imm;
4395 for (unsigned i = 1; i < NumElts; ++i) {
4396 // Increment the expected index. If it wraps around, it may still be
4397 // a VEXT but the source vectors must be swapped.
4399 if (ExpectedElt == NumElts * 2) {
4405 continue; // ignore UNDEF indices
4406 if (ExpectedElt != static_cast<unsigned>(M[i]))
4410 // Adjust the index value if the source operands will be swapped.
4417 /// isREVMask - Check if a vector shuffle corresponds to a REV
4418 /// instruction with the specified blocksize. (The order of the elements
4419 /// within each block of the vector is reversed.)
4420 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4421 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4422 "Only possible block sizes for REV are: 16, 32, 64");
4424 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4428 unsigned NumElts = VT.getVectorNumElements();
4429 unsigned BlockElts = M[0] + 1;
4430 // If the first shuffle index is UNDEF, be optimistic.
4432 BlockElts = BlockSize / EltSz;
4434 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4437 for (unsigned i = 0; i < NumElts; ++i) {
4439 continue; // ignore UNDEF indices
4440 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4447 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4448 unsigned NumElts = VT.getVectorNumElements();
4449 WhichResult = (M[0] == 0 ? 0 : 1);
4450 unsigned Idx = WhichResult * NumElts / 2;
4451 for (unsigned i = 0; i != NumElts; i += 2) {
4452 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4453 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4461 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4462 unsigned NumElts = VT.getVectorNumElements();
4463 WhichResult = (M[0] == 0 ? 0 : 1);
4464 for (unsigned i = 0; i != NumElts; ++i) {
4466 continue; // ignore UNDEF indices
4467 if ((unsigned)M[i] != 2 * i + WhichResult)
4474 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4475 unsigned NumElts = VT.getVectorNumElements();
4476 WhichResult = (M[0] == 0 ? 0 : 1);
4477 for (unsigned i = 0; i < NumElts; i += 2) {
4478 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4479 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4485 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4486 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4487 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4488 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4489 unsigned NumElts = VT.getVectorNumElements();
4490 WhichResult = (M[0] == 0 ? 0 : 1);
4491 unsigned Idx = WhichResult * NumElts / 2;
4492 for (unsigned i = 0; i != NumElts; i += 2) {
4493 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4494 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4502 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4503 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4504 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4505 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4506 unsigned Half = VT.getVectorNumElements() / 2;
4507 WhichResult = (M[0] == 0 ? 0 : 1);
4508 for (unsigned j = 0; j != 2; ++j) {
4509 unsigned Idx = WhichResult;
4510 for (unsigned i = 0; i != Half; ++i) {
4511 int MIdx = M[i + j * Half];
4512 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4521 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4522 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4523 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4524 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4525 unsigned NumElts = VT.getVectorNumElements();
4526 WhichResult = (M[0] == 0 ? 0 : 1);
4527 for (unsigned i = 0; i < NumElts; i += 2) {
4528 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4529 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4535 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4536 /// the specified operations to build the shuffle.
4537 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4538 SDValue RHS, SelectionDAG &DAG,
4540 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4541 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4542 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4545 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4554 OP_VUZPL, // VUZP, left result
4555 OP_VUZPR, // VUZP, right result
4556 OP_VZIPL, // VZIP, left result
4557 OP_VZIPR, // VZIP, right result
4558 OP_VTRNL, // VTRN, left result
4559 OP_VTRNR // VTRN, right result
4562 if (OpNum == OP_COPY) {
4563 if (LHSID == (1 * 9 + 2) * 9 + 3)
4565 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4569 SDValue OpLHS, OpRHS;
4570 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4571 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4572 EVT VT = OpLHS.getValueType();
4576 llvm_unreachable("Unknown shuffle opcode!");
4578 // VREV divides the vector in half and swaps within the half.
4579 if (VT.getVectorElementType() == MVT::i32 ||
4580 VT.getVectorElementType() == MVT::f32)
4581 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4582 // vrev <4 x i16> -> REV32
4583 if (VT.getVectorElementType() == MVT::i16)
4584 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4585 // vrev <4 x i8> -> REV16
4586 assert(VT.getVectorElementType() == MVT::i8);
4587 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4592 EVT EltTy = VT.getVectorElementType();
4594 if (EltTy == MVT::i8)
4595 Opcode = ARM64ISD::DUPLANE8;
4596 else if (EltTy == MVT::i16)
4597 Opcode = ARM64ISD::DUPLANE16;
4598 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4599 Opcode = ARM64ISD::DUPLANE32;
4600 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4601 Opcode = ARM64ISD::DUPLANE64;
4603 llvm_unreachable("Invalid vector element type?");
4605 if (VT.getSizeInBits() == 64)
4606 OpLHS = WidenVector(OpLHS, DAG);
4607 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4608 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4613 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4614 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4615 DAG.getConstant(Imm, MVT::i32));
4618 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4620 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4622 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4624 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4626 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4628 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4632 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4633 SelectionDAG &DAG) {
4634 // Check to see if we can use the TBL instruction.
4635 SDValue V1 = Op.getOperand(0);
4636 SDValue V2 = Op.getOperand(1);
4639 EVT EltVT = Op.getValueType().getVectorElementType();
4640 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4642 SmallVector<SDValue, 8> TBLMask;
4643 for (int Val : ShuffleMask) {
4644 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4645 unsigned Offset = Byte + Val * BytesPerElt;
4646 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4650 MVT IndexVT = MVT::v8i8;
4651 unsigned IndexLen = 8;
4652 if (Op.getValueType().getSizeInBits() == 128) {
4653 IndexVT = MVT::v16i8;
4657 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4658 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4661 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4663 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4664 Shuffle = DAG.getNode(
4665 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4666 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4667 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4669 if (IndexLen == 8) {
4670 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4671 Shuffle = DAG.getNode(
4672 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4673 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4674 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4676 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4677 // cannot currently represent the register constraints on the input
4679 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4680 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4681 // &TBLMask[0], IndexLen));
4682 Shuffle = DAG.getNode(
4683 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4684 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4685 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4688 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4691 static unsigned getDUPLANEOp(EVT EltType) {
4692 if (EltType == MVT::i8)
4693 return ARM64ISD::DUPLANE8;
4694 if (EltType == MVT::i16)
4695 return ARM64ISD::DUPLANE16;
4696 if (EltType == MVT::i32 || EltType == MVT::f32)
4697 return ARM64ISD::DUPLANE32;
4698 if (EltType == MVT::i64 || EltType == MVT::f64)
4699 return ARM64ISD::DUPLANE64;
4701 llvm_unreachable("Invalid vector element type?");
4704 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4705 SelectionDAG &DAG) const {
4707 EVT VT = Op.getValueType();
4709 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4711 // Convert shuffles that are directly supported on NEON to target-specific
4712 // DAG nodes, instead of keeping them as shuffles and matching them again
4713 // during code selection. This is more efficient and avoids the possibility
4714 // of inconsistencies between legalization and selection.
4715 ArrayRef<int> ShuffleMask = SVN->getMask();
4717 SDValue V1 = Op.getOperand(0);
4718 SDValue V2 = Op.getOperand(1);
4720 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4721 V1.getValueType().getSimpleVT())) {
4722 int Lane = SVN->getSplatIndex();
4723 // If this is undef splat, generate it via "just" vdup, if possible.
4727 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4728 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4730 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4731 // constant. If so, we can just reference the lane's definition directly.
4732 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4733 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4734 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4736 // Otherwise, duplicate from the lane of the input vector.
4737 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4739 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4740 // to make a vector of the same size as this SHUFFLE. We can ignore the
4741 // extract entirely, and canonicalise the concat using WidenVector.
4742 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4743 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4744 V1 = V1.getOperand(0);
4745 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4746 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4747 Lane -= Idx * VT.getVectorNumElements() / 2;
4748 V1 = WidenVector(V1.getOperand(Idx), DAG);
4749 } else if (VT.getSizeInBits() == 64)
4750 V1 = WidenVector(V1, DAG);
4752 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4755 if (isREVMask(ShuffleMask, VT, 64))
4756 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4757 if (isREVMask(ShuffleMask, VT, 32))
4758 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4759 if (isREVMask(ShuffleMask, VT, 16))
4760 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4762 bool ReverseEXT = false;
4764 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4767 Imm *= getExtFactor(V1);
4768 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4769 DAG.getConstant(Imm, MVT::i32));
4770 } else if (V2->getOpcode() == ISD::UNDEF &&
4771 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4772 Imm *= getExtFactor(V1);
4773 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4774 DAG.getConstant(Imm, MVT::i32));
4777 unsigned WhichResult;
4778 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4779 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4780 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4782 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4783 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4784 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4786 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4787 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4788 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4791 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4792 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4793 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4795 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4796 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4797 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4799 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4800 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4801 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4804 // If the shuffle is not directly supported and it has 4 elements, use
4805 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4806 unsigned NumElts = VT.getVectorNumElements();
4808 unsigned PFIndexes[4];
4809 for (unsigned i = 0; i != 4; ++i) {
4810 if (ShuffleMask[i] < 0)
4813 PFIndexes[i] = ShuffleMask[i];
4816 // Compute the index in the perfect shuffle table.
4817 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4818 PFIndexes[2] * 9 + PFIndexes[3];
4819 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4820 unsigned Cost = (PFEntry >> 30);
4823 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4826 return GenerateTBL(Op, ShuffleMask, DAG);
4829 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4831 EVT VT = BVN->getValueType(0);
4832 APInt SplatBits, SplatUndef;
4833 unsigned SplatBitSize;
4835 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4836 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4838 for (unsigned i = 0; i < NumSplats; ++i) {
4839 CnstBits <<= SplatBitSize;
4840 UndefBits <<= SplatBitSize;
4841 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4842 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4851 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4852 SelectionDAG &DAG) const {
4853 BuildVectorSDNode *BVN =
4854 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4855 SDValue LHS = Op.getOperand(0);
4857 EVT VT = Op.getValueType();
4862 APInt CnstBits(VT.getSizeInBits(), 0);
4863 APInt UndefBits(VT.getSizeInBits(), 0);
4864 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4865 // We only have BIC vector immediate instruction, which is and-not.
4866 CnstBits = ~CnstBits;
4868 // We make use of a little bit of goto ickiness in order to avoid having to
4869 // duplicate the immediate matching logic for the undef toggled case.
4870 bool SecondTry = false;
4873 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4874 CnstBits = CnstBits.zextOrTrunc(64);
4875 uint64_t CnstVal = CnstBits.getZExtValue();
4877 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4878 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4879 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4880 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4881 DAG.getConstant(CnstVal, MVT::i32),
4882 DAG.getConstant(0, MVT::i32));
4883 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4886 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4887 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4888 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4889 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4890 DAG.getConstant(CnstVal, MVT::i32),
4891 DAG.getConstant(8, MVT::i32));
4892 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4895 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4896 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4897 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4898 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4899 DAG.getConstant(CnstVal, MVT::i32),
4900 DAG.getConstant(16, MVT::i32));
4901 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4904 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4905 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4906 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4907 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4908 DAG.getConstant(CnstVal, MVT::i32),
4909 DAG.getConstant(24, MVT::i32));
4910 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4913 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4914 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4915 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4916 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4917 DAG.getConstant(CnstVal, MVT::i32),
4918 DAG.getConstant(0, MVT::i32));
4919 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4922 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4923 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4924 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4925 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4926 DAG.getConstant(CnstVal, MVT::i32),
4927 DAG.getConstant(8, MVT::i32));
4928 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4935 CnstBits = ~UndefBits;
4939 // We can always fall back to a non-immediate AND.
4944 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4945 // consists of only the same constant int value, returned in reference arg
4947 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4948 uint64_t &ConstVal) {
4949 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4952 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4955 EVT VT = Bvec->getValueType(0);
4956 unsigned NumElts = VT.getVectorNumElements();
4957 for (unsigned i = 1; i < NumElts; ++i)
4958 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4960 ConstVal = FirstElt->getZExtValue();
4964 static unsigned getIntrinsicID(const SDNode *N) {
4965 unsigned Opcode = N->getOpcode();
4968 return Intrinsic::not_intrinsic;
4969 case ISD::INTRINSIC_WO_CHAIN: {
4970 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4971 if (IID < Intrinsic::num_intrinsics)
4973 return Intrinsic::not_intrinsic;
4978 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4979 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4980 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4981 // Also, logical shift right -> sri, with the same structure.
4982 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4983 EVT VT = N->getValueType(0);
4990 // Is the first op an AND?
4991 const SDValue And = N->getOperand(0);
4992 if (And.getOpcode() != ISD::AND)
4995 // Is the second op an shl or lshr?
4996 SDValue Shift = N->getOperand(1);
4997 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4998 // or ARM64ISD::VLSHR vector, #shift
4999 unsigned ShiftOpc = Shift.getOpcode();
5000 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
5002 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
5004 // Is the shift amount constant?
5005 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5009 // Is the and mask vector all constant?
5011 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5014 // Is C1 == ~C2, taking into account how much one can shift elements of a
5016 uint64_t C2 = C2node->getZExtValue();
5017 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5018 if (C2 > ElemSizeInBits)
5020 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5021 if ((C1 & ElemMask) != (~C2 & ElemMask))
5024 SDValue X = And.getOperand(0);
5025 SDValue Y = Shift.getOperand(0);
5028 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
5030 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5031 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5033 DEBUG(dbgs() << "arm64-lower: transformed: \n");
5034 DEBUG(N->dump(&DAG));
5035 DEBUG(dbgs() << "into: \n");
5036 DEBUG(ResultSLI->dump(&DAG));
5042 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
5043 SelectionDAG &DAG) const {
5044 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5045 if (EnableARM64SlrGeneration) {
5046 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5051 BuildVectorSDNode *BVN =
5052 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5053 SDValue LHS = Op.getOperand(1);
5055 EVT VT = Op.getValueType();
5057 // OR commutes, so try swapping the operands.
5059 LHS = Op.getOperand(0);
5060 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5065 APInt CnstBits(VT.getSizeInBits(), 0);
5066 APInt UndefBits(VT.getSizeInBits(), 0);
5067 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5068 // We make use of a little bit of goto ickiness in order to avoid having to
5069 // duplicate the immediate matching logic for the undef toggled case.
5070 bool SecondTry = false;
5073 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5074 CnstBits = CnstBits.zextOrTrunc(64);
5075 uint64_t CnstVal = CnstBits.getZExtValue();
5077 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5078 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5079 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5080 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5081 DAG.getConstant(CnstVal, MVT::i32),
5082 DAG.getConstant(0, MVT::i32));
5083 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5086 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5087 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5088 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5089 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5090 DAG.getConstant(CnstVal, MVT::i32),
5091 DAG.getConstant(8, MVT::i32));
5092 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5095 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5096 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5097 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5098 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5099 DAG.getConstant(CnstVal, MVT::i32),
5100 DAG.getConstant(16, MVT::i32));
5101 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5104 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5105 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5106 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5107 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5108 DAG.getConstant(CnstVal, MVT::i32),
5109 DAG.getConstant(24, MVT::i32));
5110 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5113 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5114 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5115 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5116 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5117 DAG.getConstant(CnstVal, MVT::i32),
5118 DAG.getConstant(0, MVT::i32));
5119 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5122 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5123 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5124 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5125 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5126 DAG.getConstant(CnstVal, MVT::i32),
5127 DAG.getConstant(8, MVT::i32));
5128 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5135 CnstBits = UndefBits;
5139 // We can always fall back to a non-immediate OR.
5144 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5145 SelectionDAG &DAG) const {
5146 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5148 EVT VT = Op.getValueType();
5150 APInt CnstBits(VT.getSizeInBits(), 0);
5151 APInt UndefBits(VT.getSizeInBits(), 0);
5152 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5153 // We make use of a little bit of goto ickiness in order to avoid having to
5154 // duplicate the immediate matching logic for the undef toggled case.
5155 bool SecondTry = false;
5158 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5159 CnstBits = CnstBits.zextOrTrunc(64);
5160 uint64_t CnstVal = CnstBits.getZExtValue();
5162 // Certain magic vector constants (used to express things like NOT
5163 // and NEG) are passed through unmodified. This allows codegen patterns
5164 // for these operations to match. Special-purpose patterns will lower
5165 // these immediates to MOVIs if it proves necessary.
5166 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5169 // The many faces of MOVI...
5170 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
5171 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
5172 if (VT.getSizeInBits() == 128) {
5173 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
5174 DAG.getConstant(CnstVal, MVT::i32));
5175 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5178 // Support the V64 version via subregister insertion.
5179 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
5180 DAG.getConstant(CnstVal, MVT::i32));
5181 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5184 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5185 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5186 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5187 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5188 DAG.getConstant(CnstVal, MVT::i32),
5189 DAG.getConstant(0, MVT::i32));
5190 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5193 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5194 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5195 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5196 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5197 DAG.getConstant(CnstVal, MVT::i32),
5198 DAG.getConstant(8, MVT::i32));
5199 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5202 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5203 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5204 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5205 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5206 DAG.getConstant(CnstVal, MVT::i32),
5207 DAG.getConstant(16, MVT::i32));
5208 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5211 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5212 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5213 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5214 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5215 DAG.getConstant(CnstVal, MVT::i32),
5216 DAG.getConstant(24, MVT::i32));
5217 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5220 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5221 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5222 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5223 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5224 DAG.getConstant(CnstVal, MVT::i32),
5225 DAG.getConstant(0, MVT::i32));
5226 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5229 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5230 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5231 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5232 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5233 DAG.getConstant(CnstVal, MVT::i32),
5234 DAG.getConstant(8, MVT::i32));
5235 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5238 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5239 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5240 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5241 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5242 DAG.getConstant(CnstVal, MVT::i32),
5243 DAG.getConstant(264, MVT::i32));
5244 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5247 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5248 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5249 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5250 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5251 DAG.getConstant(CnstVal, MVT::i32),
5252 DAG.getConstant(272, MVT::i32));
5253 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5256 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
5257 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
5258 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5259 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
5260 DAG.getConstant(CnstVal, MVT::i32));
5261 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5264 // The few faces of FMOV...
5265 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
5266 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
5267 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5268 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
5269 DAG.getConstant(CnstVal, MVT::i32));
5270 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5273 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
5274 VT.getSizeInBits() == 128) {
5275 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
5276 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
5277 DAG.getConstant(CnstVal, MVT::i32));
5278 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5281 // The many faces of MVNI...
5283 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5284 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5285 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5286 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5287 DAG.getConstant(CnstVal, MVT::i32),
5288 DAG.getConstant(0, MVT::i32));
5289 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5292 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5293 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5294 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5295 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5296 DAG.getConstant(CnstVal, MVT::i32),
5297 DAG.getConstant(8, MVT::i32));
5298 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5301 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5302 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5303 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5304 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5305 DAG.getConstant(CnstVal, MVT::i32),
5306 DAG.getConstant(16, MVT::i32));
5307 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5310 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5311 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5312 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5313 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5314 DAG.getConstant(CnstVal, MVT::i32),
5315 DAG.getConstant(24, MVT::i32));
5316 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5319 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5320 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5321 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5322 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5323 DAG.getConstant(CnstVal, MVT::i32),
5324 DAG.getConstant(0, MVT::i32));
5325 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5328 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5329 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5330 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5331 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5332 DAG.getConstant(CnstVal, MVT::i32),
5333 DAG.getConstant(8, MVT::i32));
5334 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5337 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5338 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5339 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5340 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5341 DAG.getConstant(CnstVal, MVT::i32),
5342 DAG.getConstant(264, MVT::i32));
5343 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5346 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5347 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5348 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5349 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5350 DAG.getConstant(CnstVal, MVT::i32),
5351 DAG.getConstant(272, MVT::i32));
5352 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5359 CnstBits = UndefBits;
5364 // Scan through the operands to find some interesting properties we can
5366 // 1) If only one value is used, we can use a DUP, or
5367 // 2) if only the low element is not undef, we can just insert that, or
5368 // 3) if only one constant value is used (w/ some non-constant lanes),
5369 // we can splat the constant value into the whole vector then fill
5370 // in the non-constant lanes.
5371 // 4) FIXME: If different constant values are used, but we can intelligently
5372 // select the values we'll be overwriting for the non-constant
5373 // lanes such that we can directly materialize the vector
5374 // some other way (MOVI, e.g.), we can be sneaky.
5375 unsigned NumElts = VT.getVectorNumElements();
5376 bool isOnlyLowElement = true;
5377 bool usesOnlyOneValue = true;
5378 bool usesOnlyOneConstantValue = true;
5379 bool isConstant = true;
5380 unsigned NumConstantLanes = 0;
5382 SDValue ConstantValue;
5383 for (unsigned i = 0; i < NumElts; ++i) {
5384 SDValue V = Op.getOperand(i);
5385 if (V.getOpcode() == ISD::UNDEF)
5388 isOnlyLowElement = false;
5389 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5392 if (isa<ConstantSDNode>(V)) {
5394 if (!ConstantValue.getNode())
5396 else if (ConstantValue != V)
5397 usesOnlyOneConstantValue = false;
5400 if (!Value.getNode())
5402 else if (V != Value)
5403 usesOnlyOneValue = false;
5406 if (!Value.getNode())
5407 return DAG.getUNDEF(VT);
5409 if (isOnlyLowElement)
5410 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5412 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5413 // i32 and try again.
5414 if (usesOnlyOneValue) {
5416 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5417 Value.getValueType() != VT)
5418 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5420 // This is actually a DUPLANExx operation, which keeps everything vectory.
5422 // DUPLANE works on 128-bit vectors, widen it if necessary.
5423 SDValue Lane = Value.getOperand(1);
5424 Value = Value.getOperand(0);
5425 if (Value.getValueType().getSizeInBits() == 64)
5426 Value = WidenVector(Value, DAG);
5428 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5429 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5432 if (VT.getVectorElementType().isFloatingPoint()) {
5433 SmallVector<SDValue, 8> Ops;
5435 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5436 for (unsigned i = 0; i < NumElts; ++i)
5437 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5438 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5439 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
5440 Val = LowerBUILD_VECTOR(Val, DAG);
5442 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5446 // If there was only one constant value used and for more than one lane,
5447 // start by splatting that value, then replace the non-constant lanes. This
5448 // is better than the default, which will perform a separate initialization
5450 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5451 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5452 // Now insert the non-constant lanes.
5453 for (unsigned i = 0; i < NumElts; ++i) {
5454 SDValue V = Op.getOperand(i);
5455 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5456 if (!isa<ConstantSDNode>(V)) {
5457 // Note that type legalization likely mucked about with the VT of the
5458 // source operand, so we may have to convert it here before inserting.
5459 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5465 // If all elements are constants and the case above didn't get hit, fall back
5466 // to the default expansion, which will generate a load from the constant
5471 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5473 SDValue shuffle = ReconstructShuffle(Op, DAG);
5474 if (shuffle != SDValue())
5478 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5479 // know the default expansion would otherwise fall back on something even
5480 // worse. For a vector with one or two non-undef values, that's
5481 // scalar_to_vector for the elements followed by a shuffle (provided the
5482 // shuffle is valid for the target) and materialization element by element
5483 // on the stack followed by a load for everything else.
5484 if (!isConstant && !usesOnlyOneValue) {
5485 SDValue Vec = DAG.getUNDEF(VT);
5486 SDValue Op0 = Op.getOperand(0);
5487 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5489 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5490 // a) Avoid a RMW dependency on the full vector register, and
5491 // b) Allow the register coalescer to fold away the copy if the
5492 // value is already in an S or D register.
5493 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5494 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5496 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5497 DAG.getTargetConstant(SubIdx, MVT::i32));
5498 Vec = SDValue(N, 0);
5501 for (; i < NumElts; ++i) {
5502 SDValue V = Op.getOperand(i);
5503 if (V.getOpcode() == ISD::UNDEF)
5505 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5506 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5511 // Just use the default expansion. We failed to find a better alternative.
5515 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5516 SelectionDAG &DAG) const {
5517 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5519 // Check for non-constant lane.
5520 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5523 EVT VT = Op.getOperand(0).getValueType();
5525 // Insertion/extraction are legal for V128 types.
5526 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5527 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5530 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5531 VT != MVT::v1i64 && VT != MVT::v2f32)
5534 // For V64 types, we perform insertion by expanding the value
5535 // to a V128 type and perform the insertion on that.
5537 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5538 EVT WideTy = WideVec.getValueType();
5540 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5541 Op.getOperand(1), Op.getOperand(2));
5542 // Re-narrow the resultant vector.
5543 return NarrowVector(Node, DAG);
5546 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5547 SelectionDAG &DAG) const {
5548 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5550 // Check for non-constant lane.
5551 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5554 EVT VT = Op.getOperand(0).getValueType();
5556 // Insertion/extraction are legal for V128 types.
5557 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5558 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5561 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5562 VT != MVT::v1i64 && VT != MVT::v2f32)
5565 // For V64 types, we perform extraction by expanding the value
5566 // to a V128 type and perform the extraction on that.
5568 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5569 EVT WideTy = WideVec.getValueType();
5571 EVT ExtrTy = WideTy.getVectorElementType();
5572 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5575 // For extractions, we just return the result directly.
5576 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5580 SDValue ARM64TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5581 SelectionDAG &DAG) const {
5582 assert(Op.getOpcode() == ISD::SCALAR_TO_VECTOR && "Unknown opcode!");
5583 // Some AdvSIMD intrinsics leave their results in the scalar B/H/S/D
5584 // registers. The default lowering will copy those to a GPR then back
5585 // to a vector register. Instead, just recognize those cases and reference
5586 // the vector register they're already a subreg of.
5587 SDValue Op0 = Op->getOperand(0);
5588 if (Op0->getOpcode() != ISD::INTRINSIC_WO_CHAIN)
5590 unsigned IID = getIntrinsicID(Op0.getNode());
5591 // The below list of intrinsics isn't exhaustive. Add cases as-needed.
5592 // FIXME: Even better would be if there were an attribute on the node
5593 // that we could query and set in the intrinsics definition or something.
5597 // Early exit if this isn't one of the intrinsics we handle.
5599 case Intrinsic::arm64_neon_uaddv:
5600 case Intrinsic::arm64_neon_saddv:
5601 case Intrinsic::arm64_neon_uaddlv:
5602 case Intrinsic::arm64_neon_saddlv:
5603 switch (Op0.getValueType().getSizeInBits()) {
5605 llvm_unreachable("Illegal result size from ARM64 vector intrinsic!");
5607 SubIdx = ARM64::bsub;
5610 SubIdx = ARM64::hsub;
5613 SubIdx = ARM64::ssub;
5616 SubIdx = ARM64::dsub;
5621 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(Op),
5622 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
5623 Op0, DAG.getTargetConstant(SubIdx, MVT::i32));
5624 return SDValue(N, 0);
5627 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5628 SelectionDAG &DAG) const {
5629 EVT VT = Op.getOperand(0).getValueType();
5635 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5638 unsigned Val = Cst->getZExtValue();
5640 unsigned Size = Op.getValueType().getSizeInBits();
5644 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5647 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5650 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5653 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5656 llvm_unreachable("Unexpected vector type in extract_subvector!");
5659 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5661 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5667 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5669 if (VT.getVectorNumElements() == 4 &&
5670 (VT.is128BitVector() || VT.is64BitVector())) {
5671 unsigned PFIndexes[4];
5672 for (unsigned i = 0; i != 4; ++i) {
5676 PFIndexes[i] = M[i];
5679 // Compute the index in the perfect shuffle table.
5680 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5681 PFIndexes[2] * 9 + PFIndexes[3];
5682 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5683 unsigned Cost = (PFEntry >> 30);
5690 unsigned Imm, WhichResult;
5692 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5693 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5694 isEXTMask(M, VT, ReverseVEXT, Imm) ||
5695 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5696 isTRNMask(M, VT, WhichResult) || isUZPMask(M, VT, WhichResult) ||
5697 isZIPMask(M, VT, WhichResult) ||
5698 isTRN_v_undef_Mask(M, VT, WhichResult) ||
5699 isUZP_v_undef_Mask(M, VT, WhichResult) ||
5700 isZIP_v_undef_Mask(M, VT, WhichResult));
5703 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5704 /// operand of a vector shift operation, where all the elements of the
5705 /// build_vector must have the same constant integer value.
5706 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5707 // Ignore bit_converts.
5708 while (Op.getOpcode() == ISD::BITCAST)
5709 Op = Op.getOperand(0);
5710 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5711 APInt SplatBits, SplatUndef;
5712 unsigned SplatBitSize;
5714 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5715 HasAnyUndefs, ElementBits) ||
5716 SplatBitSize > ElementBits)
5718 Cnt = SplatBits.getSExtValue();
5722 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5723 /// operand of a vector shift left operation. That value must be in the range:
5724 /// 0 <= Value < ElementBits for a left shift; or
5725 /// 0 <= Value <= ElementBits for a long left shift.
5726 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5727 assert(VT.isVector() && "vector shift count is not a vector type");
5728 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5729 if (!getVShiftImm(Op, ElementBits, Cnt))
5731 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5734 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5735 /// operand of a vector shift right operation. For a shift opcode, the value
5736 /// is positive, but for an intrinsic the value count must be negative. The
5737 /// absolute value must be in the range:
5738 /// 1 <= |Value| <= ElementBits for a right shift; or
5739 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5740 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5742 assert(VT.isVector() && "vector shift count is not a vector type");
5743 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5744 if (!getVShiftImm(Op, ElementBits, Cnt))
5748 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5751 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5752 SelectionDAG &DAG) const {
5753 EVT VT = Op.getValueType();
5757 if (!Op.getOperand(1).getValueType().isVector())
5759 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5761 switch (Op.getOpcode()) {
5763 llvm_unreachable("unexpected shift opcode");
5766 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5767 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5768 DAG.getConstant(Cnt, MVT::i32));
5769 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5770 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5771 Op.getOperand(0), Op.getOperand(1));
5774 // Right shift immediate
5775 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5778 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5779 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5780 DAG.getConstant(Cnt, MVT::i32));
5783 // Right shift register. Note, there is not a shift right register
5784 // instruction, but the shift left register instruction takes a signed
5785 // value, where negative numbers specify a right shift.
5786 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5787 : Intrinsic::arm64_neon_ushl;
5788 // negate the shift amount
5789 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5790 SDValue NegShiftLeft =
5791 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5792 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5793 return NegShiftLeft;
5799 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5800 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5801 SDLoc dl, SelectionDAG &DAG) {
5802 EVT SrcVT = LHS.getValueType();
5804 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5805 APInt CnstBits(VT.getSizeInBits(), 0);
5806 APInt UndefBits(VT.getSizeInBits(), 0);
5807 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5808 bool IsZero = IsCnst && (CnstBits == 0);
5810 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5817 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5819 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5820 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5824 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5825 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5828 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5829 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5832 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5833 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5836 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5837 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5841 // If we ignore NaNs then we can use to the MI implementation.
5845 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5846 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5856 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5858 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5859 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5863 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5864 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5867 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5868 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5871 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5872 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5875 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5876 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5878 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5880 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5883 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5884 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5886 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5888 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5892 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5893 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5894 SDValue LHS = Op.getOperand(0);
5895 SDValue RHS = Op.getOperand(1);
5898 if (LHS.getValueType().getVectorElementType().isInteger()) {
5899 assert(LHS.getValueType() == RHS.getValueType());
5900 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5901 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5905 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5906 LHS.getValueType().getVectorElementType() == MVT::f64);
5908 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5909 // clean. Some of them require two branches to implement.
5910 ARM64CC::CondCode CC1, CC2;
5911 changeFPCCToARM64CC(CC, CC1, CC2);
5913 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5915 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5916 if (!Cmp1.getNode())
5919 if (CC2 != ARM64CC::AL) {
5921 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5922 if (!Cmp2.getNode())
5925 return DAG.getNode(ISD::OR, dl, Cmp1.getValueType(), Cmp1, Cmp2);
5931 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5932 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5933 /// specified in the intrinsic calls.
5934 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5936 unsigned Intrinsic) const {
5937 switch (Intrinsic) {
5938 case Intrinsic::arm64_neon_ld2:
5939 case Intrinsic::arm64_neon_ld3:
5940 case Intrinsic::arm64_neon_ld4:
5941 case Intrinsic::arm64_neon_ld2lane:
5942 case Intrinsic::arm64_neon_ld3lane:
5943 case Intrinsic::arm64_neon_ld4lane:
5944 case Intrinsic::arm64_neon_ld2r:
5945 case Intrinsic::arm64_neon_ld3r:
5946 case Intrinsic::arm64_neon_ld4r: {
5947 Info.opc = ISD::INTRINSIC_W_CHAIN;
5948 // Conservatively set memVT to the entire set of vectors loaded.
5949 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5950 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5951 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5954 Info.vol = false; // volatile loads with NEON intrinsics not supported
5955 Info.readMem = true;
5956 Info.writeMem = false;
5959 case Intrinsic::arm64_neon_st2:
5960 case Intrinsic::arm64_neon_st3:
5961 case Intrinsic::arm64_neon_st4:
5962 case Intrinsic::arm64_neon_st2lane:
5963 case Intrinsic::arm64_neon_st3lane:
5964 case Intrinsic::arm64_neon_st4lane: {
5965 Info.opc = ISD::INTRINSIC_VOID;
5966 // Conservatively set memVT to the entire set of vectors stored.
5967 unsigned NumElts = 0;
5968 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5969 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5970 if (!ArgTy->isVectorTy())
5972 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5974 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5975 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5978 Info.vol = false; // volatile stores with NEON intrinsics not supported
5979 Info.readMem = false;
5980 Info.writeMem = true;
5983 case Intrinsic::arm64_ldxr: {
5984 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5985 Info.opc = ISD::INTRINSIC_W_CHAIN;
5986 Info.memVT = MVT::getVT(PtrTy->getElementType());
5987 Info.ptrVal = I.getArgOperand(0);
5989 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5991 Info.readMem = true;
5992 Info.writeMem = false;
5995 case Intrinsic::arm64_stxr: {
5996 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5997 Info.opc = ISD::INTRINSIC_W_CHAIN;
5998 Info.memVT = MVT::getVT(PtrTy->getElementType());
5999 Info.ptrVal = I.getArgOperand(1);
6001 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6003 Info.readMem = false;
6004 Info.writeMem = true;
6007 case Intrinsic::arm64_ldxp: {
6008 Info.opc = ISD::INTRINSIC_W_CHAIN;
6009 Info.memVT = MVT::i128;
6010 Info.ptrVal = I.getArgOperand(0);
6014 Info.readMem = true;
6015 Info.writeMem = false;
6018 case Intrinsic::arm64_stxp: {
6019 Info.opc = ISD::INTRINSIC_W_CHAIN;
6020 Info.memVT = MVT::i128;
6021 Info.ptrVal = I.getArgOperand(2);
6025 Info.readMem = false;
6026 Info.writeMem = true;
6036 // Truncations from 64-bit GPR to 32-bit GPR is free.
6037 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6038 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6040 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6041 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6042 if (NumBits1 <= NumBits2)
6046 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6047 if (!VT1.isInteger() || !VT2.isInteger())
6049 unsigned NumBits1 = VT1.getSizeInBits();
6050 unsigned NumBits2 = VT2.getSizeInBits();
6051 if (NumBits1 <= NumBits2)
6056 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6058 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6059 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6061 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6062 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6063 if (NumBits1 == 32 && NumBits2 == 64)
6067 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6068 if (!VT1.isInteger() || !VT2.isInteger())
6070 unsigned NumBits1 = VT1.getSizeInBits();
6071 unsigned NumBits2 = VT2.getSizeInBits();
6072 if (NumBits1 == 32 && NumBits2 == 64)
6077 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6078 EVT VT1 = Val.getValueType();
6079 if (isZExtFree(VT1, VT2)) {
6083 if (Val.getOpcode() != ISD::LOAD)
6086 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6087 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
6088 VT2.isInteger() && VT1.getSizeInBits() <= 32);
6091 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
6092 unsigned &RequiredAligment) const {
6093 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6095 // Cyclone supports unaligned accesses.
6096 RequiredAligment = 0;
6097 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6098 return NumBits == 32 || NumBits == 64;
6101 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
6102 unsigned &RequiredAligment) const {
6103 if (!LoadedType.isSimple() ||
6104 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6106 // Cyclone supports unaligned accesses.
6107 RequiredAligment = 0;
6108 unsigned NumBits = LoadedType.getSizeInBits();
6109 return NumBits == 32 || NumBits == 64;
6112 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6113 unsigned AlignCheck) {
6114 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6115 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6118 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6119 unsigned SrcAlign, bool IsMemset,
6120 bool ZeroMemset, bool MemcpyStrSrc,
6121 MachineFunction &MF) const {
6122 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6123 // instruction to materialize the v2i64 zero and one store (with restrictive
6124 // addressing mode). Just do two i64 store of zero-registers.
6126 const Function *F = MF.getFunction();
6127 if (!IsMemset && Size >= 16 &&
6128 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
6129 Attribute::NoImplicitFloat) &&
6130 (memOpAlign(SrcAlign, DstAlign, 16) ||
6131 (allowsUnalignedMemoryAccesses(MVT::v2i64, 0, &Fast) && Fast)))
6134 return Size >= 8 ? MVT::i64 : MVT::i32;
6137 // 12-bit optionally shifted immediates are legal for adds.
6138 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6139 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6144 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6145 // immediates is the same as for an add or a sub.
6146 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6149 return isLegalAddImmediate(Immed);
6152 /// isLegalAddressingMode - Return true if the addressing mode represented
6153 /// by AM is legal for this target, for a load/store of the specified type.
6154 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6156 // ARM64 has five basic addressing modes:
6158 // reg + 9-bit signed offset
6159 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6161 // reg + SIZE_IN_BYTES * reg
6163 // No global is ever allowed as a base.
6167 // No reg+reg+imm addressing.
6168 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6171 // check reg + imm case:
6172 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6173 uint64_t NumBytes = 0;
6174 if (Ty->isSized()) {
6175 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6176 NumBytes = NumBits / 8;
6177 if (!isPowerOf2_64(NumBits))
6182 int64_t Offset = AM.BaseOffs;
6184 // 9-bit signed offset
6185 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6188 // 12-bit unsigned offset
6189 unsigned shift = Log2_64(NumBytes);
6190 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6191 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6192 (Offset >> shift) << shift == Offset)
6197 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6199 if (!AM.Scale || AM.Scale == 1 ||
6200 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6205 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6207 // Scaling factors are not free at all.
6208 // Operands | Rt Latency
6209 // -------------------------------------------
6211 // -------------------------------------------
6212 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6213 // Rt, [Xn, Wm, <extend> #imm] |
6214 if (isLegalAddressingMode(AM, Ty))
6215 // Scale represents reg2 * scale, thus account for 1 if
6216 // it is not equal to 0 or 1.
6217 return AM.Scale != 0 && AM.Scale != 1;
6221 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6222 VT = VT.getScalarType();
6227 switch (VT.getSimpleVT().SimpleTy) {
6239 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6240 // LR is a callee-save register, but we must treat it as clobbered by any call
6241 // site. Hence we include LR in the scratch registers, which are in turn added
6242 // as implicit-defs for stackmaps and patchpoints.
6243 static const uint16_t ScratchRegs[] = {
6244 ARM64::X16, ARM64::X17, ARM64::LR, 0
6249 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6251 assert(Ty->isIntegerTy());
6253 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6257 int64_t Val = Imm.getSExtValue();
6258 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
6261 if ((int64_t)Val < 0)
6264 Val &= (1LL << 32) - 1;
6266 unsigned LZ = countLeadingZeros((uint64_t)Val);
6267 unsigned Shift = (63 - LZ) / 16;
6268 // MOVZ is free so return true for one or fewer MOVK.
6269 return (Shift < 3) ? true : false;
6272 // Generate SUBS and CSEL for integer abs.
6273 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6274 EVT VT = N->getValueType(0);
6276 SDValue N0 = N->getOperand(0);
6277 SDValue N1 = N->getOperand(1);
6280 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6281 // and change it to SUB and CSEL.
6282 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6283 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6284 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6285 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6286 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6287 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6289 // Generate SUBS & CSEL.
6291 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6292 N0.getOperand(0), DAG.getConstant(0, VT));
6293 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6294 DAG.getConstant(ARM64CC::PL, MVT::i32),
6295 SDValue(Cmp.getNode(), 1));
6300 // performXorCombine - Attempts to handle integer ABS.
6301 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6302 TargetLowering::DAGCombinerInfo &DCI,
6303 const ARM64Subtarget *Subtarget) {
6304 if (DCI.isBeforeLegalizeOps())
6307 return performIntegerAbsCombine(N, DAG);
6310 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6311 TargetLowering::DAGCombinerInfo &DCI,
6312 const ARM64Subtarget *Subtarget) {
6313 if (DCI.isBeforeLegalizeOps())
6316 // Multiplication of a power of two plus/minus one can be done more
6317 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6318 // future CPUs have a cheaper MADD instruction, this may need to be
6319 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6320 // 64-bit is 5 cycles, so this is always a win.
6321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6322 APInt Value = C->getAPIntValue();
6323 EVT VT = N->getValueType(0);
6324 APInt VP1 = Value + 1;
6325 if (VP1.isPowerOf2()) {
6326 // Multiplying by one less than a power of two, replace with a shift
6328 SDValue ShiftedVal =
6329 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6330 DAG.getConstant(VP1.logBase2(), MVT::i64));
6331 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6333 APInt VM1 = Value - 1;
6334 if (VM1.isPowerOf2()) {
6335 // Multiplying by one more than a power of two, replace with a shift
6337 SDValue ShiftedVal =
6338 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6339 DAG.getConstant(VM1.logBase2(), MVT::i64));
6340 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6346 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6347 EVT VT = N->getValueType(0);
6348 if (VT != MVT::f32 && VT != MVT::f64)
6350 // Only optimize when the source and destination types have the same width.
6351 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6354 // If the result of an integer load is only used by an integer-to-float
6355 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6356 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6357 SDValue N0 = N->getOperand(0);
6358 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6359 // Do not change the width of a volatile load.
6360 !cast<LoadSDNode>(N0)->isVolatile()) {
6361 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6362 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6363 LN0->getPointerInfo(), LN0->isVolatile(),
6364 LN0->isNonTemporal(), LN0->isInvariant(),
6365 LN0->getAlignment());
6367 // Make sure successors of the original load stay after it by updating them
6368 // to use the new Chain.
6369 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6372 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6373 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6379 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6380 /// searches for and classifies those shifts.
6381 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6383 if (N.getOpcode() == ISD::SHL)
6385 else if (N.getOpcode() == ISD::SRL)
6390 if (!isa<ConstantSDNode>(N.getOperand(1)))
6393 ShiftAmount = N->getConstantOperandVal(1);
6394 Src = N->getOperand(0);
6398 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6399 /// registers viewed as a high/low pair. This function looks for the pattern:
6400 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6401 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6403 static SDValue tryCombineToEXTR(SDNode *N,
6404 TargetLowering::DAGCombinerInfo &DCI) {
6405 SelectionDAG &DAG = DCI.DAG;
6407 EVT VT = N->getValueType(0);
6409 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6411 if (VT != MVT::i32 && VT != MVT::i64)
6415 uint32_t ShiftLHS = 0;
6417 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6421 uint32_t ShiftRHS = 0;
6423 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6426 // If they're both trying to come from the high part of the register, they're
6427 // not really an EXTR.
6428 if (LHSFromHi == RHSFromHi)
6431 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6435 std::swap(LHS, RHS);
6436 std::swap(ShiftLHS, ShiftRHS);
6439 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6440 DAG.getConstant(ShiftRHS, MVT::i64));
6443 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6444 const ARM64Subtarget *Subtarget) {
6445 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6446 if (!EnableARM64ExtrGeneration)
6448 SelectionDAG &DAG = DCI.DAG;
6449 EVT VT = N->getValueType(0);
6451 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6454 SDValue Res = tryCombineToEXTR(N, DCI);
6461 static SDValue performBitcastCombine(SDNode *N,
6462 TargetLowering::DAGCombinerInfo &DCI,
6463 SelectionDAG &DAG) {
6464 // Wait 'til after everything is legalized to try this. That way we have
6465 // legal vector types and such.
6466 if (DCI.isBeforeLegalizeOps())
6469 // Remove extraneous bitcasts around an extract_subvector.
6471 // (v4i16 (bitconvert
6472 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6474 // (extract_subvector ((v8i16 ...), (i64 4)))
6476 // Only interested in 64-bit vectors as the ultimate result.
6477 EVT VT = N->getValueType(0);
6480 if (VT.getSimpleVT().getSizeInBits() != 64)
6482 // Is the operand an extract_subvector starting at the beginning or halfway
6483 // point of the vector? A low half may also come through as an
6484 // EXTRACT_SUBREG, so look for that, too.
6485 SDValue Op0 = N->getOperand(0);
6486 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6487 !(Op0->isMachineOpcode() &&
6488 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6490 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6491 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6492 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6494 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6495 if (idx != ARM64::dsub)
6497 // The dsub reference is equivalent to a lane zero subvector reference.
6500 // Look through the bitcast of the input to the extract.
6501 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6503 SDValue Source = Op0->getOperand(0)->getOperand(0);
6504 // If the source type has twice the number of elements as our destination
6505 // type, we know this is an extract of the high or low half of the vector.
6506 EVT SVT = Source->getValueType(0);
6507 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6510 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6512 // Create the simplified form to just extract the low or high half of the
6513 // vector directly rather than bothering with the bitcasts.
6515 unsigned NumElements = VT.getVectorNumElements();
6517 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6518 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6520 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6521 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6527 static SDValue performConcatVectorsCombine(SDNode *N,
6528 TargetLowering::DAGCombinerInfo &DCI,
6529 SelectionDAG &DAG) {
6530 // Wait 'til after everything is legalized to try this. That way we have
6531 // legal vector types and such.
6532 if (DCI.isBeforeLegalizeOps())
6536 EVT VT = N->getValueType(0);
6538 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6539 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6540 // canonicalise to that.
6541 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6542 assert(VT.getVectorElementType().getSizeInBits() == 64);
6543 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6544 WidenVector(N->getOperand(0), DAG),
6545 DAG.getConstant(0, MVT::i64));
6548 // Canonicalise concat_vectors so that the right-hand vector has as few
6549 // bit-casts as possible before its real operation. The primary matching
6550 // destination for these operations will be the narrowing "2" instructions,
6551 // which depend on the operation being performed on this right-hand vector.
6553 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6555 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6557 SDValue Op1 = N->getOperand(1);
6558 if (Op1->getOpcode() != ISD::BITCAST)
6560 SDValue RHS = Op1->getOperand(0);
6561 MVT RHSTy = RHS.getValueType().getSimpleVT();
6562 // If the RHS is not a vector, this is not the pattern we're looking for.
6563 if (!RHSTy.isVector())
6566 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6568 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6569 RHSTy.getVectorNumElements() * 2);
6571 ISD::BITCAST, dl, VT,
6572 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6573 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6576 static SDValue tryCombineFixedPointConvert(SDNode *N,
6577 TargetLowering::DAGCombinerInfo &DCI,
6578 SelectionDAG &DAG) {
6579 // Wait 'til after everything is legalized to try this. That way we have
6580 // legal vector types and such.
6581 if (DCI.isBeforeLegalizeOps())
6583 // Transform a scalar conversion of a value from a lane extract into a
6584 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6585 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6586 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6588 // The second form interacts better with instruction selection and the
6589 // register allocator to avoid cross-class register copies that aren't
6590 // coalescable due to a lane reference.
6592 // Check the operand and see if it originates from a lane extract.
6593 SDValue Op1 = N->getOperand(1);
6594 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6595 // Yep, no additional predication needed. Perform the transform.
6596 SDValue IID = N->getOperand(0);
6597 SDValue Shift = N->getOperand(2);
6598 SDValue Vec = Op1.getOperand(0);
6599 SDValue Lane = Op1.getOperand(1);
6600 EVT ResTy = N->getValueType(0);
6604 // The vector width should be 128 bits by the time we get here, even
6605 // if it started as 64 bits (the extract_vector handling will have
6607 assert(Vec.getValueType().getSizeInBits() == 128 &&
6608 "unexpected vector size on extract_vector_elt!");
6609 if (Vec.getValueType() == MVT::v4i32)
6610 VecResTy = MVT::v4f32;
6611 else if (Vec.getValueType() == MVT::v2i64)
6612 VecResTy = MVT::v2f64;
6614 assert(0 && "unexpected vector type!");
6617 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6618 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6623 // AArch64 high-vector "long" operations are formed by performing the non-high
6624 // version on an extract_subvector of each operand which gets the high half:
6626 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6628 // However, there are cases which don't have an extract_high explicitly, but
6629 // have another operation that can be made compatible with one for free. For
6632 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6634 // This routine does the actual conversion of such DUPs, once outer routines
6635 // have determined that everything else is in order.
6636 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6637 // We can handle most types of duplicate, but the lane ones have an extra
6638 // operand saying *which* lane, so we need to know.
6640 switch (N.getOpcode()) {
6644 case ARM64ISD::DUPLANE8:
6645 case ARM64ISD::DUPLANE16:
6646 case ARM64ISD::DUPLANE32:
6647 case ARM64ISD::DUPLANE64:
6654 MVT NarrowTy = N.getSimpleValueType();
6655 if (!NarrowTy.is64BitVector())
6658 MVT ElementTy = NarrowTy.getVectorElementType();
6659 unsigned NumElems = NarrowTy.getVectorNumElements();
6660 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6664 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6667 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6669 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6670 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6673 static bool isEssentiallyExtractSubvector(SDValue N) {
6674 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6677 return N.getOpcode() == ISD::BITCAST &&
6678 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6681 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6682 struct GenericSetCCInfo {
6683 const SDValue *Opnd0;
6684 const SDValue *Opnd1;
6688 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6689 struct ARM64SetCCInfo {
6691 ARM64CC::CondCode CC;
6694 /// \brief Helper structure to keep track of SetCC information.
6696 GenericSetCCInfo Generic;
6697 ARM64SetCCInfo ARM64;
6700 /// \brief Helper structure to be able to read SetCC information.
6701 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6702 /// a GenericSetCCInfo.
6703 struct SetCCInfoAndKind {
6708 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6710 /// ARM64 lowered one.
6711 /// \p SetCCInfo is filled accordingly.
6712 /// \post SetCCInfo is meanginfull only when this function returns true.
6713 /// \return True when Op is a kind of SET_CC operation.
6714 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6715 // If this is a setcc, this is straight forward.
6716 if (Op.getOpcode() == ISD::SETCC) {
6717 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6718 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6719 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6720 SetCCInfo.IsARM64 = false;
6723 // Otherwise, check if this is a matching csel instruction.
6727 if (Op.getOpcode() != ARM64ISD::CSEL)
6729 // Set the information about the operands.
6730 // TODO: we want the operands of the Cmp not the csel
6731 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6732 SetCCInfo.IsARM64 = true;
6733 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6734 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6736 // Check that the operands matches the constraints:
6737 // (1) Both operands must be constants.
6738 // (2) One must be 1 and the other must be 0.
6739 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6740 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6743 if (!TValue || !FValue)
6747 if (!TValue->isOne()) {
6748 // Update the comparison when we are interested in !cc.
6749 std::swap(TValue, FValue);
6750 SetCCInfo.Info.ARM64.CC =
6751 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6753 return TValue->isOne() && FValue->isNullValue();
6756 // The folding we want to perform is:
6757 // (add x, (setcc cc ...) )
6759 // (csel x, (add x, 1), !cc ...)
6761 // The latter will get matched to a CSINC instruction.
6762 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6763 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6764 SDValue LHS = Op->getOperand(0);
6765 SDValue RHS = Op->getOperand(1);
6766 SetCCInfoAndKind InfoAndKind;
6768 // If neither operand is a SET_CC, give up.
6769 if (!isSetCC(LHS, InfoAndKind)) {
6770 std::swap(LHS, RHS);
6771 if (!isSetCC(LHS, InfoAndKind))
6775 // FIXME: This could be generatized to work for FP comparisons.
6776 EVT CmpVT = InfoAndKind.IsARM64
6777 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6778 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6779 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6785 if (InfoAndKind.IsARM64) {
6786 CCVal = DAG.getConstant(
6787 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6788 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6790 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6791 *InfoAndKind.Info.Generic.Opnd1,
6792 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6795 EVT VT = Op->getValueType(0);
6796 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6797 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6800 // The basic add/sub long vector instructions have variants with "2" on the end
6801 // which act on the high-half of their inputs. They are normally matched by
6804 // (add (zeroext (extract_high LHS)),
6805 // (zeroext (extract_high RHS)))
6806 // -> uaddl2 vD, vN, vM
6808 // However, if one of the extracts is something like a duplicate, this
6809 // instruction can still be used profitably. This function puts the DAG into a
6810 // more appropriate form for those patterns to trigger.
6811 static SDValue performAddSubLongCombine(SDNode *N,
6812 TargetLowering::DAGCombinerInfo &DCI,
6813 SelectionDAG &DAG) {
6814 if (DCI.isBeforeLegalizeOps())
6817 MVT VT = N->getSimpleValueType(0);
6818 if (!VT.is128BitVector()) {
6819 if (N->getOpcode() == ISD::ADD)
6820 return performSetccAddFolding(N, DAG);
6824 // Make sure both branches are extended in the same way.
6825 SDValue LHS = N->getOperand(0);
6826 SDValue RHS = N->getOperand(1);
6827 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6828 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6829 LHS.getOpcode() != RHS.getOpcode())
6832 unsigned ExtType = LHS.getOpcode();
6834 // It's not worth doing if at least one of the inputs isn't already an
6835 // extract, but we don't know which it'll be so we have to try both.
6836 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6837 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6841 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6842 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6843 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6847 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6850 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6853 // Massage DAGs which we can use the high-half "long" operations on into
6854 // something isel will recognize better. E.g.
6856 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6857 // (arm64_neon_umull (extract_high (v2i64 vec)))
6858 // (extract_high (v2i64 (dup128 scalar)))))
6860 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6861 TargetLowering::DAGCombinerInfo &DCI,
6862 SelectionDAG &DAG) {
6863 if (DCI.isBeforeLegalizeOps())
6866 SDValue LHS = N->getOperand(1);
6867 SDValue RHS = N->getOperand(2);
6868 assert(LHS.getValueType().is64BitVector() &&
6869 RHS.getValueType().is64BitVector() &&
6870 "unexpected shape for long operation");
6872 // Either node could be a DUP, but it's not worth doing both of them (you'd
6873 // just as well use the non-high version) so look for a corresponding extract
6874 // operation on the other "wing".
6875 if (isEssentiallyExtractSubvector(LHS)) {
6876 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6879 } else if (isEssentiallyExtractSubvector(RHS)) {
6880 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6885 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6886 N->getOperand(0), LHS, RHS);
6889 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6890 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6891 unsigned ElemBits = ElemTy.getSizeInBits();
6893 int64_t ShiftAmount;
6894 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6895 APInt SplatValue, SplatUndef;
6896 unsigned SplatBitSize;
6898 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6899 HasAnyUndefs, ElemBits) ||
6900 SplatBitSize != ElemBits)
6903 ShiftAmount = SplatValue.getSExtValue();
6904 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6905 ShiftAmount = CVN->getSExtValue();
6913 llvm_unreachable("Unknown shift intrinsic");
6914 case Intrinsic::arm64_neon_sqshl:
6915 Opcode = ARM64ISD::SQSHL_I;
6916 IsRightShift = false;
6918 case Intrinsic::arm64_neon_uqshl:
6919 Opcode = ARM64ISD::UQSHL_I;
6920 IsRightShift = false;
6922 case Intrinsic::arm64_neon_srshl:
6923 Opcode = ARM64ISD::SRSHR_I;
6924 IsRightShift = true;
6926 case Intrinsic::arm64_neon_urshl:
6927 Opcode = ARM64ISD::URSHR_I;
6928 IsRightShift = true;
6930 case Intrinsic::arm64_neon_sqshlu:
6931 Opcode = ARM64ISD::SQSHLU_I;
6932 IsRightShift = false;
6936 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6937 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6938 DAG.getConstant(-ShiftAmount, MVT::i32));
6939 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6940 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6941 DAG.getConstant(ShiftAmount, MVT::i32));
6946 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6947 // the intrinsics must be legal and take an i32, this means there's almost
6948 // certainly going to be a zext in the DAG which we can eliminate.
6949 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6950 SDValue AndN = N->getOperand(2);
6951 if (AndN.getOpcode() != ISD::AND)
6954 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6955 if (!CMask || CMask->getZExtValue() != Mask)
6958 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6959 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6962 static SDValue performIntrinsicCombine(SDNode *N,
6963 TargetLowering::DAGCombinerInfo &DCI,
6964 const ARM64Subtarget *Subtarget) {
6965 SelectionDAG &DAG = DCI.DAG;
6966 unsigned IID = getIntrinsicID(N);
6970 case Intrinsic::arm64_neon_vcvtfxs2fp:
6971 case Intrinsic::arm64_neon_vcvtfxu2fp:
6972 return tryCombineFixedPointConvert(N, DCI, DAG);
6974 case Intrinsic::arm64_neon_fmax:
6975 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6976 N->getOperand(1), N->getOperand(2));
6977 case Intrinsic::arm64_neon_fmin:
6978 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6979 N->getOperand(1), N->getOperand(2));
6980 case Intrinsic::arm64_neon_smull:
6981 case Intrinsic::arm64_neon_umull:
6982 case Intrinsic::arm64_neon_pmull:
6983 case Intrinsic::arm64_neon_sqdmull:
6984 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6985 case Intrinsic::arm64_neon_sqshl:
6986 case Intrinsic::arm64_neon_uqshl:
6987 case Intrinsic::arm64_neon_sqshlu:
6988 case Intrinsic::arm64_neon_srshl:
6989 case Intrinsic::arm64_neon_urshl:
6990 return tryCombineShiftImm(IID, N, DAG);
6991 case Intrinsic::arm64_crc32b:
6992 case Intrinsic::arm64_crc32cb:
6993 return tryCombineCRC32(0xff, N, DAG);
6994 case Intrinsic::arm64_crc32h:
6995 case Intrinsic::arm64_crc32ch:
6996 return tryCombineCRC32(0xffff, N, DAG);
7001 static SDValue performExtendCombine(SDNode *N,
7002 TargetLowering::DAGCombinerInfo &DCI,
7003 SelectionDAG &DAG) {
7004 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7005 // we can convert that DUP into another extract_high (of a bigger DUP), which
7006 // helps the backend to decide that an sabdl2 would be useful, saving a real
7007 // extract_high operation.
7008 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7009 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7010 SDNode *ABDNode = N->getOperand(0).getNode();
7011 unsigned IID = getIntrinsicID(ABDNode);
7012 if (IID == Intrinsic::arm64_neon_sabd ||
7013 IID == Intrinsic::arm64_neon_uabd) {
7014 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7015 if (!NewABD.getNode())
7018 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7023 // This is effectively a custom type legalization for ARM64.
7025 // Type legalization will split an extend of a small, legal, type to a larger
7026 // illegal type by first splitting the destination type, often creating
7027 // illegal source types, which then get legalized in isel-confusing ways,
7028 // leading to really terrible codegen. E.g.,
7029 // %result = v8i32 sext v8i8 %value
7031 // %losrc = extract_subreg %value, ...
7032 // %hisrc = extract_subreg %value, ...
7033 // %lo = v4i32 sext v4i8 %losrc
7034 // %hi = v4i32 sext v4i8 %hisrc
7035 // Things go rapidly downhill from there.
7037 // For ARM64, the [sz]ext vector instructions can only go up one element
7038 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7039 // take two instructions.
7041 // This implies that the most efficient way to do the extend from v8i8
7042 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7043 // the normal splitting to happen for the v8i16->v8i32.
7045 // This is pre-legalization to catch some cases where the default
7046 // type legalization will create ill-tempered code.
7047 if (!DCI.isBeforeLegalizeOps())
7050 // We're only interested in cleaning things up for non-legal vector types
7051 // here. If both the source and destination are legal, things will just
7052 // work naturally without any fiddling.
7053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7054 EVT ResVT = N->getValueType(0);
7055 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7057 // If the vector type isn't a simple VT, it's beyond the scope of what
7058 // we're worried about here. Let legalization do its thing and hope for
7060 if (!ResVT.isSimple())
7063 SDValue Src = N->getOperand(0);
7064 MVT SrcVT = Src->getValueType(0).getSimpleVT();
7065 // If the source VT is a 64-bit vector, we can play games and get the
7066 // better results we want.
7067 if (SrcVT.getSizeInBits() != 64)
7070 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7071 unsigned ElementCount = SrcVT.getVectorNumElements();
7072 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7074 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7076 // Now split the rest of the operation into two halves, each with a 64
7080 unsigned NumElements = ResVT.getVectorNumElements();
7081 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7082 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7083 ResVT.getVectorElementType(), NumElements / 2);
7085 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7086 LoVT.getVectorNumElements());
7087 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7088 DAG.getIntPtrConstant(0));
7089 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7090 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
7091 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7092 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7094 // Now combine the parts back together so we still have a single result
7095 // like the combiner expects.
7096 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7099 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7100 /// value. The load store optimizer pass will merge them to store pair stores.
7101 /// This has better performance than a splat of the scalar followed by a split
7102 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7103 /// followed by an ext.b and two stores.
7104 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7105 SDValue StVal = St->getValue();
7106 EVT VT = StVal.getValueType();
7108 // Don't replace floating point stores, they possibly won't be transformed to
7109 // stp because of the store pair suppress pass.
7110 if (VT.isFloatingPoint())
7113 // Check for insert vector elements.
7114 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7117 // We can express a splat as store pair(s) for 2 or 4 elements.
7118 unsigned NumVecElts = VT.getVectorNumElements();
7119 if (NumVecElts != 4 && NumVecElts != 2)
7121 SDValue SplatVal = StVal.getOperand(1);
7122 unsigned RemainInsertElts = NumVecElts - 1;
7124 // Check that this is a splat.
7125 while (--RemainInsertElts) {
7126 SDValue NextInsertElt = StVal.getOperand(0);
7127 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7129 if (NextInsertElt.getOperand(1) != SplatVal)
7131 StVal = NextInsertElt;
7133 unsigned OrigAlignment = St->getAlignment();
7134 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7135 unsigned Alignment = std::min(OrigAlignment, EltOffset);
7137 // Create scalar stores. This is at least as good as the code sequence for a
7138 // split unaligned store wich is a dup.s, ext.b, and two stores.
7139 // Most of the time the three stores should be replaced by store pair
7140 // instructions (stp).
7142 SDValue BasePtr = St->getBasePtr();
7144 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7145 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7147 unsigned Offset = EltOffset;
7148 while (--NumVecElts) {
7149 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7150 DAG.getConstant(Offset, MVT::i64));
7151 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7152 St->getPointerInfo(), St->isVolatile(),
7153 St->isNonTemporal(), Alignment);
7154 Offset += EltOffset;
7159 static SDValue performSTORECombine(SDNode *N,
7160 TargetLowering::DAGCombinerInfo &DCI,
7162 const ARM64Subtarget *Subtarget) {
7163 if (!DCI.isBeforeLegalize())
7166 StoreSDNode *S = cast<StoreSDNode>(N);
7167 if (S->isVolatile())
7170 // Cyclone has bad performance on unaligned 16B stores when crossing line and
7171 // page boundries. We want to split such stores.
7172 if (!Subtarget->isCyclone())
7175 // Don't split at Oz.
7176 MachineFunction &MF = DAG.getMachineFunction();
7177 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7178 AttributeSet::FunctionIndex, Attribute::MinSize);
7182 SDValue StVal = S->getValue();
7183 EVT VT = StVal.getValueType();
7185 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7186 // those up regresses performance on micro-benchmarks and olden/bh.
7187 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7190 // Split unaligned 16B stores. They are terrible for performance.
7191 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7192 // extensions can use this to mark that it does not want splitting to happen
7193 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7194 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7195 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7196 S->getAlignment() <= 2)
7199 // If we get a splat of a scalar convert this vector store to a store of
7200 // scalars. They will be merged into store pairs thereby removing two
7202 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7203 if (ReplacedSplat != SDValue())
7204 return ReplacedSplat;
7207 unsigned NumElts = VT.getVectorNumElements() / 2;
7208 // Split VT into two.
7210 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7211 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7212 DAG.getIntPtrConstant(0));
7213 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7214 DAG.getIntPtrConstant(NumElts));
7215 SDValue BasePtr = S->getBasePtr();
7217 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7218 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7219 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7220 DAG.getConstant(8, MVT::i64));
7221 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7222 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7226 // Optimize compare with zero and branch.
7227 static SDValue performBRCONDCombine(SDNode *N,
7228 TargetLowering::DAGCombinerInfo &DCI,
7229 SelectionDAG &DAG) {
7230 SDValue Chain = N->getOperand(0);
7231 SDValue Dest = N->getOperand(1);
7232 SDValue CCVal = N->getOperand(2);
7233 SDValue Cmp = N->getOperand(3);
7235 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7236 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7237 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
7240 unsigned CmpOpc = Cmp.getOpcode();
7241 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
7244 // Only attempt folding if there is only one use of the flag and no use of the
7246 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7249 SDValue LHS = Cmp.getOperand(0);
7250 SDValue RHS = Cmp.getOperand(1);
7252 assert(LHS.getValueType() == RHS.getValueType() &&
7253 "Expected the value type to be the same for both operands!");
7254 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7257 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7258 std::swap(LHS, RHS);
7260 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7263 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7264 LHS.getOpcode() == ISD::SRL)
7267 // Fold the compare into the branch instruction.
7269 if (CC == ARM64CC::EQ)
7270 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7272 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7274 // Do not add new nodes to DAG combiner worklist.
7275 DCI.CombineTo(N, BR, false);
7280 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7281 DAGCombinerInfo &DCI) const {
7282 SelectionDAG &DAG = DCI.DAG;
7283 switch (N->getOpcode()) {
7288 return performAddSubLongCombine(N, DCI, DAG);
7290 return performXorCombine(N, DAG, DCI, Subtarget);
7292 return performMulCombine(N, DAG, DCI, Subtarget);
7293 case ISD::SINT_TO_FP:
7294 case ISD::UINT_TO_FP:
7295 return performIntToFpCombine(N, DAG);
7297 return performORCombine(N, DCI, Subtarget);
7298 case ISD::INTRINSIC_WO_CHAIN:
7299 return performIntrinsicCombine(N, DCI, Subtarget);
7300 case ISD::ANY_EXTEND:
7301 case ISD::ZERO_EXTEND:
7302 case ISD::SIGN_EXTEND:
7303 return performExtendCombine(N, DCI, DAG);
7305 return performBitcastCombine(N, DCI, DAG);
7306 case ISD::CONCAT_VECTORS:
7307 return performConcatVectorsCombine(N, DCI, DAG);
7309 return performSTORECombine(N, DCI, DAG, Subtarget);
7310 case ARM64ISD::BRCOND:
7311 return performBRCONDCombine(N, DCI, DAG);
7316 // Check if the return value is used as only a return value, as otherwise
7317 // we can't perform a tail-call. In particular, we need to check for
7318 // target ISD nodes that are returns and any other "odd" constructs
7319 // that the generic analysis code won't necessarily catch.
7320 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7321 if (N->getNumValues() != 1)
7323 if (!N->hasNUsesOfValue(1, 0))
7326 SDValue TCChain = Chain;
7327 SDNode *Copy = *N->use_begin();
7328 if (Copy->getOpcode() == ISD::CopyToReg) {
7329 // If the copy has a glue operand, we conservatively assume it isn't safe to
7330 // perform a tail call.
7331 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7334 TCChain = Copy->getOperand(0);
7335 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7338 bool HasRet = false;
7339 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
7341 if (UI->getOpcode() != ARM64ISD::RET_FLAG)
7353 // Return whether the an instruction can potentially be optimized to a tail
7354 // call. This will cause the optimizers to attempt to move, or duplicate,
7355 // return instructions to help enable tail call optimizations for this
7357 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7358 if (!EnableARM64TailCalls)
7361 if (!CI->isTailCall())
7367 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7369 ISD::MemIndexedMode &AM,
7371 SelectionDAG &DAG) const {
7372 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7375 Base = Op->getOperand(0);
7376 // All of the indexed addressing mode instructions take a signed
7377 // 9 bit immediate offset.
7378 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7379 int64_t RHSC = (int64_t)RHS->getZExtValue();
7380 if (RHSC >= 256 || RHSC <= -256)
7382 IsInc = (Op->getOpcode() == ISD::ADD);
7383 Offset = Op->getOperand(1);
7389 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7391 ISD::MemIndexedMode &AM,
7392 SelectionDAG &DAG) const {
7395 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7396 VT = LD->getMemoryVT();
7397 Ptr = LD->getBasePtr();
7398 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7399 VT = ST->getMemoryVT();
7400 Ptr = ST->getBasePtr();
7405 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7407 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7411 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7414 ISD::MemIndexedMode &AM,
7415 SelectionDAG &DAG) const {
7418 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7419 VT = LD->getMemoryVT();
7420 Ptr = LD->getBasePtr();
7421 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7422 VT = ST->getMemoryVT();
7423 Ptr = ST->getBasePtr();
7428 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7430 // Post-indexing updates the base, so it's not a valid transform
7431 // if that's not the same as the load's pointer.
7434 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7438 /// The only 128-bit atomic operation is an stxp that succeeds. In particular
7439 /// neither ldp nor ldxp are atomic. So the canonical sequence for an atomic
7442 /// ldxp x0, x1, [x8]
7443 /// stxp w2, x0, x1, [x8]
7445 /// If the stxp succeeds then the ldxp managed to get both halves without an
7446 /// intervening stxp from a different thread and the read was atomic.
7447 static void ReplaceATOMIC_LOAD_128(SDNode *N, SmallVectorImpl<SDValue> &Results,
7448 SelectionDAG &DAG) {
7450 AtomicSDNode *AN = cast<AtomicSDNode>(N);
7451 EVT VT = AN->getMemoryVT();
7452 SDValue Zero = DAG.getConstant(0, VT);
7454 // FIXME: Really want ATOMIC_LOAD_NOP but that doesn't fit into the existing
7455 // scheme very well. Given the complexity of what we're already generating, an
7456 // extra couple of ORRs probably won't make much difference.
7457 SDValue Result = DAG.getAtomic(ISD::ATOMIC_LOAD_OR, DL, AN->getMemoryVT(),
7458 N->getOperand(0), N->getOperand(1), Zero,
7459 AN->getMemOperand(), AN->getOrdering(),
7460 AN->getSynchScope());
7462 Results.push_back(Result.getValue(0)); // Value
7463 Results.push_back(Result.getValue(1)); // Chain
7466 static void ReplaceATOMIC_OP_128(SDNode *N, SmallVectorImpl<SDValue> &Results,
7467 SelectionDAG &DAG, unsigned NewOp) {
7469 AtomicOrdering Ordering = cast<AtomicSDNode>(N)->getOrdering();
7470 assert(N->getValueType(0) == MVT::i128 &&
7471 "Only know how to expand i128 atomics");
7473 SmallVector<SDValue, 6> Ops;
7474 Ops.push_back(N->getOperand(1)); // Ptr
7476 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7477 N->getOperand(2), DAG.getIntPtrConstant(0)));
7478 // High part of Val1
7479 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7480 N->getOperand(2), DAG.getIntPtrConstant(1)));
7481 if (NewOp == ARM64::ATOMIC_CMP_SWAP_I128) {
7483 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7484 N->getOperand(3), DAG.getIntPtrConstant(0)));
7485 // High part of Val2
7486 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7487 N->getOperand(3), DAG.getIntPtrConstant(1)));
7490 Ops.push_back(DAG.getTargetConstant(Ordering, MVT::i32));
7491 Ops.push_back(N->getOperand(0)); // Chain
7493 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
7494 SDNode *Result = DAG.getMachineNode(NewOp, DL, Tys, Ops);
7495 SDValue OpsF[] = { SDValue(Result, 0), SDValue(Result, 1) };
7496 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, OpsF, 2));
7497 Results.push_back(SDValue(Result, 2));
7500 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7501 SmallVectorImpl<SDValue> &Results,
7502 SelectionDAG &DAG) const {
7503 switch (N->getOpcode()) {
7505 llvm_unreachable("Don't know how to custom expand this");
7506 case ISD::ATOMIC_LOAD:
7507 ReplaceATOMIC_LOAD_128(N, Results, DAG);
7509 case ISD::ATOMIC_LOAD_ADD:
7510 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_ADD_I128);
7512 case ISD::ATOMIC_LOAD_SUB:
7513 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_SUB_I128);
7515 case ISD::ATOMIC_LOAD_AND:
7516 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_AND_I128);
7518 case ISD::ATOMIC_LOAD_OR:
7519 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_OR_I128);
7521 case ISD::ATOMIC_LOAD_XOR:
7522 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_XOR_I128);
7524 case ISD::ATOMIC_LOAD_NAND:
7525 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_NAND_I128);
7527 case ISD::ATOMIC_SWAP:
7528 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_SWAP_I128);
7530 case ISD::ATOMIC_LOAD_MIN:
7531 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_MIN_I128);
7533 case ISD::ATOMIC_LOAD_MAX:
7534 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_MAX_I128);
7536 case ISD::ATOMIC_LOAD_UMIN:
7537 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_UMIN_I128);
7539 case ISD::ATOMIC_LOAD_UMAX:
7540 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_UMAX_I128);
7542 case ISD::ATOMIC_CMP_SWAP:
7543 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_CMP_SWAP_I128);
7545 case ISD::FP_TO_UINT:
7546 case ISD::FP_TO_SINT:
7547 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7548 // Let normal code take care of it by not adding anything to Results.