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 setTargetDAGCombine(ISD::VSELECT);
439 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
440 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
441 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
443 setStackPointerRegisterToSaveRestore(ARM64::SP);
445 setSchedulingPreference(Sched::Hybrid);
448 MaskAndBranchFoldingIsLegal = true;
450 setMinFunctionAlignment(2);
452 RequireStrictAlign = StrictAlign;
455 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
456 if (VT == MVT::v2f32) {
457 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
458 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
460 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
461 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
462 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
463 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
464 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
466 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
467 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
470 // Mark vector float intrinsics as expand.
471 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
472 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
473 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
474 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
475 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
476 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
477 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
478 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
479 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
480 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
483 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
484 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
485 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
486 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
487 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
488 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
489 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
490 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
491 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
492 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
493 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
494 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
496 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
497 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
498 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
499 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
501 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
502 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
503 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
504 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
505 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
507 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
508 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
511 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
512 addRegisterClass(VT, &ARM64::FPR64RegClass);
513 addTypeForNEON(VT, MVT::v2i32);
516 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
517 addRegisterClass(VT, &ARM64::FPR128RegClass);
518 addTypeForNEON(VT, MVT::v4i32);
521 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
524 return VT.changeVectorElementTypeToInteger();
527 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
528 /// Mask are known to be either zero or one and return them in the
529 /// KnownZero/KnownOne bitsets.
530 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
531 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
532 const SelectionDAG &DAG, unsigned Depth) const {
533 switch (Op.getOpcode()) {
536 case ARM64ISD::CSEL: {
537 APInt KnownZero2, KnownOne2;
538 DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
539 DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
540 KnownZero &= KnownZero2;
541 KnownOne &= KnownOne2;
544 case ISD::INTRINSIC_W_CHAIN:
546 case ISD::INTRINSIC_WO_CHAIN:
547 case ISD::INTRINSIC_VOID: {
548 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
552 case Intrinsic::arm64_neon_umaxv:
553 case Intrinsic::arm64_neon_uminv: {
554 // Figure out the datatype of the vector operand. The UMINV instruction
555 // will zero extend the result, so we can mark as known zero all the
556 // bits larger than the element datatype. 32-bit or larget doesn't need
557 // this as those are legal types and will be handled by isel directly.
558 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
559 unsigned BitWidth = KnownZero.getBitWidth();
560 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
561 assert(BitWidth >= 8 && "Unexpected width!");
562 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
564 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
565 assert(BitWidth >= 16 && "Unexpected width!");
566 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
576 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
580 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
581 // FIXME: On ARM64, this depends on the type.
582 // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
583 // and the offset has to be a multiple of the related size in bytes.
588 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
589 const TargetLibraryInfo *libInfo) const {
590 return ARM64::createFastISel(funcInfo, libInfo);
593 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
597 case ARM64ISD::CALL: return "ARM64ISD::CALL";
598 case ARM64ISD::ADRP: return "ARM64ISD::ADRP";
599 case ARM64ISD::ADDlow: return "ARM64ISD::ADDlow";
600 case ARM64ISD::LOADgot: return "ARM64ISD::LOADgot";
601 case ARM64ISD::RET_FLAG: return "ARM64ISD::RET_FLAG";
602 case ARM64ISD::BRCOND: return "ARM64ISD::BRCOND";
603 case ARM64ISD::CSEL: return "ARM64ISD::CSEL";
604 case ARM64ISD::FCSEL: return "ARM64ISD::FCSEL";
605 case ARM64ISD::CSINV: return "ARM64ISD::CSINV";
606 case ARM64ISD::CSNEG: return "ARM64ISD::CSNEG";
607 case ARM64ISD::CSINC: return "ARM64ISD::CSINC";
608 case ARM64ISD::THREAD_POINTER: return "ARM64ISD::THREAD_POINTER";
609 case ARM64ISD::TLSDESC_CALL: return "ARM64ISD::TLSDESC_CALL";
610 case ARM64ISD::ADC: return "ARM64ISD::ADC";
611 case ARM64ISD::SBC: return "ARM64ISD::SBC";
612 case ARM64ISD::ADDS: return "ARM64ISD::ADDS";
613 case ARM64ISD::SUBS: return "ARM64ISD::SUBS";
614 case ARM64ISD::ADCS: return "ARM64ISD::ADCS";
615 case ARM64ISD::SBCS: return "ARM64ISD::SBCS";
616 case ARM64ISD::ANDS: return "ARM64ISD::ANDS";
617 case ARM64ISD::FCMP: return "ARM64ISD::FCMP";
618 case ARM64ISD::FMIN: return "ARM64ISD::FMIN";
619 case ARM64ISD::FMAX: return "ARM64ISD::FMAX";
620 case ARM64ISD::DUP: return "ARM64ISD::DUP";
621 case ARM64ISD::DUPLANE8: return "ARM64ISD::DUPLANE8";
622 case ARM64ISD::DUPLANE16: return "ARM64ISD::DUPLANE16";
623 case ARM64ISD::DUPLANE32: return "ARM64ISD::DUPLANE32";
624 case ARM64ISD::DUPLANE64: return "ARM64ISD::DUPLANE64";
625 case ARM64ISD::MOVI: return "ARM64ISD::MOVI";
626 case ARM64ISD::MOVIshift: return "ARM64ISD::MOVIshift";
627 case ARM64ISD::MOVIedit: return "ARM64ISD::MOVIedit";
628 case ARM64ISD::MOVImsl: return "ARM64ISD::MOVImsl";
629 case ARM64ISD::FMOV: return "ARM64ISD::FMOV";
630 case ARM64ISD::MVNIshift: return "ARM64ISD::MVNIshift";
631 case ARM64ISD::MVNImsl: return "ARM64ISD::MVNImsl";
632 case ARM64ISD::BICi: return "ARM64ISD::BICi";
633 case ARM64ISD::ORRi: return "ARM64ISD::ORRi";
634 case ARM64ISD::NEG: return "ARM64ISD::NEG";
635 case ARM64ISD::EXTR: return "ARM64ISD::EXTR";
636 case ARM64ISD::ZIP1: return "ARM64ISD::ZIP1";
637 case ARM64ISD::ZIP2: return "ARM64ISD::ZIP2";
638 case ARM64ISD::UZP1: return "ARM64ISD::UZP1";
639 case ARM64ISD::UZP2: return "ARM64ISD::UZP2";
640 case ARM64ISD::TRN1: return "ARM64ISD::TRN1";
641 case ARM64ISD::TRN2: return "ARM64ISD::TRN2";
642 case ARM64ISD::REV16: return "ARM64ISD::REV16";
643 case ARM64ISD::REV32: return "ARM64ISD::REV32";
644 case ARM64ISD::REV64: return "ARM64ISD::REV64";
645 case ARM64ISD::EXT: return "ARM64ISD::EXT";
646 case ARM64ISD::VSHL: return "ARM64ISD::VSHL";
647 case ARM64ISD::VLSHR: return "ARM64ISD::VLSHR";
648 case ARM64ISD::VASHR: return "ARM64ISD::VASHR";
649 case ARM64ISD::CMEQ: return "ARM64ISD::CMEQ";
650 case ARM64ISD::CMGE: return "ARM64ISD::CMGE";
651 case ARM64ISD::CMGT: return "ARM64ISD::CMGT";
652 case ARM64ISD::CMHI: return "ARM64ISD::CMHI";
653 case ARM64ISD::CMHS: return "ARM64ISD::CMHS";
654 case ARM64ISD::FCMEQ: return "ARM64ISD::FCMEQ";
655 case ARM64ISD::FCMGE: return "ARM64ISD::FCMGE";
656 case ARM64ISD::FCMGT: return "ARM64ISD::FCMGT";
657 case ARM64ISD::CMEQz: return "ARM64ISD::CMEQz";
658 case ARM64ISD::CMGEz: return "ARM64ISD::CMGEz";
659 case ARM64ISD::CMGTz: return "ARM64ISD::CMGTz";
660 case ARM64ISD::CMLEz: return "ARM64ISD::CMLEz";
661 case ARM64ISD::CMLTz: return "ARM64ISD::CMLTz";
662 case ARM64ISD::FCMEQz: return "ARM64ISD::FCMEQz";
663 case ARM64ISD::FCMGEz: return "ARM64ISD::FCMGEz";
664 case ARM64ISD::FCMGTz: return "ARM64ISD::FCMGTz";
665 case ARM64ISD::FCMLEz: return "ARM64ISD::FCMLEz";
666 case ARM64ISD::FCMLTz: return "ARM64ISD::FCMLTz";
667 case ARM64ISD::NOT: return "ARM64ISD::NOT";
668 case ARM64ISD::BIT: return "ARM64ISD::BIT";
669 case ARM64ISD::CBZ: return "ARM64ISD::CBZ";
670 case ARM64ISD::CBNZ: return "ARM64ISD::CBNZ";
671 case ARM64ISD::TBZ: return "ARM64ISD::TBZ";
672 case ARM64ISD::TBNZ: return "ARM64ISD::TBNZ";
673 case ARM64ISD::TC_RETURN: return "ARM64ISD::TC_RETURN";
674 case ARM64ISD::SITOF: return "ARM64ISD::SITOF";
675 case ARM64ISD::UITOF: return "ARM64ISD::UITOF";
676 case ARM64ISD::SQSHL_I: return "ARM64ISD::SQSHL_I";
677 case ARM64ISD::UQSHL_I: return "ARM64ISD::UQSHL_I";
678 case ARM64ISD::SRSHR_I: return "ARM64ISD::SRSHR_I";
679 case ARM64ISD::URSHR_I: return "ARM64ISD::URSHR_I";
680 case ARM64ISD::SQSHLU_I: return "ARM64ISD::SQSHLU_I";
681 case ARM64ISD::WrapperLarge: return "ARM64ISD::WrapperLarge";
685 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
686 unsigned &LdrOpc, unsigned &StrOpc) {
687 static unsigned LoadBares[] = { ARM64::LDXRB, ARM64::LDXRH, ARM64::LDXRW,
688 ARM64::LDXRX, ARM64::LDXPX };
689 static unsigned LoadAcqs[] = { ARM64::LDAXRB, ARM64::LDAXRH, ARM64::LDAXRW,
690 ARM64::LDAXRX, ARM64::LDAXPX };
691 static unsigned StoreBares[] = { ARM64::STXRB, ARM64::STXRH, ARM64::STXRW,
692 ARM64::STXRX, ARM64::STXPX };
693 static unsigned StoreRels[] = { ARM64::STLXRB, ARM64::STLXRH, ARM64::STLXRW,
694 ARM64::STLXRX, ARM64::STLXPX };
696 unsigned *LoadOps, *StoreOps;
697 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
702 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
703 StoreOps = StoreRels;
705 StoreOps = StoreBares;
707 assert(isPowerOf2_32(Size) && Size <= 16 &&
708 "unsupported size for atomic binary op!");
710 LdrOpc = LoadOps[Log2_32(Size)];
711 StrOpc = StoreOps[Log2_32(Size)];
714 MachineBasicBlock *ARM64TargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
715 MachineBasicBlock *BB,
716 unsigned Size) const {
717 unsigned dest = MI->getOperand(0).getReg();
718 unsigned ptr = MI->getOperand(1).getReg();
719 unsigned oldval = MI->getOperand(2).getReg();
720 unsigned newval = MI->getOperand(3).getReg();
721 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
722 unsigned scratch = BB->getParent()->getRegInfo().createVirtualRegister(
723 &ARM64::GPR32RegClass);
724 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
725 DebugLoc dl = MI->getDebugLoc();
727 // FIXME: We currently always generate a seq_cst operation; we should
728 // be able to relax this in some cases.
729 unsigned ldrOpc, strOpc;
730 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
732 MachineFunction *MF = BB->getParent();
733 const BasicBlock *LLVM_BB = BB->getBasicBlock();
734 MachineFunction::iterator It = BB;
735 ++It; // insert the new blocks after the current block
737 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
738 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
739 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
740 MF->insert(It, loop1MBB);
741 MF->insert(It, loop2MBB);
742 MF->insert(It, exitMBB);
744 // Transfer the remainder of BB and its successor edges to exitMBB.
745 exitMBB->splice(exitMBB->begin(), BB,
746 std::next(MachineBasicBlock::iterator(MI)), BB->end());
747 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
751 // fallthrough --> loop1MBB
752 BB->addSuccessor(loop1MBB);
759 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
760 BuildMI(BB, dl, TII->get(Size == 8 ? ARM64::SUBSXrr : ARM64::SUBSWrr))
761 .addReg(Size == 8 ? ARM64::XZR : ARM64::WZR, RegState::Define)
764 BuildMI(BB, dl, TII->get(ARM64::Bcc)).addImm(ARM64CC::NE).addMBB(exitMBB);
765 BB->addSuccessor(loop2MBB);
766 BB->addSuccessor(exitMBB);
769 // strex scratch, newval, [ptr]
773 BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
774 BuildMI(BB, dl, TII->get(ARM64::CBNZW)).addReg(scratch).addMBB(loop1MBB);
775 BB->addSuccessor(loop1MBB);
776 BB->addSuccessor(exitMBB);
782 MI->eraseFromParent(); // The instruction is gone now.
788 ARM64TargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
789 unsigned Size, unsigned BinOpcode) const {
790 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
791 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
793 const BasicBlock *LLVM_BB = BB->getBasicBlock();
794 MachineFunction *MF = BB->getParent();
795 MachineFunction::iterator It = BB;
798 unsigned dest = MI->getOperand(0).getReg();
799 unsigned ptr = MI->getOperand(1).getReg();
800 unsigned incr = MI->getOperand(2).getReg();
801 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
802 DebugLoc dl = MI->getDebugLoc();
804 unsigned ldrOpc, strOpc;
805 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
807 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
808 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
809 MF->insert(It, loopMBB);
810 MF->insert(It, exitMBB);
812 // Transfer the remainder of BB and its successor edges to exitMBB.
813 exitMBB->splice(exitMBB->begin(), BB,
814 std::next(MachineBasicBlock::iterator(MI)), BB->end());
815 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
817 MachineRegisterInfo &RegInfo = MF->getRegInfo();
818 unsigned scratch = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
822 : RegInfo.createVirtualRegister(Size == 8 ? &ARM64::GPR64RegClass
823 : &ARM64::GPR32RegClass);
827 // fallthrough --> loopMBB
828 BB->addSuccessor(loopMBB);
832 // <binop> scratch2, dest, incr
833 // stxr scratch, scratch2, ptr
834 // cbnz scratch, loopMBB
835 // fallthrough --> exitMBB
837 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
839 // operand order needs to go the other way for NAND
840 if (BinOpcode == ARM64::BICWrr || BinOpcode == ARM64::BICXrr)
841 BuildMI(BB, dl, TII->get(BinOpcode), scratch2).addReg(incr).addReg(dest);
843 BuildMI(BB, dl, TII->get(BinOpcode), scratch2).addReg(dest).addReg(incr);
846 BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
847 BuildMI(BB, dl, TII->get(ARM64::CBNZW)).addReg(scratch).addMBB(loopMBB);
849 BB->addSuccessor(loopMBB);
850 BB->addSuccessor(exitMBB);
856 MI->eraseFromParent(); // The instruction is gone now.
861 MachineBasicBlock *ARM64TargetLowering::EmitAtomicBinary128(
862 MachineInstr *MI, MachineBasicBlock *BB, unsigned BinOpcodeLo,
863 unsigned BinOpcodeHi) const {
864 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
865 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
867 const BasicBlock *LLVM_BB = BB->getBasicBlock();
868 MachineFunction *MF = BB->getParent();
869 MachineFunction::iterator It = BB;
872 unsigned DestLo = MI->getOperand(0).getReg();
873 unsigned DestHi = MI->getOperand(1).getReg();
874 unsigned Ptr = MI->getOperand(2).getReg();
875 unsigned IncrLo = MI->getOperand(3).getReg();
876 unsigned IncrHi = MI->getOperand(4).getReg();
877 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(5).getImm());
878 DebugLoc DL = MI->getDebugLoc();
880 unsigned LdrOpc, StrOpc;
881 getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
883 MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
884 MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
885 MF->insert(It, LoopMBB);
886 MF->insert(It, ExitMBB);
888 // Transfer the remainder of BB and its successor edges to exitMBB.
889 ExitMBB->splice(ExitMBB->begin(), BB,
890 std::next(MachineBasicBlock::iterator(MI)), BB->end());
891 ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
893 MachineRegisterInfo &RegInfo = MF->getRegInfo();
894 unsigned ScratchRes = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
895 unsigned ScratchLo = IncrLo, ScratchHi = IncrHi;
897 assert(BinOpcodeHi && "Expect neither or both opcodes to be defined");
898 ScratchLo = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
899 ScratchHi = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
904 // fallthrough --> LoopMBB
905 BB->addSuccessor(LoopMBB);
908 // ldxp DestLo, DestHi, Ptr
909 // <binoplo> ScratchLo, DestLo, IncrLo
910 // <binophi> ScratchHi, DestHi, IncrHi
911 // stxp ScratchRes, ScratchLo, ScratchHi, ptr
912 // cbnz ScratchRes, LoopMBB
913 // fallthrough --> ExitMBB
915 BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
916 .addReg(DestHi, RegState::Define)
919 // operand order needs to go the other way for NAND
920 if (BinOpcodeLo == ARM64::BICXrr) {
921 std::swap(IncrLo, DestLo);
922 std::swap(IncrHi, DestHi);
925 BuildMI(BB, DL, TII->get(BinOpcodeLo), ScratchLo).addReg(DestLo).addReg(
927 BuildMI(BB, DL, TII->get(BinOpcodeHi), ScratchHi).addReg(DestHi).addReg(
931 BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
935 BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(LoopMBB);
937 BB->addSuccessor(LoopMBB);
938 BB->addSuccessor(ExitMBB);
944 MI->eraseFromParent(); // The instruction is gone now.
950 ARM64TargetLowering::EmitAtomicCmpSwap128(MachineInstr *MI,
951 MachineBasicBlock *BB) const {
952 unsigned DestLo = MI->getOperand(0).getReg();
953 unsigned DestHi = MI->getOperand(1).getReg();
954 unsigned Ptr = MI->getOperand(2).getReg();
955 unsigned OldValLo = MI->getOperand(3).getReg();
956 unsigned OldValHi = MI->getOperand(4).getReg();
957 unsigned NewValLo = MI->getOperand(5).getReg();
958 unsigned NewValHi = MI->getOperand(6).getReg();
959 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(7).getImm());
960 unsigned ScratchRes = BB->getParent()->getRegInfo().createVirtualRegister(
961 &ARM64::GPR32RegClass);
962 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
963 DebugLoc DL = MI->getDebugLoc();
965 unsigned LdrOpc, StrOpc;
966 getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
968 MachineFunction *MF = BB->getParent();
969 const BasicBlock *LLVM_BB = BB->getBasicBlock();
970 MachineFunction::iterator It = BB;
971 ++It; // insert the new blocks after the current block
973 MachineBasicBlock *Loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
974 MachineBasicBlock *Loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
975 MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
976 MF->insert(It, Loop1MBB);
977 MF->insert(It, Loop2MBB);
978 MF->insert(It, ExitMBB);
980 // Transfer the remainder of BB and its successor edges to exitMBB.
981 ExitMBB->splice(ExitMBB->begin(), BB,
982 std::next(MachineBasicBlock::iterator(MI)), BB->end());
983 ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
987 // fallthrough --> Loop1MBB
988 BB->addSuccessor(Loop1MBB);
991 // ldxp DestLo, DestHi, [Ptr]
992 // cmp DestLo, OldValLo
993 // sbc xzr, DestHi, OldValHi
996 BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
997 .addReg(DestHi, RegState::Define)
999 BuildMI(BB, DL, TII->get(ARM64::SUBSXrr), ARM64::XZR).addReg(DestLo).addReg(
1001 BuildMI(BB, DL, TII->get(ARM64::SBCXr), ARM64::XZR).addReg(DestHi).addReg(
1004 BuildMI(BB, DL, TII->get(ARM64::Bcc)).addImm(ARM64CC::NE).addMBB(ExitMBB);
1005 BB->addSuccessor(Loop2MBB);
1006 BB->addSuccessor(ExitMBB);
1009 // stxp ScratchRes, NewValLo, NewValHi, [Ptr]
1010 // cbnz ScratchRes, Loop1MBB
1012 BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
1016 BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(Loop1MBB);
1017 BB->addSuccessor(Loop1MBB);
1018 BB->addSuccessor(ExitMBB);
1024 MI->eraseFromParent(); // The instruction is gone now.
1029 MachineBasicBlock *ARM64TargetLowering::EmitAtomicMinMax128(
1030 MachineInstr *MI, MachineBasicBlock *BB, unsigned CondCode) const {
1031 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
1032 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1034 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1035 MachineFunction *MF = BB->getParent();
1036 MachineFunction::iterator It = BB;
1039 unsigned DestLo = MI->getOperand(0).getReg();
1040 unsigned DestHi = MI->getOperand(1).getReg();
1041 unsigned Ptr = MI->getOperand(2).getReg();
1042 unsigned IncrLo = MI->getOperand(3).getReg();
1043 unsigned IncrHi = MI->getOperand(4).getReg();
1044 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(5).getImm());
1045 DebugLoc DL = MI->getDebugLoc();
1047 unsigned LdrOpc, StrOpc;
1048 getExclusiveOperation(16, Ord, LdrOpc, StrOpc);
1050 MachineBasicBlock *LoopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1051 MachineBasicBlock *ExitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1052 MF->insert(It, LoopMBB);
1053 MF->insert(It, ExitMBB);
1055 // Transfer the remainder of BB and its successor edges to exitMBB.
1056 ExitMBB->splice(ExitMBB->begin(), BB,
1057 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1058 ExitMBB->transferSuccessorsAndUpdatePHIs(BB);
1060 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1061 unsigned ScratchRes = RegInfo.createVirtualRegister(&ARM64::GPR32RegClass);
1062 unsigned ScratchLo = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
1063 unsigned ScratchHi = RegInfo.createVirtualRegister(&ARM64::GPR64RegClass);
1067 // fallthrough --> LoopMBB
1068 BB->addSuccessor(LoopMBB);
1071 // ldxp DestLo, DestHi, Ptr
1072 // cmp ScratchLo, DestLo, IncrLo
1073 // sbc xzr, ScratchHi, DestHi, IncrHi
1074 // csel ScratchLo, DestLo, IncrLo, <cmp-op>
1075 // csel ScratchHi, DestHi, IncrHi, <cmp-op>
1076 // stxp ScratchRes, ScratchLo, ScratchHi, ptr
1077 // cbnz ScratchRes, LoopMBB
1078 // fallthrough --> ExitMBB
1080 BuildMI(BB, DL, TII->get(LdrOpc), DestLo)
1081 .addReg(DestHi, RegState::Define)
1084 BuildMI(BB, DL, TII->get(ARM64::SUBSXrr), ARM64::XZR).addReg(DestLo).addReg(
1086 BuildMI(BB, DL, TII->get(ARM64::SBCXr), ARM64::XZR).addReg(DestHi).addReg(
1089 BuildMI(BB, DL, TII->get(ARM64::CSELXr), ScratchLo)
1093 BuildMI(BB, DL, TII->get(ARM64::CSELXr), ScratchHi)
1098 BuildMI(BB, DL, TII->get(StrOpc), ScratchRes)
1102 BuildMI(BB, DL, TII->get(ARM64::CBNZW)).addReg(ScratchRes).addMBB(LoopMBB);
1104 BB->addSuccessor(LoopMBB);
1105 BB->addSuccessor(ExitMBB);
1111 MI->eraseFromParent(); // The instruction is gone now.
1117 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
1118 MachineBasicBlock *MBB) const {
1119 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1123 // [... previous instrs leading to comparison ...]
1129 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1131 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1132 MachineFunction *MF = MBB->getParent();
1133 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1134 DebugLoc DL = MI->getDebugLoc();
1135 MachineFunction::iterator It = MBB;
1138 unsigned DestReg = MI->getOperand(0).getReg();
1139 unsigned IfTrueReg = MI->getOperand(1).getReg();
1140 unsigned IfFalseReg = MI->getOperand(2).getReg();
1141 unsigned CondCode = MI->getOperand(3).getImm();
1142 bool CPSRKilled = MI->getOperand(4).isKill();
1144 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1145 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1146 MF->insert(It, TrueBB);
1147 MF->insert(It, EndBB);
1149 // Transfer rest of current basic-block to EndBB
1150 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1152 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1154 BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1155 BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
1156 MBB->addSuccessor(TrueBB);
1157 MBB->addSuccessor(EndBB);
1159 // TrueBB falls through to the end.
1160 TrueBB->addSuccessor(EndBB);
1163 TrueBB->addLiveIn(ARM64::CPSR);
1164 EndBB->addLiveIn(ARM64::CPSR);
1167 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
1173 MI->eraseFromParent();
1178 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1179 MachineBasicBlock *BB) const {
1180 switch (MI->getOpcode()) {
1185 assert(0 && "Unexpected instruction for custom inserter!");
1188 case ARM64::ATOMIC_LOAD_ADD_I8:
1189 return EmitAtomicBinary(MI, BB, 1, ARM64::ADDWrr);
1190 case ARM64::ATOMIC_LOAD_ADD_I16:
1191 return EmitAtomicBinary(MI, BB, 2, ARM64::ADDWrr);
1192 case ARM64::ATOMIC_LOAD_ADD_I32:
1193 return EmitAtomicBinary(MI, BB, 4, ARM64::ADDWrr);
1194 case ARM64::ATOMIC_LOAD_ADD_I64:
1195 return EmitAtomicBinary(MI, BB, 8, ARM64::ADDXrr);
1196 case ARM64::ATOMIC_LOAD_ADD_I128:
1197 return EmitAtomicBinary128(MI, BB, ARM64::ADDSXrr, ARM64::ADCXr);
1199 case ARM64::ATOMIC_LOAD_AND_I8:
1200 return EmitAtomicBinary(MI, BB, 1, ARM64::ANDWrr);
1201 case ARM64::ATOMIC_LOAD_AND_I16:
1202 return EmitAtomicBinary(MI, BB, 2, ARM64::ANDWrr);
1203 case ARM64::ATOMIC_LOAD_AND_I32:
1204 return EmitAtomicBinary(MI, BB, 4, ARM64::ANDWrr);
1205 case ARM64::ATOMIC_LOAD_AND_I64:
1206 return EmitAtomicBinary(MI, BB, 8, ARM64::ANDXrr);
1207 case ARM64::ATOMIC_LOAD_AND_I128:
1208 return EmitAtomicBinary128(MI, BB, ARM64::ANDXrr, ARM64::ANDXrr);
1210 case ARM64::ATOMIC_LOAD_OR_I8:
1211 return EmitAtomicBinary(MI, BB, 1, ARM64::ORRWrr);
1212 case ARM64::ATOMIC_LOAD_OR_I16:
1213 return EmitAtomicBinary(MI, BB, 2, ARM64::ORRWrr);
1214 case ARM64::ATOMIC_LOAD_OR_I32:
1215 return EmitAtomicBinary(MI, BB, 4, ARM64::ORRWrr);
1216 case ARM64::ATOMIC_LOAD_OR_I64:
1217 return EmitAtomicBinary(MI, BB, 8, ARM64::ORRXrr);
1218 case ARM64::ATOMIC_LOAD_OR_I128:
1219 return EmitAtomicBinary128(MI, BB, ARM64::ORRXrr, ARM64::ORRXrr);
1221 case ARM64::ATOMIC_LOAD_XOR_I8:
1222 return EmitAtomicBinary(MI, BB, 1, ARM64::EORWrr);
1223 case ARM64::ATOMIC_LOAD_XOR_I16:
1224 return EmitAtomicBinary(MI, BB, 2, ARM64::EORWrr);
1225 case ARM64::ATOMIC_LOAD_XOR_I32:
1226 return EmitAtomicBinary(MI, BB, 4, ARM64::EORWrr);
1227 case ARM64::ATOMIC_LOAD_XOR_I64:
1228 return EmitAtomicBinary(MI, BB, 8, ARM64::EORXrr);
1229 case ARM64::ATOMIC_LOAD_XOR_I128:
1230 return EmitAtomicBinary128(MI, BB, ARM64::EORXrr, ARM64::EORXrr);
1232 case ARM64::ATOMIC_LOAD_NAND_I8:
1233 return EmitAtomicBinary(MI, BB, 1, ARM64::BICWrr);
1234 case ARM64::ATOMIC_LOAD_NAND_I16:
1235 return EmitAtomicBinary(MI, BB, 2, ARM64::BICWrr);
1236 case ARM64::ATOMIC_LOAD_NAND_I32:
1237 return EmitAtomicBinary(MI, BB, 4, ARM64::BICWrr);
1238 case ARM64::ATOMIC_LOAD_NAND_I64:
1239 return EmitAtomicBinary(MI, BB, 8, ARM64::BICXrr);
1240 case ARM64::ATOMIC_LOAD_NAND_I128:
1241 return EmitAtomicBinary128(MI, BB, ARM64::BICXrr, ARM64::BICXrr);
1243 case ARM64::ATOMIC_LOAD_SUB_I8:
1244 return EmitAtomicBinary(MI, BB, 1, ARM64::SUBWrr);
1245 case ARM64::ATOMIC_LOAD_SUB_I16:
1246 return EmitAtomicBinary(MI, BB, 2, ARM64::SUBWrr);
1247 case ARM64::ATOMIC_LOAD_SUB_I32:
1248 return EmitAtomicBinary(MI, BB, 4, ARM64::SUBWrr);
1249 case ARM64::ATOMIC_LOAD_SUB_I64:
1250 return EmitAtomicBinary(MI, BB, 8, ARM64::SUBXrr);
1251 case ARM64::ATOMIC_LOAD_SUB_I128:
1252 return EmitAtomicBinary128(MI, BB, ARM64::SUBSXrr, ARM64::SBCXr);
1254 case ARM64::ATOMIC_LOAD_MIN_I128:
1255 return EmitAtomicMinMax128(MI, BB, ARM64CC::LT);
1257 case ARM64::ATOMIC_LOAD_MAX_I128:
1258 return EmitAtomicMinMax128(MI, BB, ARM64CC::GT);
1260 case ARM64::ATOMIC_LOAD_UMIN_I128:
1261 return EmitAtomicMinMax128(MI, BB, ARM64CC::CC);
1263 case ARM64::ATOMIC_LOAD_UMAX_I128:
1264 return EmitAtomicMinMax128(MI, BB, ARM64CC::HI);
1266 case ARM64::ATOMIC_SWAP_I8:
1267 return EmitAtomicBinary(MI, BB, 1, 0);
1268 case ARM64::ATOMIC_SWAP_I16:
1269 return EmitAtomicBinary(MI, BB, 2, 0);
1270 case ARM64::ATOMIC_SWAP_I32:
1271 return EmitAtomicBinary(MI, BB, 4, 0);
1272 case ARM64::ATOMIC_SWAP_I64:
1273 return EmitAtomicBinary(MI, BB, 8, 0);
1274 case ARM64::ATOMIC_SWAP_I128:
1275 return EmitAtomicBinary128(MI, BB, 0, 0);
1277 case ARM64::ATOMIC_CMP_SWAP_I8:
1278 return EmitAtomicCmpSwap(MI, BB, 1);
1279 case ARM64::ATOMIC_CMP_SWAP_I16:
1280 return EmitAtomicCmpSwap(MI, BB, 2);
1281 case ARM64::ATOMIC_CMP_SWAP_I32:
1282 return EmitAtomicCmpSwap(MI, BB, 4);
1283 case ARM64::ATOMIC_CMP_SWAP_I64:
1284 return EmitAtomicCmpSwap(MI, BB, 8);
1285 case ARM64::ATOMIC_CMP_SWAP_I128:
1286 return EmitAtomicCmpSwap128(MI, BB);
1288 case ARM64::F128CSEL:
1289 return EmitF128CSEL(MI, BB);
1291 case TargetOpcode::STACKMAP:
1292 case TargetOpcode::PATCHPOINT:
1293 return emitPatchPoint(MI, BB);
1295 llvm_unreachable("Unexpected instruction for custom inserter!");
1298 //===----------------------------------------------------------------------===//
1299 // ARM64 Lowering private implementation.
1300 //===----------------------------------------------------------------------===//
1302 //===----------------------------------------------------------------------===//
1304 //===----------------------------------------------------------------------===//
1306 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
1307 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
1310 llvm_unreachable("Unknown condition code!");
1334 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
1335 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
1336 ARM64CC::CondCode &CondCode2) {
1337 CondCode2 = ARM64CC::AL;
1340 llvm_unreachable("Unknown FP condition!");
1343 CondCode = ARM64CC::EQ;
1347 CondCode = ARM64CC::GT;
1351 CondCode = ARM64CC::GE;
1354 CondCode = ARM64CC::MI;
1357 CondCode = ARM64CC::LS;
1360 CondCode = ARM64CC::MI;
1361 CondCode2 = ARM64CC::GT;
1364 CondCode = ARM64CC::VC;
1367 CondCode = ARM64CC::VS;
1370 CondCode = ARM64CC::EQ;
1371 CondCode2 = ARM64CC::VS;
1374 CondCode = ARM64CC::HI;
1377 CondCode = ARM64CC::PL;
1381 CondCode = ARM64CC::LT;
1385 CondCode = ARM64CC::LE;
1389 CondCode = ARM64CC::NE;
1394 static bool isLegalArithImmed(uint64_t C) {
1395 // Matches ARM64DAGToDAGISel::SelectArithImmed().
1396 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1399 static SDValue emitComparison(SDValue LHS, SDValue RHS, SDLoc dl,
1400 SelectionDAG &DAG) {
1401 EVT VT = LHS.getValueType();
1403 if (VT.isFloatingPoint())
1404 return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
1406 // The CMP instruction is just an alias for SUBS, and representing it as
1407 // SUBS means that it's possible to get CSE with subtract operations.
1408 // A later phase can perform the optimization of setting the destination
1409 // register to WZR/XZR if it ends up being unused.
1410 return DAG.getNode(ARM64ISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1414 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1415 SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
1416 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1417 EVT VT = RHS.getValueType();
1418 uint64_t C = RHSC->getZExtValue();
1419 if (!isLegalArithImmed(C)) {
1420 // Constant does not fit, try adjusting it by one?
1426 if ((VT == MVT::i32 && C != 0x80000000 &&
1427 isLegalArithImmed((uint32_t)(C - 1))) ||
1428 (VT == MVT::i64 && C != 0x80000000ULL &&
1429 isLegalArithImmed(C - 1ULL))) {
1430 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1431 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1432 RHS = DAG.getConstant(C, VT);
1437 if ((VT == MVT::i32 && C != 0 &&
1438 isLegalArithImmed((uint32_t)(C - 1))) ||
1439 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1440 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1441 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1442 RHS = DAG.getConstant(C, VT);
1447 if ((VT == MVT::i32 && C != 0x7fffffff &&
1448 isLegalArithImmed((uint32_t)(C + 1))) ||
1449 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1450 isLegalArithImmed(C + 1ULL))) {
1451 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1452 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1453 RHS = DAG.getConstant(C, VT);
1458 if ((VT == MVT::i32 && C != 0xffffffff &&
1459 isLegalArithImmed((uint32_t)(C + 1))) ||
1460 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1461 isLegalArithImmed(C + 1ULL))) {
1462 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1463 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1464 RHS = DAG.getConstant(C, VT);
1471 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
1472 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
1473 ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1477 static std::pair<SDValue, SDValue>
1478 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1479 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1480 "Unsupported value type");
1481 SDValue Value, Overflow;
1483 SDValue LHS = Op.getOperand(0);
1484 SDValue RHS = Op.getOperand(1);
1486 switch (Op.getOpcode()) {
1488 llvm_unreachable("Unknown overflow instruction!");
1490 Opc = ARM64ISD::ADDS;
1494 Opc = ARM64ISD::ADDS;
1498 Opc = ARM64ISD::SUBS;
1502 Opc = ARM64ISD::SUBS;
1505 // Multiply needs a little bit extra work.
1509 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1510 if (Op.getValueType() == MVT::i32) {
1511 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1512 // For a 32 bit multiply with overflow check we want the instruction
1513 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1514 // need to generate the following pattern:
1515 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1516 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1517 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1518 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1519 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1520 DAG.getConstant(0, MVT::i64));
1521 // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1522 // operation. We need to clear out the upper 32 bits, because we used a
1523 // widening multiply that wrote all 64 bits. In the end this should be a
1525 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1527 // The signed overflow check requires more than just a simple check for
1528 // any bit set in the upper 32 bits of the result. These bits could be
1529 // just the sign bits of a negative number. To perform the overflow
1530 // check we have to arithmetic shift right the 32nd bit of the result by
1531 // 31 bits. Then we compare the result to the upper 32 bits.
1532 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1533 DAG.getConstant(32, MVT::i64));
1534 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1535 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1536 DAG.getConstant(31, MVT::i64));
1537 // It is important that LowerBits is last, otherwise the arithmetic
1538 // shift will not be folded into the compare (SUBS).
1539 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1540 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1543 // The overflow check for unsigned multiply is easy. We only need to
1544 // check if any of the upper 32 bits are set. This can be done with a
1545 // CMP (shifted register). For that we need to generate the following
1547 // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1548 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1549 DAG.getConstant(32, MVT::i64));
1550 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1552 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1553 UpperBits).getValue(1);
1557 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1558 // For the 64 bit multiply
1559 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1561 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1562 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1563 DAG.getConstant(63, MVT::i64));
1564 // It is important that LowerBits is last, otherwise the arithmetic
1565 // shift will not be folded into the compare (SUBS).
1566 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1567 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1570 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1571 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1573 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1574 UpperBits).getValue(1);
1581 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1583 // Emit the ARM64 operation with overflow check.
1584 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1585 Overflow = Value.getValue(1);
1587 return std::make_pair(Value, Overflow);
1590 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1591 RTLIB::Libcall Call) const {
1592 SmallVector<SDValue, 2> Ops;
1593 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1594 Ops.push_back(Op.getOperand(i));
1596 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1600 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1601 SDValue Sel = Op.getOperand(0);
1602 SDValue Other = Op.getOperand(1);
1604 // If neither operand is a SELECT_CC, give up.
1605 if (Sel.getOpcode() != ISD::SELECT_CC)
1606 std::swap(Sel, Other);
1607 if (Sel.getOpcode() != ISD::SELECT_CC)
1610 // The folding we want to perform is:
1611 // (xor x, (select_cc a, b, cc, 0, -1) )
1613 // (csel x, (xor x, -1), cc ...)
1615 // The latter will get matched to a CSINV instruction.
1617 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1618 SDValue LHS = Sel.getOperand(0);
1619 SDValue RHS = Sel.getOperand(1);
1620 SDValue TVal = Sel.getOperand(2);
1621 SDValue FVal = Sel.getOperand(3);
1624 // FIXME: This could be generalized to non-integer comparisons.
1625 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1628 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1629 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1631 // The the values aren't constants, this isn't the pattern we're looking for.
1632 if (!CFVal || !CTVal)
1635 // We can commute the SELECT_CC by inverting the condition. This
1636 // might be needed to make this fit into a CSINV pattern.
1637 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1638 std::swap(TVal, FVal);
1639 std::swap(CTVal, CFVal);
1640 CC = ISD::getSetCCInverse(CC, true);
1643 // If the constants line up, perform the transform!
1644 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1646 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1649 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1650 DAG.getConstant(-1ULL, Other.getValueType()));
1652 return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1659 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1660 EVT VT = Op.getValueType();
1662 // Let legalize expand this if it isn't a legal type yet.
1663 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1666 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1669 bool ExtraOp = false;
1670 switch (Op.getOpcode()) {
1672 assert(0 && "Invalid code");
1674 Opc = ARM64ISD::ADDS;
1677 Opc = ARM64ISD::SUBS;
1680 Opc = ARM64ISD::ADCS;
1684 Opc = ARM64ISD::SBCS;
1690 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1691 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1695 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1696 // Let legalize expand this if it isn't a legal type yet.
1697 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1700 ARM64CC::CondCode CC;
1701 // The actual operation that sets the overflow or carry flag.
1702 SDValue Value, Overflow;
1703 std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1705 // We use 0 and 1 as false and true values.
1706 SDValue TVal = DAG.getConstant(1, MVT::i32);
1707 SDValue FVal = DAG.getConstant(0, MVT::i32);
1709 // We use an inverted condition, because the conditional select is inverted
1710 // too. This will allow it to be selected to a single instruction:
1711 // CSINC Wd, WZR, WZR, invert(cond).
1712 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1713 Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1716 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1717 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1720 // Prefetch operands are:
1721 // 1: Address to prefetch
1723 // 3: int locality (0 = no locality ... 3 = extreme locality)
1724 // 4: bool isDataCache
1725 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1727 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1728 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1729 // The data thing is not used.
1730 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1732 bool IsStream = !Locality;
1733 // When the locality number is set
1735 // The front-end should have filtered out the out-of-range values
1736 assert(Locality <= 3 && "Prefetch locality out-of-range");
1737 // The locality degree is the opposite of the cache speed.
1738 // Put the number the other way around.
1739 // The encoding starts at 0 for level 1
1740 Locality = 3 - Locality;
1743 // built the mask value encoding the expected behavior.
1744 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1745 (Locality << 1) | // Cache level bits
1746 (unsigned)IsStream; // Stream bit
1747 return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1748 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1751 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1752 SelectionDAG &DAG) const {
1753 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1756 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1758 return LowerF128Call(Op, DAG, LC);
1761 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1762 SelectionDAG &DAG) const {
1763 if (Op.getOperand(0).getValueType() != MVT::f128) {
1764 // It's legal except when f128 is involved
1769 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1771 // FP_ROUND node has a second operand indicating whether it is known to be
1772 // precise. That doesn't take part in the LibCall so we can't directly use
1774 SDValue SrcVal = Op.getOperand(0);
1775 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1776 /*isSigned*/ false, SDLoc(Op)).first;
1779 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1780 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1781 // Any additional optimization in this function should be recorded
1782 // in the cost tables.
1783 EVT InVT = Op.getOperand(0).getValueType();
1784 EVT VT = Op.getValueType();
1786 // FP_TO_XINT conversion from the same type are legal.
1787 if (VT.getSizeInBits() == InVT.getSizeInBits())
1790 if (InVT == MVT::v2f64) {
1792 SDValue Cv = DAG.getNode(Op.getOpcode(), dl, MVT::v2i64, Op.getOperand(0));
1793 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1796 // Type changing conversions are illegal.
1800 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1801 SelectionDAG &DAG) const {
1802 if (Op.getOperand(0).getValueType().isVector())
1803 return LowerVectorFP_TO_INT(Op, DAG);
1805 if (Op.getOperand(0).getValueType() != MVT::f128) {
1806 // It's legal except when f128 is involved
1811 if (Op.getOpcode() == ISD::FP_TO_SINT)
1812 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1814 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1816 SmallVector<SDValue, 2> Ops;
1817 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1818 Ops.push_back(Op.getOperand(i));
1820 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1824 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1825 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1826 // Any additional optimization in this function should be recorded
1827 // in the cost tables.
1828 EVT VT = Op.getValueType();
1830 SDValue In = Op.getOperand(0);
1831 EVT InVT = In.getValueType();
1833 // v2i32 to v2f32 is legal.
1834 if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1837 // This function only handles v2f64 outputs.
1838 if (VT == MVT::v2f64) {
1839 // Extend the input argument to a v2i64 that we can feed into the
1840 // floating point conversion. Zero or sign extend based on whether
1841 // we're doing a signed or unsigned float conversion.
1843 Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1844 assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1845 SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1846 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1849 // Scalarize v2i64 to v2f32 conversions.
1850 std::vector<SDValue> BuildVectorOps;
1851 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1852 SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1853 DAG.getConstant(i, MVT::i64));
1854 Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1855 BuildVectorOps.push_back(Sclr);
1858 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &BuildVectorOps[0],
1859 BuildVectorOps.size());
1862 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1863 SelectionDAG &DAG) const {
1864 if (Op.getValueType().isVector())
1865 return LowerVectorINT_TO_FP(Op, DAG);
1867 // i128 conversions are libcalls.
1868 if (Op.getOperand(0).getValueType() == MVT::i128)
1871 // Other conversions are legal, unless it's to the completely software-based
1873 if (Op.getValueType() != MVT::f128)
1877 if (Op.getOpcode() == ISD::SINT_TO_FP)
1878 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1880 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1882 return LowerF128Call(Op, DAG, LC);
1885 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1886 // For iOS, we want to call an alternative entry point: __sincos_stret,
1887 // which returns the values in two S / D registers.
1889 SDValue Arg = Op.getOperand(0);
1890 EVT ArgVT = Arg.getValueType();
1891 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1898 Entry.isSExt = false;
1899 Entry.isZExt = false;
1900 Args.push_back(Entry);
1902 const char *LibcallName =
1903 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1904 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1906 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1907 TargetLowering::CallLoweringInfo CLI(
1908 DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1909 CallingConv::Fast, /*isTaillCall=*/false,
1910 /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1911 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1912 return CallResult.first;
1915 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1916 SelectionDAG &DAG) const {
1917 switch (Op.getOpcode()) {
1919 llvm_unreachable("unimplemented operand");
1921 case ISD::GlobalAddress:
1922 return LowerGlobalAddress(Op, DAG);
1923 case ISD::GlobalTLSAddress:
1924 return LowerGlobalTLSAddress(Op, DAG);
1926 return LowerSETCC(Op, DAG);
1928 return LowerBR_CC(Op, DAG);
1930 return LowerSELECT(Op, DAG);
1931 case ISD::SELECT_CC:
1932 return LowerSELECT_CC(Op, DAG);
1933 case ISD::JumpTable:
1934 return LowerJumpTable(Op, DAG);
1935 case ISD::ConstantPool:
1936 return LowerConstantPool(Op, DAG);
1937 case ISD::BlockAddress:
1938 return LowerBlockAddress(Op, DAG);
1940 return LowerVASTART(Op, DAG);
1942 return LowerVACOPY(Op, DAG);
1944 return LowerVAARG(Op, DAG);
1949 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1956 return LowerXALUO(Op, DAG);
1958 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1960 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1962 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1964 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1966 return LowerFP_ROUND(Op, DAG);
1967 case ISD::FP_EXTEND:
1968 return LowerFP_EXTEND(Op, DAG);
1969 case ISD::FRAMEADDR:
1970 return LowerFRAMEADDR(Op, DAG);
1971 case ISD::RETURNADDR:
1972 return LowerRETURNADDR(Op, DAG);
1973 case ISD::INSERT_VECTOR_ELT:
1974 return LowerINSERT_VECTOR_ELT(Op, DAG);
1975 case ISD::EXTRACT_VECTOR_ELT:
1976 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1977 case ISD::BUILD_VECTOR:
1978 return LowerBUILD_VECTOR(Op, DAG);
1979 case ISD::VECTOR_SHUFFLE:
1980 return LowerVECTOR_SHUFFLE(Op, DAG);
1981 case ISD::EXTRACT_SUBVECTOR:
1982 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1986 return LowerVectorSRA_SRL_SHL(Op, DAG);
1987 case ISD::SHL_PARTS:
1988 return LowerShiftLeftParts(Op, DAG);
1989 case ISD::SRL_PARTS:
1990 case ISD::SRA_PARTS:
1991 return LowerShiftRightParts(Op, DAG);
1993 return LowerCTPOP(Op, DAG);
1994 case ISD::FCOPYSIGN:
1995 return LowerFCOPYSIGN(Op, DAG);
1997 return LowerVectorAND(Op, DAG);
1999 return LowerVectorOR(Op, DAG);
2001 return LowerXOR(Op, DAG);
2003 return LowerPREFETCH(Op, DAG);
2004 case ISD::SINT_TO_FP:
2005 case ISD::UINT_TO_FP:
2006 return LowerINT_TO_FP(Op, DAG);
2007 case ISD::FP_TO_SINT:
2008 case ISD::FP_TO_UINT:
2009 return LowerFP_TO_INT(Op, DAG);
2011 return LowerFSINCOS(Op, DAG);
2015 /// getFunctionAlignment - Return the Log2 alignment of this function.
2016 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
2020 //===----------------------------------------------------------------------===//
2021 // Calling Convention Implementation
2022 //===----------------------------------------------------------------------===//
2024 #include "ARM64GenCallingConv.inc"
2026 /// Selects the correct CCAssignFn for a the given CallingConvention
2028 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2029 bool IsVarArg) const {
2032 llvm_unreachable("Unsupported calling convention.");
2033 case CallingConv::WebKit_JS:
2034 return CC_ARM64_WebKit_JS;
2035 case CallingConv::C:
2036 case CallingConv::Fast:
2037 if (!Subtarget->isTargetDarwin())
2038 return CC_ARM64_AAPCS;
2039 return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
2043 SDValue ARM64TargetLowering::LowerFormalArguments(
2044 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2045 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2046 SmallVectorImpl<SDValue> &InVals) const {
2047 MachineFunction &MF = DAG.getMachineFunction();
2048 MachineFrameInfo *MFI = MF.getFrameInfo();
2050 // Assign locations to all of the incoming arguments.
2051 SmallVector<CCValAssign, 16> ArgLocs;
2052 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2053 getTargetMachine(), ArgLocs, *DAG.getContext());
2055 // At this point, Ins[].VT may already be promoted to i32. To correctly
2056 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2057 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2058 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2059 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2061 unsigned NumArgs = Ins.size();
2062 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2063 unsigned CurArgIdx = 0;
2064 for (unsigned i = 0; i != NumArgs; ++i) {
2065 MVT ValVT = Ins[i].VT;
2066 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
2067 CurArgIdx = Ins[i].OrigArgIndex;
2069 // Get type of the original argument.
2070 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2071 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2072 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2074 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2076 else if (ActualMVT == MVT::i16)
2079 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2081 AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2082 assert(!Res && "Call operand has unhandled type");
2086 SmallVector<SDValue, 16> ArgValues;
2087 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2088 CCValAssign &VA = ArgLocs[i];
2090 // Arguments stored in registers.
2091 if (VA.isRegLoc()) {
2092 EVT RegVT = VA.getLocVT();
2095 const TargetRegisterClass *RC;
2097 if (RegVT == MVT::i32)
2098 RC = &ARM64::GPR32RegClass;
2099 else if (RegVT == MVT::i64)
2100 RC = &ARM64::GPR64RegClass;
2101 else if (RegVT == MVT::f32)
2102 RC = &ARM64::FPR32RegClass;
2103 else if (RegVT == MVT::f64 || RegVT == MVT::v1i64 ||
2104 RegVT == MVT::v1f64 || RegVT == MVT::v2i32 ||
2105 RegVT == MVT::v4i16 || RegVT == MVT::v8i8)
2106 RC = &ARM64::FPR64RegClass;
2107 else if (RegVT == MVT::v2i64 || RegVT == MVT::v4i32 ||
2108 RegVT == MVT::v8i16 || RegVT == MVT::v16i8)
2109 RC = &ARM64::FPR128RegClass;
2111 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2113 // Transform the arguments in physical registers into virtual ones.
2114 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2115 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2117 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2118 // to 64 bits. Insert an assert[sz]ext to capture this, then
2119 // truncate to the right size.
2120 switch (VA.getLocInfo()) {
2122 llvm_unreachable("Unknown loc info!");
2123 case CCValAssign::Full:
2125 case CCValAssign::BCvt:
2126 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2128 case CCValAssign::SExt:
2129 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2130 DAG.getValueType(VA.getValVT()));
2131 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
2133 case CCValAssign::ZExt:
2134 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2135 DAG.getValueType(VA.getValVT()));
2136 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
2140 InVals.push_back(ArgValue);
2142 } else { // VA.isRegLoc()
2143 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2144 unsigned ArgOffset = VA.getLocMemOffset();
2145 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
2146 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
2148 // Create load nodes to retrieve arguments from the stack.
2149 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2150 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
2151 MachinePointerInfo::getFixedStack(FI), false,
2158 if (!Subtarget->isTargetDarwin()) {
2159 // The AAPCS variadic function ABI is identical to the non-variadic
2160 // one. As a result there may be more arguments in registers and we should
2161 // save them for future reference.
2162 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2165 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
2166 // This will point to the next argument passed via stack.
2167 unsigned StackOffset = CCInfo.getNextStackOffset();
2168 // We currently pass all varargs at 8-byte alignment.
2169 StackOffset = ((StackOffset + 7) & ~7);
2170 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2176 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2177 SelectionDAG &DAG, SDLoc DL,
2178 SDValue &Chain) const {
2179 MachineFunction &MF = DAG.getMachineFunction();
2180 MachineFrameInfo *MFI = MF.getFrameInfo();
2181 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
2183 SmallVector<SDValue, 8> MemOps;
2185 static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
2186 ARM64::X3, ARM64::X4, ARM64::X5,
2187 ARM64::X6, ARM64::X7 };
2188 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2189 unsigned FirstVariadicGPR =
2190 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
2192 static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
2193 ARM64::Q3, ARM64::Q4, ARM64::Q5,
2194 ARM64::Q6, ARM64::Q7 };
2195 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2196 unsigned FirstVariadicFPR =
2197 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
2199 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2201 if (GPRSaveSize != 0) {
2202 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2204 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2206 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2207 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
2208 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2210 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2211 MachinePointerInfo::getStack(i * 8), false, false, 0);
2212 MemOps.push_back(Store);
2213 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2214 DAG.getConstant(8, getPointerTy()));
2218 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2220 if (FPRSaveSize != 0) {
2221 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2223 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2225 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2226 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
2227 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
2229 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2230 MachinePointerInfo::getStack(i * 16), false, false, 0);
2231 MemOps.push_back(Store);
2232 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2233 DAG.getConstant(16, getPointerTy()));
2237 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2238 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2239 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2240 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2242 if (!MemOps.empty()) {
2243 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2248 /// LowerCallResult - Lower the result values of a call into the
2249 /// appropriate copies out of appropriate physical registers.
2250 SDValue ARM64TargetLowering::LowerCallResult(
2251 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2252 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2253 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2254 SDValue ThisVal) const {
2255 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2256 : RetCC_ARM64_AAPCS;
2257 // Assign locations to each value returned by this call.
2258 SmallVector<CCValAssign, 16> RVLocs;
2259 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2260 getTargetMachine(), RVLocs, *DAG.getContext());
2261 CCInfo.AnalyzeCallResult(Ins, RetCC);
2263 // Copy all of the result registers out of their specified physreg.
2264 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2265 CCValAssign VA = RVLocs[i];
2267 // Pass 'this' value directly from the argument to return value, to avoid
2268 // reg unit interference
2269 if (i == 0 && isThisReturn) {
2270 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2271 "unexpected return calling convention register assignment");
2272 InVals.push_back(ThisVal);
2277 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2278 Chain = Val.getValue(1);
2279 InFlag = Val.getValue(2);
2281 switch (VA.getLocInfo()) {
2283 llvm_unreachable("Unknown loc info!");
2284 case CCValAssign::Full:
2286 case CCValAssign::BCvt:
2287 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2291 InVals.push_back(Val);
2297 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
2298 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2299 bool isCalleeStructRet, bool isCallerStructRet,
2300 const SmallVectorImpl<ISD::OutputArg> &Outs,
2301 const SmallVectorImpl<SDValue> &OutVals,
2302 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2303 // Look for obvious safe cases to perform tail call optimization that do not
2304 // require ABI changes. This is what gcc calls sibcall.
2306 // Do not sibcall optimize vararg calls unless the call site is not passing
2308 if (isVarArg && !Outs.empty())
2311 // Also avoid sibcall optimization if either caller or callee uses struct
2312 // return semantics.
2313 if (isCalleeStructRet || isCallerStructRet)
2316 // Note that currently ARM64 "C" calling convention and "Fast" calling
2317 // convention are compatible. If/when that ever changes, we'll need to
2318 // add checks here to make sure any interactions are OK.
2320 // If the callee takes no arguments then go on to check the results of the
2322 if (!Outs.empty()) {
2323 // Check if stack adjustment is needed. For now, do not do this if any
2324 // argument is passed on the stack.
2325 SmallVector<CCValAssign, 16> ArgLocs;
2326 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2327 getTargetMachine(), ArgLocs, *DAG.getContext());
2328 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
2329 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2330 if (CCInfo.getNextStackOffset()) {
2331 // Check if the arguments are already laid out in the right way as
2332 // the caller's fixed stack objects.
2333 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2334 ++i, ++realArgIdx) {
2335 CCValAssign &VA = ArgLocs[i];
2336 if (VA.getLocInfo() == CCValAssign::Indirect)
2338 if (VA.needsCustom()) {
2339 // Just don't handle anything that needs custom adjustments for now.
2340 // If need be, we can revisit later, but we shouldn't ever end up
2343 } else if (!VA.isRegLoc()) {
2344 // Likewise, don't try to handle stack based arguments for the
2354 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2355 /// and add input and output parameter nodes.
2356 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2357 SmallVectorImpl<SDValue> &InVals) const {
2358 SelectionDAG &DAG = CLI.DAG;
2360 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2361 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2362 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2363 SDValue Chain = CLI.Chain;
2364 SDValue Callee = CLI.Callee;
2365 bool &IsTailCall = CLI.IsTailCall;
2366 CallingConv::ID CallConv = CLI.CallConv;
2367 bool IsVarArg = CLI.IsVarArg;
2369 MachineFunction &MF = DAG.getMachineFunction();
2370 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2371 bool IsThisReturn = false;
2373 // If tail calls are explicitly disabled, make sure not to use them.
2374 if (!EnableARM64TailCalls)
2378 // Check if it's really possible to do a tail call.
2379 IsTailCall = isEligibleForTailCallOptimization(
2380 Callee, CallConv, IsVarArg, IsStructRet,
2381 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2382 // We don't support GuaranteedTailCallOpt, only automatically
2383 // detected sibcalls.
2384 // FIXME: Re-evaluate. Is this true? Should it be true?
2389 // Analyze operands of the call, assigning locations to each operand.
2390 SmallVector<CCValAssign, 16> ArgLocs;
2391 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2392 getTargetMachine(), ArgLocs, *DAG.getContext());
2395 // Handle fixed and variable vector arguments differently.
2396 // Variable vector arguments always go into memory.
2397 unsigned NumArgs = Outs.size();
2399 for (unsigned i = 0; i != NumArgs; ++i) {
2400 MVT ArgVT = Outs[i].VT;
2401 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2402 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2403 /*IsVarArg=*/ !Outs[i].IsFixed);
2404 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2405 assert(!Res && "Call operand has unhandled type");
2409 // At this point, Outs[].VT may already be promoted to i32. To correctly
2410 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2411 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2412 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2413 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2415 unsigned NumArgs = Outs.size();
2416 for (unsigned i = 0; i != NumArgs; ++i) {
2417 MVT ValVT = Outs[i].VT;
2418 // Get type of the original argument.
2419 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
2420 /*AllowUnknown*/ true);
2421 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2422 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2423 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2425 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2427 else if (ActualMVT == MVT::i16)
2430 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2431 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
2432 assert(!Res && "Call operand has unhandled type");
2437 // Get a count of how many bytes are to be pushed on the stack.
2438 unsigned NumBytes = CCInfo.getNextStackOffset();
2440 // Adjust the stack pointer for the new arguments...
2441 // These operations are automatically eliminated by the prolog/epilog pass
2444 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2446 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
2448 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2449 SmallVector<SDValue, 8> MemOpChains;
2451 // Walk the register/memloc assignments, inserting copies/loads.
2452 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2453 ++i, ++realArgIdx) {
2454 CCValAssign &VA = ArgLocs[i];
2455 SDValue Arg = OutVals[realArgIdx];
2456 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2458 // Promote the value if needed.
2459 switch (VA.getLocInfo()) {
2461 llvm_unreachable("Unknown loc info!");
2462 case CCValAssign::Full:
2464 case CCValAssign::SExt:
2465 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2467 case CCValAssign::ZExt:
2468 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2470 case CCValAssign::AExt:
2471 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2473 case CCValAssign::BCvt:
2474 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2476 case CCValAssign::FPExt:
2477 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2481 if (VA.isRegLoc()) {
2482 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2483 assert(VA.getLocVT() == MVT::i64 &&
2484 "unexpected calling convention register assignment");
2485 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2486 "unexpected use of 'returned'");
2487 IsThisReturn = true;
2489 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2491 assert(VA.isMemLoc());
2492 // There's no reason we can't support stack args w/ tailcall, but
2493 // we currently don't, so assert if we see one.
2494 assert(!IsTailCall && "stack argument with tail call!?");
2495 unsigned LocMemOffset = VA.getLocMemOffset();
2496 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2497 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2499 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2500 // promoted to a legal register type i32, we should truncate Arg back to
2502 if (Arg.getValueType().isSimple() &&
2503 Arg.getValueType().getSimpleVT() == MVT::i32 &&
2504 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2505 VA.getLocVT() == MVT::i16))
2506 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2508 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2509 MachinePointerInfo::getStack(LocMemOffset),
2511 MemOpChains.push_back(Store);
2515 if (!MemOpChains.empty())
2516 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOpChains[0],
2517 MemOpChains.size());
2519 // Build a sequence of copy-to-reg nodes chained together with token chain
2520 // and flag operands which copy the outgoing args into the appropriate regs.
2522 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2523 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2524 RegsToPass[i].second, InFlag);
2525 InFlag = Chain.getValue(1);
2528 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2529 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2530 // node so that legalize doesn't hack it.
2531 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2532 Subtarget->isTargetMachO()) {
2533 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2534 const GlobalValue *GV = G->getGlobal();
2535 bool InternalLinkage = GV->hasInternalLinkage();
2536 if (InternalLinkage)
2537 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2539 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2541 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2543 } else if (ExternalSymbolSDNode *S =
2544 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2545 const char *Sym = S->getSymbol();
2547 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2548 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2550 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2551 const GlobalValue *GV = G->getGlobal();
2552 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2553 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2554 const char *Sym = S->getSymbol();
2555 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2558 std::vector<SDValue> Ops;
2559 Ops.push_back(Chain);
2560 Ops.push_back(Callee);
2562 // Add argument registers to the end of the list so that they are known live
2564 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2565 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2566 RegsToPass[i].second.getValueType()));
2568 // Add a register mask operand representing the call-preserved registers.
2569 const uint32_t *Mask;
2570 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2571 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2573 // For 'this' returns, use the X0-preserving mask if applicable
2574 Mask = ARI->getThisReturnPreservedMask(CallConv);
2576 IsThisReturn = false;
2577 Mask = ARI->getCallPreservedMask(CallConv);
2580 Mask = ARI->getCallPreservedMask(CallConv);
2582 assert(Mask && "Missing call preserved mask for calling convention");
2583 Ops.push_back(DAG.getRegisterMask(Mask));
2585 if (InFlag.getNode())
2586 Ops.push_back(InFlag);
2588 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2590 // If we're doing a tall call, use a TC_RETURN here rather than an
2591 // actual call instruction.
2593 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, &Ops[0], Ops.size());
2595 // Returns a chain and a flag for retval copy to use.
2596 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
2597 InFlag = Chain.getValue(1);
2599 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2600 DAG.getIntPtrConstant(0, true), InFlag, DL);
2602 InFlag = Chain.getValue(1);
2604 // Handle result values, copying them out of physregs into vregs that we
2606 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2607 InVals, IsThisReturn,
2608 IsThisReturn ? OutVals[0] : SDValue());
2611 bool ARM64TargetLowering::CanLowerReturn(
2612 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2613 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2614 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2615 : RetCC_ARM64_AAPCS;
2616 SmallVector<CCValAssign, 16> RVLocs;
2617 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2618 return CCInfo.CheckReturn(Outs, RetCC);
2622 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2624 const SmallVectorImpl<ISD::OutputArg> &Outs,
2625 const SmallVectorImpl<SDValue> &OutVals,
2626 SDLoc DL, SelectionDAG &DAG) const {
2627 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2628 : RetCC_ARM64_AAPCS;
2629 SmallVector<CCValAssign, 16> RVLocs;
2630 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2631 getTargetMachine(), RVLocs, *DAG.getContext());
2632 CCInfo.AnalyzeReturn(Outs, RetCC);
2634 // Copy the result values into the output registers.
2636 SmallVector<SDValue, 4> RetOps(1, Chain);
2637 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2638 ++i, ++realRVLocIdx) {
2639 CCValAssign &VA = RVLocs[i];
2640 assert(VA.isRegLoc() && "Can only return in registers!");
2641 SDValue Arg = OutVals[realRVLocIdx];
2643 switch (VA.getLocInfo()) {
2645 llvm_unreachable("Unknown loc info!");
2646 case CCValAssign::Full:
2648 case CCValAssign::BCvt:
2649 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2653 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2654 Flag = Chain.getValue(1);
2655 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2658 RetOps[0] = Chain; // Update chain.
2660 // Add the flag if we have it.
2662 RetOps.push_back(Flag);
2664 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, &RetOps[0],
2668 //===----------------------------------------------------------------------===//
2669 // Other Lowering Code
2670 //===----------------------------------------------------------------------===//
2672 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2673 SelectionDAG &DAG) const {
2674 EVT PtrVT = getPointerTy();
2676 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2677 unsigned char OpFlags =
2678 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2680 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2681 "unexpected offset in global node");
2683 // This also catched the large code model case for Darwin.
2684 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2685 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2686 // FIXME: Once remat is capable of dealing with instructions with register
2687 // operands, expand this into two nodes instead of using a wrapper node.
2688 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2691 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2692 const unsigned char MO_NC = ARM64II::MO_NC;
2694 ARM64ISD::WrapperLarge, DL, PtrVT,
2695 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2696 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2697 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2698 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2700 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2701 // the only correct model on Darwin.
2702 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2703 OpFlags | ARM64II::MO_PAGE);
2704 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2705 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2707 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2708 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2712 /// \brief Convert a TLS address reference into the correct sequence of loads
2713 /// and calls to compute the variable's address (for Darwin, currently) and
2714 /// return an SDValue containing the final node.
2716 /// Darwin only has one TLS scheme which must be capable of dealing with the
2717 /// fully general situation, in the worst case. This means:
2718 /// + "extern __thread" declaration.
2719 /// + Defined in a possibly unknown dynamic library.
2721 /// The general system is that each __thread variable has a [3 x i64] descriptor
2722 /// which contains information used by the runtime to calculate the address. The
2723 /// only part of this the compiler needs to know about is the first xword, which
2724 /// contains a function pointer that must be called with the address of the
2725 /// entire descriptor in "x0".
2727 /// Since this descriptor may be in a different unit, in general even the
2728 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2730 /// adrp x0, _var@TLVPPAGE
2731 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2732 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2733 /// ; the function pointer
2734 /// blr x1 ; Uses descriptor address in x0
2735 /// ; Address of _var is now in x0.
2737 /// If the address of _var's descriptor *is* known to the linker, then it can
2738 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2739 /// a slight efficiency gain.
2741 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2742 SelectionDAG &DAG) const {
2743 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2746 MVT PtrVT = getPointerTy();
2747 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2750 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2751 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2753 // The first entry in the descriptor is a function pointer that we must call
2754 // to obtain the address of the variable.
2755 SDValue Chain = DAG.getEntryNode();
2756 SDValue FuncTLVGet =
2757 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2758 false, true, true, 8);
2759 Chain = FuncTLVGet.getValue(1);
2761 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2762 MFI->setAdjustsStack(true);
2764 // TLS calls preserve all registers except those that absolutely must be
2765 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2767 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2768 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2769 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2771 // Finally, we can make the call. This is just a degenerate version of a
2772 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2773 // the address of the variable in this thread.
2774 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2775 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2776 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2777 DAG.getRegisterMask(Mask), Chain.getValue(1));
2778 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2781 /// When accessing thread-local variables under either the general-dynamic or
2782 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2783 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2784 /// is a function pointer to carry out the resolution. This function takes the
2785 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2786 /// other registers (except LR, CPSR) are preserved.
2788 /// Thus, the ideal call sequence on AArch64 is:
2790 /// adrp x0, :tlsdesc:thread_var
2791 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2792 /// add x0, x0, :tlsdesc_lo12:thread_var
2793 /// .tlsdesccall thread_var
2795 /// (TPIDR_EL0 offset now in x0).
2797 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2798 /// relocation to help the linker relax this sequence if it turns out to be too
2801 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2803 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2804 SDValue DescAddr, SDLoc DL,
2805 SelectionDAG &DAG) const {
2806 EVT PtrVT = getPointerTy();
2808 // The function we need to call is simply the first entry in the GOT for this
2809 // descriptor, load it in preparation.
2810 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2812 // TLS calls preserve all registers except those that absolutely must be
2813 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2815 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2816 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2817 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2819 // The function takes only one argument: the address of the descriptor itself
2821 SDValue Glue, Chain;
2822 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2823 Glue = Chain.getValue(1);
2825 // We're now ready to populate the argument list, as with a normal call:
2826 SmallVector<SDValue, 6> Ops;
2827 Ops.push_back(Chain);
2828 Ops.push_back(Func);
2829 Ops.push_back(SymAddr);
2830 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2831 Ops.push_back(DAG.getRegisterMask(Mask));
2832 Ops.push_back(Glue);
2834 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2835 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, &Ops[0], Ops.size());
2836 Glue = Chain.getValue(1);
2838 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2841 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2842 SelectionDAG &DAG) const {
2843 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2844 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2845 "ELF TLS only supported in small memory model");
2846 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2848 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2851 EVT PtrVT = getPointerTy();
2853 const GlobalValue *GV = GA->getGlobal();
2855 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2857 if (Model == TLSModel::LocalExec) {
2858 SDValue HiVar = DAG.getTargetGlobalAddress(
2859 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2860 SDValue LoVar = DAG.getTargetGlobalAddress(
2861 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2863 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2864 DAG.getTargetConstant(16, MVT::i32)),
2866 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2867 DAG.getTargetConstant(0, MVT::i32)),
2869 } else if (Model == TLSModel::InitialExec) {
2870 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2871 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2872 } else if (Model == TLSModel::LocalDynamic) {
2873 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2874 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2875 // the beginning of the module's TLS region, followed by a DTPREL offset
2878 // These accesses will need deduplicating if there's more than one.
2879 ARM64FunctionInfo *MFI =
2880 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2881 MFI->incNumLocalDynamicTLSAccesses();
2883 // Accesses used in this sequence go via the TLS descriptor which lives in
2884 // the GOT. Prepare an address we can use to handle this.
2885 SDValue HiDesc = DAG.getTargetExternalSymbol(
2886 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2887 SDValue LoDesc = DAG.getTargetExternalSymbol(
2888 "_TLS_MODULE_BASE_", PtrVT,
2889 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2891 // First argument to the descriptor call is the address of the descriptor
2893 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2894 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2896 // The call needs a relocation too for linker relaxation. It doesn't make
2897 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2899 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2902 // Now we can calculate the offset from TPIDR_EL0 to this module's
2903 // thread-local area.
2904 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2906 // Now use :dtprel_whatever: operations to calculate this variable's offset
2907 // in its thread-storage area.
2908 SDValue HiVar = DAG.getTargetGlobalAddress(
2909 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2910 SDValue LoVar = DAG.getTargetGlobalAddress(
2911 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2914 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2915 DAG.getTargetConstant(16, MVT::i32)),
2917 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2918 DAG.getTargetConstant(0, MVT::i32)),
2921 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2922 } else if (Model == TLSModel::GeneralDynamic) {
2923 // Accesses used in this sequence go via the TLS descriptor which lives in
2924 // the GOT. Prepare an address we can use to handle this.
2925 SDValue HiDesc = DAG.getTargetGlobalAddress(
2926 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2927 SDValue LoDesc = DAG.getTargetGlobalAddress(
2929 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2931 // First argument to the descriptor call is the address of the descriptor
2933 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2934 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2936 // The call needs a relocation too for linker relaxation. It doesn't make
2937 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2940 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2942 // Finally we can make a call to calculate the offset from tpidr_el0.
2943 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2945 llvm_unreachable("Unsupported ELF TLS access model");
2947 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2950 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2951 SelectionDAG &DAG) const {
2952 if (Subtarget->isTargetDarwin())
2953 return LowerDarwinGlobalTLSAddress(Op, DAG);
2954 else if (Subtarget->isTargetELF())
2955 return LowerELFGlobalTLSAddress(Op, DAG);
2957 llvm_unreachable("Unexpected platform trying to use TLS");
2959 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2960 SDValue Chain = Op.getOperand(0);
2961 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2962 SDValue LHS = Op.getOperand(2);
2963 SDValue RHS = Op.getOperand(3);
2964 SDValue Dest = Op.getOperand(4);
2967 // Handle f128 first, since lowering it will result in comparing the return
2968 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2969 // is expecting to deal with.
2970 if (LHS.getValueType() == MVT::f128) {
2971 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2973 // If softenSetCCOperands returned a scalar, we need to compare the result
2974 // against zero to select between true and false values.
2975 if (RHS.getNode() == 0) {
2976 RHS = DAG.getConstant(0, LHS.getValueType());
2981 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2983 unsigned Opc = LHS.getOpcode();
2984 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2985 cast<ConstantSDNode>(RHS)->isOne() &&
2986 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2987 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2988 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2989 "Unexpected condition code.");
2990 // Only lower legal XALUO ops.
2991 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2994 // The actual operation with overflow check.
2995 ARM64CC::CondCode OFCC;
2996 SDValue Value, Overflow;
2997 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2999 if (CC == ISD::SETNE)
3000 OFCC = getInvertedCondCode(OFCC);
3001 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3003 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
3007 if (LHS.getValueType().isInteger()) {
3008 assert((LHS.getValueType() == RHS.getValueType()) &&
3009 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3011 // If the RHS of the comparison is zero, we can potentially fold this
3012 // to a specialized branch.
3013 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3014 if (RHSC && RHSC->getZExtValue() == 0) {
3015 if (CC == ISD::SETEQ) {
3016 // See if we can use a TBZ to fold in an AND as well.
3017 // TBZ has a smaller branch displacement than CBZ. If the offset is
3018 // out of bounds, a late MI-layer pass rewrites branches.
3019 // 403.gcc is an example that hits this case.
3020 if (LHS.getOpcode() == ISD::AND &&
3021 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3022 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3023 SDValue Test = LHS.getOperand(0);
3024 uint64_t Mask = LHS.getConstantOperandVal(1);
3026 // TBZ only operates on i64's, but the ext should be free.
3027 if (Test.getValueType() == MVT::i32)
3028 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
3030 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
3031 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3034 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3035 } else if (CC == ISD::SETNE) {
3036 // See if we can use a TBZ to fold in an AND as well.
3037 // TBZ has a smaller branch displacement than CBZ. If the offset is
3038 // out of bounds, a late MI-layer pass rewrites branches.
3039 // 403.gcc is an example that hits this case.
3040 if (LHS.getOpcode() == ISD::AND &&
3041 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3042 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3043 SDValue Test = LHS.getOperand(0);
3044 uint64_t Mask = LHS.getConstantOperandVal(1);
3046 // TBNZ only operates on i64's, but the ext should be free.
3047 if (Test.getValueType() == MVT::i32)
3048 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
3050 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3051 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3054 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3059 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3060 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3064 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3066 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3067 // clean. Some of them require two branches to implement.
3068 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3069 ARM64CC::CondCode CC1, CC2;
3070 changeFPCCToARM64CC(CC, CC1, CC2);
3071 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3073 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3074 if (CC2 != ARM64CC::AL) {
3075 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3076 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3083 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3084 SelectionDAG &DAG) const {
3085 EVT VT = Op.getValueType();
3088 SDValue In1 = Op.getOperand(0);
3089 SDValue In2 = Op.getOperand(1);
3090 EVT SrcVT = In2.getValueType();
3092 if (SrcVT == MVT::f32 && VT == MVT::f64)
3093 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3094 else if (SrcVT == MVT::f64 && VT == MVT::f32)
3095 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3097 // FIXME: Src type is different, bail out for now. Can VT really be a
3104 SDValue EltMask, VecVal1, VecVal2;
3105 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3108 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
3110 if (!VT.isVector()) {
3111 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
3112 DAG.getUNDEF(VecVT), In1);
3113 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
3114 DAG.getUNDEF(VecVT), In2);
3116 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3117 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3119 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3123 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3124 // immediate moves cannot materialize that in a single instruction for
3125 // 64-bit elements. Instead, materialize zero and then negate it.
3126 EltMask = DAG.getConstant(0, EltVT);
3128 if (!VT.isVector()) {
3129 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
3130 DAG.getUNDEF(VecVT), In1);
3131 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
3132 DAG.getUNDEF(VecVT), In2);
3134 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3135 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3138 llvm_unreachable("Invalid type for copysign!");
3141 std::vector<SDValue> BuildVectorOps;
3142 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
3143 BuildVectorOps.push_back(EltMask);
3145 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT,
3146 &BuildVectorOps[0], BuildVectorOps.size());
3148 // If we couldn't materialize the mask above, then the mask vector will be
3149 // the zero vector, and we need to negate it here.
3150 if (VT == MVT::f64 || VT == MVT::v2f64) {
3151 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3152 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3153 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3157 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3160 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
3161 else if (VT == MVT::f64)
3162 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
3164 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3167 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3168 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
3169 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
3172 // While there is no integer popcount instruction, it can
3173 // be more efficiently lowered to the following sequence that uses
3174 // AdvSIMD registers/instructions as long as the copies to/from
3175 // the AdvSIMD registers are cheap.
3176 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3177 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3178 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3179 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3180 SDValue Val = Op.getOperand(0);
3182 EVT VT = Op.getValueType();
3183 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
3186 if (VT == MVT::i32) {
3187 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
3189 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
3191 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3194 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
3195 SDValue UaddLV = DAG.getNode(
3196 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3197 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
3200 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3204 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3206 if (Op.getValueType().isVector())
3207 return LowerVSETCC(Op, DAG);
3209 SDValue LHS = Op.getOperand(0);
3210 SDValue RHS = Op.getOperand(1);
3211 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3214 // We chose ZeroOrOneBooleanContents, so use zero and one.
3215 EVT VT = Op.getValueType();
3216 SDValue TVal = DAG.getConstant(1, VT);
3217 SDValue FVal = DAG.getConstant(0, VT);
3219 // Handle f128 first, since one possible outcome is a normal integer
3220 // comparison which gets picked up by the next if statement.
3221 if (LHS.getValueType() == MVT::f128) {
3222 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3224 // If softenSetCCOperands returned a scalar, use it.
3225 if (RHS.getNode() == 0) {
3226 assert(LHS.getValueType() == Op.getValueType() &&
3227 "Unexpected setcc expansion!");
3232 if (LHS.getValueType().isInteger()) {
3235 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3237 // Note that we inverted the condition above, so we reverse the order of
3238 // the true and false operands here. This will allow the setcc to be
3239 // matched to a single CSINC instruction.
3240 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3243 // Now we know we're dealing with FP values.
3244 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3246 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3247 // and do the comparison.
3248 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3250 ARM64CC::CondCode CC1, CC2;
3251 changeFPCCToARM64CC(CC, CC1, CC2);
3252 if (CC2 == ARM64CC::AL) {
3253 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3254 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3256 // Note that we inverted the condition above, so we reverse the order of
3257 // the true and false operands here. This will allow the setcc to be
3258 // matched to a single CSINC instruction.
3259 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3261 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3262 // clean. Some of them require two CSELs to implement. As is in this case,
3263 // we emit the first CSEL and then emit a second using the output of the
3264 // first as the RHS. We're effectively OR'ing the two CC's together.
3266 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3267 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3268 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3270 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3271 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3275 /// A SELECT_CC operation is really some kind of max or min if both values being
3276 /// compared are, in some sense, equal to the results in either case. However,
3277 /// it is permissible to compare f32 values and produce directly extended f64
3280 /// Extending the comparison operands would also be allowed, but is less likely
3281 /// to happen in practice since their use is right here. Note that truncate
3282 /// operations would *not* be semantically equivalent.
3283 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3287 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3288 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3289 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3290 Result.getValueType() == MVT::f64) {
3292 APFloat CmpVal = CCmp->getValueAPF();
3293 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3294 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3297 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3300 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3301 SDValue CC = Op->getOperand(0);
3302 SDValue TVal = Op->getOperand(1);
3303 SDValue FVal = Op->getOperand(2);
3306 unsigned Opc = CC.getOpcode();
3307 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3309 if (CC.getResNo() == 1 &&
3310 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3311 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3312 // Only lower legal XALUO ops.
3313 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3316 ARM64CC::CondCode OFCC;
3317 SDValue Value, Overflow;
3318 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
3319 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3321 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
3325 if (CC.getOpcode() == ISD::SETCC)
3326 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3327 cast<CondCodeSDNode>(CC.getOperand(2))->get());
3329 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3333 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
3334 SelectionDAG &DAG) const {
3335 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3336 SDValue LHS = Op.getOperand(0);
3337 SDValue RHS = Op.getOperand(1);
3338 SDValue TVal = Op.getOperand(2);
3339 SDValue FVal = Op.getOperand(3);
3342 // Handle f128 first, because it will result in a comparison of some RTLIB
3343 // call result against zero.
3344 if (LHS.getValueType() == MVT::f128) {
3345 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3347 // If softenSetCCOperands returned a scalar, we need to compare the result
3348 // against zero to select between true and false values.
3349 if (RHS.getNode() == 0) {
3350 RHS = DAG.getConstant(0, LHS.getValueType());
3355 // Handle integers first.
3356 if (LHS.getValueType().isInteger()) {
3357 assert((LHS.getValueType() == RHS.getValueType()) &&
3358 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3360 unsigned Opcode = ARM64ISD::CSEL;
3362 // If both the TVal and the FVal are constants, see if we can swap them in
3363 // order to for a CSINV or CSINC out of them.
3364 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3365 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3367 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3368 std::swap(TVal, FVal);
3369 std::swap(CTVal, CFVal);
3370 CC = ISD::getSetCCInverse(CC, true);
3371 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3372 std::swap(TVal, FVal);
3373 std::swap(CTVal, CFVal);
3374 CC = ISD::getSetCCInverse(CC, true);
3375 } else if (TVal.getOpcode() == ISD::XOR) {
3376 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3377 // with a CSINV rather than a CSEL.
3378 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3380 if (CVal && CVal->isAllOnesValue()) {
3381 std::swap(TVal, FVal);
3382 std::swap(CTVal, CFVal);
3383 CC = ISD::getSetCCInverse(CC, true);
3385 } else if (TVal.getOpcode() == ISD::SUB) {
3386 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3387 // that we can match with a CSNEG rather than a CSEL.
3388 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3390 if (CVal && CVal->isNullValue()) {
3391 std::swap(TVal, FVal);
3392 std::swap(CTVal, CFVal);
3393 CC = ISD::getSetCCInverse(CC, true);
3395 } else if (CTVal && CFVal) {
3396 const int64_t TrueVal = CTVal->getSExtValue();
3397 const int64_t FalseVal = CFVal->getSExtValue();
3400 // If both TVal and FVal are constants, see if FVal is the
3401 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3402 // instead of a CSEL in that case.
3403 if (TrueVal == ~FalseVal) {
3404 Opcode = ARM64ISD::CSINV;
3405 } else if (TrueVal == -FalseVal) {
3406 Opcode = ARM64ISD::CSNEG;
3407 } else if (TVal.getValueType() == MVT::i32) {
3408 // If our operands are only 32-bit wide, make sure we use 32-bit
3409 // arithmetic for the check whether we can use CSINC. This ensures that
3410 // the addition in the check will wrap around properly in case there is
3411 // an overflow (which would not be the case if we do the check with
3412 // 64-bit arithmetic).
3413 const uint32_t TrueVal32 = CTVal->getZExtValue();
3414 const uint32_t FalseVal32 = CFVal->getZExtValue();
3416 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3417 Opcode = ARM64ISD::CSINC;
3419 if (TrueVal32 > FalseVal32) {
3423 // 64-bit check whether we can use CSINC.
3424 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3425 Opcode = ARM64ISD::CSINC;
3427 if (TrueVal > FalseVal) {
3432 // Swap TVal and FVal if necessary.
3434 std::swap(TVal, FVal);
3435 std::swap(CTVal, CFVal);
3436 CC = ISD::getSetCCInverse(CC, true);
3439 if (Opcode != ARM64ISD::CSEL) {
3440 // Drop FVal since we can get its value by simply inverting/negating
3447 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3449 EVT VT = Op.getValueType();
3450 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3453 // Now we know we're dealing with FP values.
3454 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3455 assert(LHS.getValueType() == RHS.getValueType());
3456 EVT VT = Op.getValueType();
3458 // Try to match this select into a max/min operation, which have dedicated
3459 // opcode in the instruction set.
3460 // NOTE: This is not correct in the presence of NaNs, so we only enable this
3462 if (getTargetMachine().Options.NoNaNsFPMath) {
3463 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3464 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3465 CC = ISD::getSetCCSwappedOperands(CC);
3466 std::swap(TVal, FVal);
3469 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3470 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3480 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3488 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3494 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3495 // and do the comparison.
3496 SDValue Cmp = emitComparison(LHS, RHS, dl, DAG);
3498 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3499 // clean. Some of them require two CSELs to implement.
3500 ARM64CC::CondCode CC1, CC2;
3501 changeFPCCToARM64CC(CC, CC1, CC2);
3502 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3503 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3505 // If we need a second CSEL, emit it, using the output of the first as the
3506 // RHS. We're effectively OR'ing the two CC's together.
3507 if (CC2 != ARM64CC::AL) {
3508 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3509 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3512 // Otherwise, return the output of the first CSEL.
3516 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3517 SelectionDAG &DAG) const {
3518 // Jump table entries as PC relative offsets. No additional tweaking
3519 // is necessary here. Just get the address of the jump table.
3520 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3521 EVT PtrVT = getPointerTy();
3524 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3525 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3526 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3527 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3528 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3531 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3532 SelectionDAG &DAG) const {
3533 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3534 EVT PtrVT = getPointerTy();
3537 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3538 // Use the GOT for the large code model on iOS.
3539 if (Subtarget->isTargetMachO()) {
3540 SDValue GotAddr = DAG.getTargetConstantPool(
3541 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3543 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3546 const unsigned char MO_NC = ARM64II::MO_NC;
3548 ARM64ISD::WrapperLarge, DL, PtrVT,
3549 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3550 CP->getOffset(), ARM64II::MO_G3),
3551 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3552 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3553 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3554 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3555 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3556 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3558 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3559 // ELF, the only valid one on Darwin.
3561 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3562 CP->getOffset(), ARM64II::MO_PAGE);
3563 SDValue Lo = DAG.getTargetConstantPool(
3564 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3565 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3567 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3568 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3572 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3573 SelectionDAG &DAG) const {
3574 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3575 EVT PtrVT = getPointerTy();
3577 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3578 !Subtarget->isTargetMachO()) {
3579 const unsigned char MO_NC = ARM64II::MO_NC;
3581 ARM64ISD::WrapperLarge, DL, PtrVT,
3582 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3583 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3584 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3585 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3587 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3588 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3590 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3591 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3595 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3596 SelectionDAG &DAG) const {
3597 ARM64FunctionInfo *FuncInfo =
3598 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3602 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3603 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3604 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3605 MachinePointerInfo(SV), false, false, 0);
3608 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3609 SelectionDAG &DAG) const {
3610 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3611 // Standard, section B.3.
3612 MachineFunction &MF = DAG.getMachineFunction();
3613 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3616 SDValue Chain = Op.getOperand(0);
3617 SDValue VAList = Op.getOperand(1);
3618 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3619 SmallVector<SDValue, 4> MemOps;
3621 // void *__stack at offset 0
3623 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3624 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3625 MachinePointerInfo(SV), false, false, 8));
3627 // void *__gr_top at offset 8
3628 int GPRSize = FuncInfo->getVarArgsGPRSize();
3630 SDValue GRTop, GRTopAddr;
3632 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3633 DAG.getConstant(8, getPointerTy()));
3635 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3636 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3637 DAG.getConstant(GPRSize, getPointerTy()));
3639 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3640 MachinePointerInfo(SV, 8), false, false, 8));
3643 // void *__vr_top at offset 16
3644 int FPRSize = FuncInfo->getVarArgsFPRSize();
3646 SDValue VRTop, VRTopAddr;
3647 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3648 DAG.getConstant(16, getPointerTy()));
3650 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3651 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3652 DAG.getConstant(FPRSize, getPointerTy()));
3654 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3655 MachinePointerInfo(SV, 16), false, false, 8));
3658 // int __gr_offs at offset 24
3659 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3660 DAG.getConstant(24, getPointerTy()));
3661 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3662 GROffsAddr, MachinePointerInfo(SV, 24), false,
3665 // int __vr_offs at offset 28
3666 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3667 DAG.getConstant(28, getPointerTy()));
3668 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3669 VROffsAddr, MachinePointerInfo(SV, 28), false,
3672 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
3676 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3677 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3678 : LowerAAPCS_VASTART(Op, DAG);
3681 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3682 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3684 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3685 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3686 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3688 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3689 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3690 8, false, false, MachinePointerInfo(DestSV),
3691 MachinePointerInfo(SrcSV));
3694 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3695 assert(Subtarget->isTargetDarwin() &&
3696 "automatic va_arg instruction only works on Darwin");
3698 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3699 EVT VT = Op.getValueType();
3701 SDValue Chain = Op.getOperand(0);
3702 SDValue Addr = Op.getOperand(1);
3703 unsigned Align = Op.getConstantOperandVal(3);
3705 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3706 MachinePointerInfo(V), false, false, false, 0);
3707 Chain = VAList.getValue(1);
3710 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3711 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3712 DAG.getConstant(Align - 1, getPointerTy()));
3713 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3714 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3717 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3718 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3720 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3721 // up to 64 bits. At the very least, we have to increase the striding of the
3722 // vaargs list to match this, and for FP values we need to introduce
3723 // FP_ROUND nodes as well.
3724 if (VT.isInteger() && !VT.isVector())
3726 bool NeedFPTrunc = false;
3727 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3732 // Increment the pointer, VAList, to the next vaarg
3733 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3734 DAG.getConstant(ArgSize, getPointerTy()));
3735 // Store the incremented VAList to the legalized pointer
3736 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3739 // Load the actual argument out of the pointer VAList
3741 // Load the value as an f64.
3742 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3743 MachinePointerInfo(), false, false, false, 0);
3744 // Round the value down to an f32.
3745 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3746 DAG.getIntPtrConstant(1));
3747 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3748 // Merge the rounded value with the chain output of the load.
3749 return DAG.getMergeValues(Ops, 2, DL);
3752 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3756 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3757 SelectionDAG &DAG) const {
3758 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3759 MFI->setFrameAddressIsTaken(true);
3761 EVT VT = Op.getValueType();
3763 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3764 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3766 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3767 MachinePointerInfo(), false, false, false, 0);
3771 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3772 SelectionDAG &DAG) const {
3773 MachineFunction &MF = DAG.getMachineFunction();
3774 MachineFrameInfo *MFI = MF.getFrameInfo();
3775 MFI->setReturnAddressIsTaken(true);
3777 EVT VT = Op.getValueType();
3779 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3781 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3782 SDValue Offset = DAG.getConstant(8, getPointerTy());
3783 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3784 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3785 MachinePointerInfo(), false, false, false, 0);
3788 // Return LR, which contains the return address. Mark it an implicit live-in.
3789 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3790 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3793 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3794 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3795 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3796 SelectionDAG &DAG) const {
3797 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3798 EVT VT = Op.getValueType();
3799 unsigned VTBits = VT.getSizeInBits();
3801 SDValue ShOpLo = Op.getOperand(0);
3802 SDValue ShOpHi = Op.getOperand(1);
3803 SDValue ShAmt = Op.getOperand(2);
3805 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3807 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3809 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3810 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3811 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3812 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3813 DAG.getConstant(VTBits, MVT::i64));
3814 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3817 emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64), dl, DAG);
3818 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3820 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3821 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3823 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3825 // ARM64 shifts larger than the register width are wrapped rather than
3826 // clamped, so we can't just emit "hi >> x".
3827 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3828 SDValue TrueValHi = Opc == ISD::SRA
3829 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3830 DAG.getConstant(VTBits - 1, MVT::i64))
3831 : DAG.getConstant(0, VT);
3833 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3835 SDValue Ops[2] = { Lo, Hi };
3836 return DAG.getMergeValues(Ops, 2, dl);
3839 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3840 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3841 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3842 SelectionDAG &DAG) const {
3843 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3844 EVT VT = Op.getValueType();
3845 unsigned VTBits = VT.getSizeInBits();
3847 SDValue ShOpLo = Op.getOperand(0);
3848 SDValue ShOpHi = Op.getOperand(1);
3849 SDValue ShAmt = Op.getOperand(2);
3852 assert(Op.getOpcode() == ISD::SHL_PARTS);
3853 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3854 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3855 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3856 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3857 DAG.getConstant(VTBits, MVT::i64));
3858 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3859 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3861 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3864 emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64), dl, DAG);
3865 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3866 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3868 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3869 // so we can't just emit "lo << a" if a is too big.
3870 SDValue TrueValLo = DAG.getConstant(0, VT);
3871 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3873 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3875 SDValue Ops[2] = { Lo, Hi };
3876 return DAG.getMergeValues(Ops, 2, dl);
3880 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3881 // The ARM64 target doesn't support folding offsets into global addresses.
3885 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3886 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3887 // FIXME: We should be able to handle f128 as well with a clever lowering.
3888 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3892 return ARM64_AM::getFP64Imm(Imm) != -1;
3893 else if (VT == MVT::f32)
3894 return ARM64_AM::getFP32Imm(Imm) != -1;
3898 //===----------------------------------------------------------------------===//
3899 // ARM64 Optimization Hooks
3900 //===----------------------------------------------------------------------===//
3902 //===----------------------------------------------------------------------===//
3903 // ARM64 Inline Assembly Support
3904 //===----------------------------------------------------------------------===//
3906 // Table of Constraints
3907 // TODO: This is the current set of constraints supported by ARM for the
3908 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3910 // r - A general register
3911 // w - An FP/SIMD register of some size in the range v0-v31
3912 // x - An FP/SIMD register of some size in the range v0-v15
3913 // I - Constant that can be used with an ADD instruction
3914 // J - Constant that can be used with a SUB instruction
3915 // K - Constant that can be used with a 32-bit logical instruction
3916 // L - Constant that can be used with a 64-bit logical instruction
3917 // M - Constant that can be used as a 32-bit MOV immediate
3918 // N - Constant that can be used as a 64-bit MOV immediate
3919 // Q - A memory reference with base register and no offset
3920 // S - A symbolic address
3921 // Y - Floating point constant zero
3922 // Z - Integer constant zero
3924 // Note that general register operands will be output using their 64-bit x
3925 // register name, whatever the size of the variable, unless the asm operand
3926 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3927 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3930 /// getConstraintType - Given a constraint letter, return the type of
3931 /// constraint it is for this target.
3932 ARM64TargetLowering::ConstraintType
3933 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3934 if (Constraint.size() == 1) {
3935 switch (Constraint[0]) {
3942 return C_RegisterClass;
3943 // An address with a single base register. Due to the way we
3944 // currently handle addresses it is the same as 'r'.
3949 return TargetLowering::getConstraintType(Constraint);
3952 /// Examine constraint type and operand type and determine a weight value.
3953 /// This object must already have been set up with the operand type
3954 /// and the current alternative constraint selected.
3955 TargetLowering::ConstraintWeight
3956 ARM64TargetLowering::getSingleConstraintMatchWeight(
3957 AsmOperandInfo &info, const char *constraint) const {
3958 ConstraintWeight weight = CW_Invalid;
3959 Value *CallOperandVal = info.CallOperandVal;
3960 // If we don't have a value, we can't do a match,
3961 // but allow it at the lowest weight.
3962 if (CallOperandVal == NULL)
3964 Type *type = CallOperandVal->getType();
3965 // Look at the constraint type.
3966 switch (*constraint) {
3968 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3972 if (type->isFloatingPointTy() || type->isVectorTy())
3973 weight = CW_Register;
3976 weight = CW_Constant;
3982 std::pair<unsigned, const TargetRegisterClass *>
3983 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3985 if (Constraint.size() == 1) {
3986 switch (Constraint[0]) {
3988 if (VT.getSizeInBits() == 64)
3989 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3990 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3993 return std::make_pair(0U, &ARM64::FPR32RegClass);
3994 if (VT.getSizeInBits() == 64)
3995 return std::make_pair(0U, &ARM64::FPR64RegClass);
3996 if (VT.getSizeInBits() == 128)
3997 return std::make_pair(0U, &ARM64::FPR128RegClass);
3999 // The instructions that this constraint is designed for can
4000 // only take 128-bit registers so just use that regclass.
4002 if (VT.getSizeInBits() == 128)
4003 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
4007 if (StringRef("{cc}").equals_lower(Constraint))
4008 return std::make_pair(unsigned(ARM64::CPSR), &ARM64::CCRRegClass);
4010 // Use the default implementation in TargetLowering to convert the register
4011 // constraint into a member of a register class.
4012 std::pair<unsigned, const TargetRegisterClass *> Res;
4013 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4015 // Not found as a standard register?
4016 if (Res.second == 0) {
4017 unsigned Size = Constraint.size();
4018 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4019 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4020 const std::string Reg =
4021 std::string(&Constraint[2], &Constraint[Size - 1]);
4022 int RegNo = atoi(Reg.c_str());
4023 if (RegNo >= 0 && RegNo <= 31) {
4024 // v0 - v31 are aliases of q0 - q31.
4025 // By default we'll emit v0-v31 for this unless there's a modifier where
4026 // we'll emit the correct register as well.
4027 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
4028 Res.second = &ARM64::FPR128RegClass;
4036 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4037 /// vector. If it is invalid, don't add anything to Ops.
4038 void ARM64TargetLowering::LowerAsmOperandForConstraint(
4039 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4040 SelectionDAG &DAG) const {
4041 SDValue Result(0, 0);
4043 // Currently only support length 1 constraints.
4044 if (Constraint.length() != 1)
4047 char ConstraintLetter = Constraint[0];
4048 switch (ConstraintLetter) {
4052 // This set of constraints deal with valid constants for various instructions.
4053 // Validate and return a target constant for them if we can.
4055 // 'z' maps to xzr or wzr so it needs an input of 0.
4056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4057 if (!C || C->getZExtValue() != 0)
4060 if (Op.getValueType() == MVT::i64)
4061 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
4063 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
4073 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4077 // Grab the value and do some validation.
4078 uint64_t CVal = C->getZExtValue();
4079 switch (ConstraintLetter) {
4080 // The I constraint applies only to simple ADD or SUB immediate operands:
4081 // i.e. 0 to 4095 with optional shift by 12
4082 // The J constraint applies only to ADD or SUB immediates that would be
4083 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4084 // instruction [or vice versa], in other words -1 to -4095 with optional
4085 // left shift by 12.
4087 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4091 uint64_t NVal = -C->getSExtValue();
4092 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
4096 // The K and L constraints apply *only* to logical immediates, including
4097 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4098 // been removed and MOV should be used). So these constraints have to
4099 // distinguish between bit patterns that are valid 32-bit or 64-bit
4100 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4101 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4104 if (ARM64_AM::isLogicalImmediate(CVal, 32))
4108 if (ARM64_AM::isLogicalImmediate(CVal, 64))
4111 // The M and N constraints are a superset of K and L respectively, for use
4112 // with the MOV (immediate) alias. As well as the logical immediates they
4113 // also match 32 or 64-bit immediates that can be loaded either using a
4114 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4115 // (M) or 64-bit 0x1234000000000000 (N) etc.
4116 // As a note some of this code is liberally stolen from the asm parser.
4118 if (!isUInt<32>(CVal))
4120 if (ARM64_AM::isLogicalImmediate(CVal, 32))
4122 if ((CVal & 0xFFFF) == CVal)
4124 if ((CVal & 0xFFFF0000ULL) == CVal)
4126 uint64_t NCVal = ~(uint32_t)CVal;
4127 if ((NCVal & 0xFFFFULL) == NCVal)
4129 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4134 if (ARM64_AM::isLogicalImmediate(CVal, 64))
4136 if ((CVal & 0xFFFFULL) == CVal)
4138 if ((CVal & 0xFFFF0000ULL) == CVal)
4140 if ((CVal & 0xFFFF00000000ULL) == CVal)
4142 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4144 uint64_t NCVal = ~CVal;
4145 if ((NCVal & 0xFFFFULL) == NCVal)
4147 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4149 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4151 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4159 // All assembler immediates are 64-bit integers.
4160 Result = DAG.getTargetConstant(CVal, MVT::i64);
4164 if (Result.getNode()) {
4165 Ops.push_back(Result);
4169 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4172 //===----------------------------------------------------------------------===//
4173 // ARM64 Advanced SIMD Support
4174 //===----------------------------------------------------------------------===//
4176 /// WidenVector - Given a value in the V64 register class, produce the
4177 /// equivalent value in the V128 register class.
4178 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4179 EVT VT = V64Reg.getValueType();
4180 unsigned NarrowSize = VT.getVectorNumElements();
4181 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4182 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4185 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4186 V64Reg, DAG.getConstant(0, MVT::i32));
4189 /// getExtFactor - Determine the adjustment factor for the position when
4190 /// generating an "extract from vector registers" instruction.
4191 static unsigned getExtFactor(SDValue &V) {
4192 EVT EltType = V.getValueType().getVectorElementType();
4193 return EltType.getSizeInBits() / 8;
4196 /// NarrowVector - Given a value in the V128 register class, produce the
4197 /// equivalent value in the V64 register class.
4198 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4199 EVT VT = V128Reg.getValueType();
4200 unsigned WideSize = VT.getVectorNumElements();
4201 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4202 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4205 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
4208 // Gather data to see if the operation can be modelled as a
4209 // shuffle in combination with VEXTs.
4210 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
4211 SelectionDAG &DAG) const {
4213 EVT VT = Op.getValueType();
4214 unsigned NumElts = VT.getVectorNumElements();
4216 SmallVector<SDValue, 2> SourceVecs;
4217 SmallVector<unsigned, 2> MinElts;
4218 SmallVector<unsigned, 2> MaxElts;
4220 for (unsigned i = 0; i < NumElts; ++i) {
4221 SDValue V = Op.getOperand(i);
4222 if (V.getOpcode() == ISD::UNDEF)
4224 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4225 // A shuffle can only come from building a vector from various
4226 // elements of other vectors.
4230 // Record this extraction against the appropriate vector if possible...
4231 SDValue SourceVec = V.getOperand(0);
4232 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4233 bool FoundSource = false;
4234 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4235 if (SourceVecs[j] == SourceVec) {
4236 if (MinElts[j] > EltNo)
4238 if (MaxElts[j] < EltNo)
4245 // Or record a new source if not...
4247 SourceVecs.push_back(SourceVec);
4248 MinElts.push_back(EltNo);
4249 MaxElts.push_back(EltNo);
4253 // Currently only do something sane when at most two source vectors
4255 if (SourceVecs.size() > 2)
4258 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4259 int VEXTOffsets[2] = { 0, 0 };
4261 // This loop extracts the usage patterns of the source vectors
4262 // and prepares appropriate SDValues for a shuffle if possible.
4263 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4264 if (SourceVecs[i].getValueType() == VT) {
4265 // No VEXT necessary
4266 ShuffleSrcs[i] = SourceVecs[i];
4269 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4270 // It probably isn't worth padding out a smaller vector just to
4271 // break it down again in a shuffle.
4275 // Don't attempt to extract subvectors from BUILD_VECTOR sources
4276 // that expand or trunc the original value.
4277 // TODO: We can try to bitcast and ANY_EXTEND the result but
4278 // we need to consider the cost of vector ANY_EXTEND, and the
4279 // legality of all the types.
4280 if (SourceVecs[i].getValueType().getVectorElementType() !=
4281 VT.getVectorElementType())
4284 // Since only 64-bit and 128-bit vectors are legal on ARM and
4285 // we've eliminated the other cases...
4286 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
4287 "unexpected vector sizes in ReconstructShuffle");
4289 if (MaxElts[i] - MinElts[i] >= NumElts) {
4290 // Span too large for a VEXT to cope
4294 if (MinElts[i] >= NumElts) {
4295 // The extraction can just take the second half
4296 VEXTOffsets[i] = NumElts;
4298 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
4299 DAG.getIntPtrConstant(NumElts));
4300 } else if (MaxElts[i] < NumElts) {
4301 // The extraction can just take the first half
4303 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4304 SourceVecs[i], DAG.getIntPtrConstant(0));
4306 // An actual VEXT is needed
4307 VEXTOffsets[i] = MinElts[i];
4308 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4309 SourceVecs[i], DAG.getIntPtrConstant(0));
4311 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
4312 DAG.getIntPtrConstant(NumElts));
4313 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
4314 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
4315 DAG.getConstant(Imm, MVT::i32));
4319 SmallVector<int, 8> Mask;
4321 for (unsigned i = 0; i < NumElts; ++i) {
4322 SDValue Entry = Op.getOperand(i);
4323 if (Entry.getOpcode() == ISD::UNDEF) {
4328 SDValue ExtractVec = Entry.getOperand(0);
4330 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
4331 if (ExtractVec == SourceVecs[0]) {
4332 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4334 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4338 // Final check before we try to produce nonsense...
4339 if (isShuffleMaskLegal(Mask, VT))
4340 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4346 // check if an EXT instruction can handle the shuffle mask when the
4347 // vector sources of the shuffle are the same.
4348 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4349 unsigned NumElts = VT.getVectorNumElements();
4351 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4357 // If this is a VEXT shuffle, the immediate value is the index of the first
4358 // element. The other shuffle indices must be the successive elements after
4360 unsigned ExpectedElt = Imm;
4361 for (unsigned i = 1; i < NumElts; ++i) {
4362 // Increment the expected index. If it wraps around, just follow it
4363 // back to index zero and keep going.
4365 if (ExpectedElt == NumElts)
4369 continue; // ignore UNDEF indices
4370 if (ExpectedElt != static_cast<unsigned>(M[i]))
4377 // check if an EXT instruction can handle the shuffle mask when the
4378 // vector sources of the shuffle are different.
4379 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4381 unsigned NumElts = VT.getVectorNumElements();
4384 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4390 // If this is a VEXT shuffle, the immediate value is the index of the first
4391 // element. The other shuffle indices must be the successive elements after
4393 unsigned ExpectedElt = Imm;
4394 for (unsigned i = 1; i < NumElts; ++i) {
4395 // Increment the expected index. If it wraps around, it may still be
4396 // a VEXT but the source vectors must be swapped.
4398 if (ExpectedElt == NumElts * 2) {
4404 continue; // ignore UNDEF indices
4405 if (ExpectedElt != static_cast<unsigned>(M[i]))
4409 // Adjust the index value if the source operands will be swapped.
4416 /// isREVMask - Check if a vector shuffle corresponds to a REV
4417 /// instruction with the specified blocksize. (The order of the elements
4418 /// within each block of the vector is reversed.)
4419 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4420 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4421 "Only possible block sizes for REV are: 16, 32, 64");
4423 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4427 unsigned NumElts = VT.getVectorNumElements();
4428 unsigned BlockElts = M[0] + 1;
4429 // If the first shuffle index is UNDEF, be optimistic.
4431 BlockElts = BlockSize / EltSz;
4433 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4436 for (unsigned i = 0; i < NumElts; ++i) {
4438 continue; // ignore UNDEF indices
4439 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4446 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4447 unsigned NumElts = VT.getVectorNumElements();
4448 WhichResult = (M[0] == 0 ? 0 : 1);
4449 unsigned Idx = WhichResult * NumElts / 2;
4450 for (unsigned i = 0; i != NumElts; i += 2) {
4451 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4452 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4460 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4461 unsigned NumElts = VT.getVectorNumElements();
4462 WhichResult = (M[0] == 0 ? 0 : 1);
4463 for (unsigned i = 0; i != NumElts; ++i) {
4465 continue; // ignore UNDEF indices
4466 if ((unsigned)M[i] != 2 * i + WhichResult)
4473 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4474 unsigned NumElts = VT.getVectorNumElements();
4475 WhichResult = (M[0] == 0 ? 0 : 1);
4476 for (unsigned i = 0; i < NumElts; i += 2) {
4477 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4478 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4484 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4485 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4486 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4487 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4488 unsigned NumElts = VT.getVectorNumElements();
4489 WhichResult = (M[0] == 0 ? 0 : 1);
4490 unsigned Idx = WhichResult * NumElts / 2;
4491 for (unsigned i = 0; i != NumElts; i += 2) {
4492 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4493 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4501 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4502 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4503 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4504 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4505 unsigned Half = VT.getVectorNumElements() / 2;
4506 WhichResult = (M[0] == 0 ? 0 : 1);
4507 for (unsigned j = 0; j != 2; ++j) {
4508 unsigned Idx = WhichResult;
4509 for (unsigned i = 0; i != Half; ++i) {
4510 int MIdx = M[i + j * Half];
4511 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4520 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4521 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4522 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4523 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4524 unsigned NumElts = VT.getVectorNumElements();
4525 WhichResult = (M[0] == 0 ? 0 : 1);
4526 for (unsigned i = 0; i < NumElts; i += 2) {
4527 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4528 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4534 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4535 /// the specified operations to build the shuffle.
4536 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4537 SDValue RHS, SelectionDAG &DAG,
4539 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4540 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4541 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4544 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4553 OP_VUZPL, // VUZP, left result
4554 OP_VUZPR, // VUZP, right result
4555 OP_VZIPL, // VZIP, left result
4556 OP_VZIPR, // VZIP, right result
4557 OP_VTRNL, // VTRN, left result
4558 OP_VTRNR // VTRN, right result
4561 if (OpNum == OP_COPY) {
4562 if (LHSID == (1 * 9 + 2) * 9 + 3)
4564 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4568 SDValue OpLHS, OpRHS;
4569 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4570 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4571 EVT VT = OpLHS.getValueType();
4575 llvm_unreachable("Unknown shuffle opcode!");
4577 // VREV divides the vector in half and swaps within the half.
4578 if (VT.getVectorElementType() == MVT::i32 ||
4579 VT.getVectorElementType() == MVT::f32)
4580 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4581 // vrev <4 x i16> -> REV32
4582 if (VT.getVectorElementType() == MVT::i16)
4583 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4584 // vrev <4 x i8> -> REV16
4585 assert(VT.getVectorElementType() == MVT::i8);
4586 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4591 EVT EltTy = VT.getVectorElementType();
4593 if (EltTy == MVT::i8)
4594 Opcode = ARM64ISD::DUPLANE8;
4595 else if (EltTy == MVT::i16)
4596 Opcode = ARM64ISD::DUPLANE16;
4597 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4598 Opcode = ARM64ISD::DUPLANE32;
4599 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4600 Opcode = ARM64ISD::DUPLANE64;
4602 llvm_unreachable("Invalid vector element type?");
4604 if (VT.getSizeInBits() == 64)
4605 OpLHS = WidenVector(OpLHS, DAG);
4606 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4607 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4612 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4613 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4614 DAG.getConstant(Imm, MVT::i32));
4617 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4619 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4621 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4623 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4625 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4627 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4631 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4632 SelectionDAG &DAG) {
4633 // Check to see if we can use the TBL instruction.
4634 SDValue V1 = Op.getOperand(0);
4635 SDValue V2 = Op.getOperand(1);
4638 EVT EltVT = Op.getValueType().getVectorElementType();
4639 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4641 SmallVector<SDValue, 8> TBLMask;
4642 for (int Val : ShuffleMask) {
4643 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4644 unsigned Offset = Byte + Val * BytesPerElt;
4645 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4649 MVT IndexVT = MVT::v8i8;
4650 unsigned IndexLen = 8;
4651 if (Op.getValueType().getSizeInBits() == 128) {
4652 IndexVT = MVT::v16i8;
4656 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4657 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4660 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4662 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4663 Shuffle = DAG.getNode(
4664 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4665 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4666 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4668 if (IndexLen == 8) {
4669 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4670 Shuffle = DAG.getNode(
4671 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4672 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4673 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4675 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4676 // cannot currently represent the register constraints on the input
4678 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4679 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4680 // &TBLMask[0], IndexLen));
4681 Shuffle = DAG.getNode(
4682 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4683 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4684 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4687 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4690 static unsigned getDUPLANEOp(EVT EltType) {
4691 if (EltType == MVT::i8)
4692 return ARM64ISD::DUPLANE8;
4693 if (EltType == MVT::i16)
4694 return ARM64ISD::DUPLANE16;
4695 if (EltType == MVT::i32 || EltType == MVT::f32)
4696 return ARM64ISD::DUPLANE32;
4697 if (EltType == MVT::i64 || EltType == MVT::f64)
4698 return ARM64ISD::DUPLANE64;
4700 llvm_unreachable("Invalid vector element type?");
4703 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4704 SelectionDAG &DAG) const {
4706 EVT VT = Op.getValueType();
4708 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4710 // Convert shuffles that are directly supported on NEON to target-specific
4711 // DAG nodes, instead of keeping them as shuffles and matching them again
4712 // during code selection. This is more efficient and avoids the possibility
4713 // of inconsistencies between legalization and selection.
4714 ArrayRef<int> ShuffleMask = SVN->getMask();
4716 SDValue V1 = Op.getOperand(0);
4717 SDValue V2 = Op.getOperand(1);
4719 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4720 V1.getValueType().getSimpleVT())) {
4721 int Lane = SVN->getSplatIndex();
4722 // If this is undef splat, generate it via "just" vdup, if possible.
4726 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4727 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4729 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4730 // constant. If so, we can just reference the lane's definition directly.
4731 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4732 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4733 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4735 // Otherwise, duplicate from the lane of the input vector.
4736 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4738 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4739 // to make a vector of the same size as this SHUFFLE. We can ignore the
4740 // extract entirely, and canonicalise the concat using WidenVector.
4741 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4742 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4743 V1 = V1.getOperand(0);
4744 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4745 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4746 Lane -= Idx * VT.getVectorNumElements() / 2;
4747 V1 = WidenVector(V1.getOperand(Idx), DAG);
4748 } else if (VT.getSizeInBits() == 64)
4749 V1 = WidenVector(V1, DAG);
4751 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4754 if (isREVMask(ShuffleMask, VT, 64))
4755 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4756 if (isREVMask(ShuffleMask, VT, 32))
4757 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4758 if (isREVMask(ShuffleMask, VT, 16))
4759 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4761 bool ReverseEXT = false;
4763 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4766 Imm *= getExtFactor(V1);
4767 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4768 DAG.getConstant(Imm, MVT::i32));
4769 } else if (V2->getOpcode() == ISD::UNDEF &&
4770 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4771 Imm *= getExtFactor(V1);
4772 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4773 DAG.getConstant(Imm, MVT::i32));
4776 unsigned WhichResult;
4777 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4778 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4779 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4781 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4782 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4783 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4785 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4786 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4787 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4790 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4791 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4792 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4794 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4795 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4796 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4798 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4799 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4800 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4803 // If the shuffle is not directly supported and it has 4 elements, use
4804 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4805 unsigned NumElts = VT.getVectorNumElements();
4807 unsigned PFIndexes[4];
4808 for (unsigned i = 0; i != 4; ++i) {
4809 if (ShuffleMask[i] < 0)
4812 PFIndexes[i] = ShuffleMask[i];
4815 // Compute the index in the perfect shuffle table.
4816 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4817 PFIndexes[2] * 9 + PFIndexes[3];
4818 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4819 unsigned Cost = (PFEntry >> 30);
4822 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4825 return GenerateTBL(Op, ShuffleMask, DAG);
4828 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4830 EVT VT = BVN->getValueType(0);
4831 APInt SplatBits, SplatUndef;
4832 unsigned SplatBitSize;
4834 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4835 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4837 for (unsigned i = 0; i < NumSplats; ++i) {
4838 CnstBits <<= SplatBitSize;
4839 UndefBits <<= SplatBitSize;
4840 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4841 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4850 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4851 SelectionDAG &DAG) const {
4852 BuildVectorSDNode *BVN =
4853 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4854 SDValue LHS = Op.getOperand(0);
4856 EVT VT = Op.getValueType();
4861 APInt CnstBits(VT.getSizeInBits(), 0);
4862 APInt UndefBits(VT.getSizeInBits(), 0);
4863 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4864 // We only have BIC vector immediate instruction, which is and-not.
4865 CnstBits = ~CnstBits;
4867 // We make use of a little bit of goto ickiness in order to avoid having to
4868 // duplicate the immediate matching logic for the undef toggled case.
4869 bool SecondTry = false;
4872 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4873 CnstBits = CnstBits.zextOrTrunc(64);
4874 uint64_t CnstVal = CnstBits.getZExtValue();
4876 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4877 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4878 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4879 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4880 DAG.getConstant(CnstVal, MVT::i32),
4881 DAG.getConstant(0, MVT::i32));
4882 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4885 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4886 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4887 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4888 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4889 DAG.getConstant(CnstVal, MVT::i32),
4890 DAG.getConstant(8, MVT::i32));
4891 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4894 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4895 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4896 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4897 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4898 DAG.getConstant(CnstVal, MVT::i32),
4899 DAG.getConstant(16, MVT::i32));
4900 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4903 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4904 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4905 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4906 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4907 DAG.getConstant(CnstVal, MVT::i32),
4908 DAG.getConstant(24, MVT::i32));
4909 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4912 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4913 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4914 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4915 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4916 DAG.getConstant(CnstVal, MVT::i32),
4917 DAG.getConstant(0, MVT::i32));
4918 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4921 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4922 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4923 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4924 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4925 DAG.getConstant(CnstVal, MVT::i32),
4926 DAG.getConstant(8, MVT::i32));
4927 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4934 CnstBits = ~UndefBits;
4938 // We can always fall back to a non-immediate AND.
4943 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4944 // consists of only the same constant int value, returned in reference arg
4946 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4947 uint64_t &ConstVal) {
4948 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4951 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4954 EVT VT = Bvec->getValueType(0);
4955 unsigned NumElts = VT.getVectorNumElements();
4956 for (unsigned i = 1; i < NumElts; ++i)
4957 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4959 ConstVal = FirstElt->getZExtValue();
4963 static unsigned getIntrinsicID(const SDNode *N) {
4964 unsigned Opcode = N->getOpcode();
4967 return Intrinsic::not_intrinsic;
4968 case ISD::INTRINSIC_WO_CHAIN: {
4969 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4970 if (IID < Intrinsic::num_intrinsics)
4972 return Intrinsic::not_intrinsic;
4977 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4978 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4979 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4980 // Also, logical shift right -> sri, with the same structure.
4981 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4982 EVT VT = N->getValueType(0);
4989 // Is the first op an AND?
4990 const SDValue And = N->getOperand(0);
4991 if (And.getOpcode() != ISD::AND)
4994 // Is the second op an shl or lshr?
4995 SDValue Shift = N->getOperand(1);
4996 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4997 // or ARM64ISD::VLSHR vector, #shift
4998 unsigned ShiftOpc = Shift.getOpcode();
4999 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
5001 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
5003 // Is the shift amount constant?
5004 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5008 // Is the and mask vector all constant?
5010 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5013 // Is C1 == ~C2, taking into account how much one can shift elements of a
5015 uint64_t C2 = C2node->getZExtValue();
5016 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5017 if (C2 > ElemSizeInBits)
5019 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5020 if ((C1 & ElemMask) != (~C2 & ElemMask))
5023 SDValue X = And.getOperand(0);
5024 SDValue Y = Shift.getOperand(0);
5027 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
5029 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5030 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5032 DEBUG(dbgs() << "arm64-lower: transformed: \n");
5033 DEBUG(N->dump(&DAG));
5034 DEBUG(dbgs() << "into: \n");
5035 DEBUG(ResultSLI->dump(&DAG));
5041 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
5042 SelectionDAG &DAG) const {
5043 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5044 if (EnableARM64SlrGeneration) {
5045 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5050 BuildVectorSDNode *BVN =
5051 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5052 SDValue LHS = Op.getOperand(1);
5054 EVT VT = Op.getValueType();
5056 // OR commutes, so try swapping the operands.
5058 LHS = Op.getOperand(0);
5059 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5064 APInt CnstBits(VT.getSizeInBits(), 0);
5065 APInt UndefBits(VT.getSizeInBits(), 0);
5066 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5067 // We make use of a little bit of goto ickiness in order to avoid having to
5068 // duplicate the immediate matching logic for the undef toggled case.
5069 bool SecondTry = false;
5072 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5073 CnstBits = CnstBits.zextOrTrunc(64);
5074 uint64_t CnstVal = CnstBits.getZExtValue();
5076 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5077 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5078 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5079 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5080 DAG.getConstant(CnstVal, MVT::i32),
5081 DAG.getConstant(0, MVT::i32));
5082 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5085 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5086 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5087 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5088 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5089 DAG.getConstant(CnstVal, MVT::i32),
5090 DAG.getConstant(8, MVT::i32));
5091 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5094 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5095 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5096 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5097 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5098 DAG.getConstant(CnstVal, MVT::i32),
5099 DAG.getConstant(16, MVT::i32));
5100 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5103 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5104 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5105 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5106 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5107 DAG.getConstant(CnstVal, MVT::i32),
5108 DAG.getConstant(24, MVT::i32));
5109 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5112 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5113 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5114 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5115 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5116 DAG.getConstant(CnstVal, MVT::i32),
5117 DAG.getConstant(0, MVT::i32));
5118 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5121 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5122 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5123 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5124 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
5125 DAG.getConstant(CnstVal, MVT::i32),
5126 DAG.getConstant(8, MVT::i32));
5127 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5134 CnstBits = UndefBits;
5138 // We can always fall back to a non-immediate OR.
5143 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5144 SelectionDAG &DAG) const {
5145 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5147 EVT VT = Op.getValueType();
5149 APInt CnstBits(VT.getSizeInBits(), 0);
5150 APInt UndefBits(VT.getSizeInBits(), 0);
5151 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5152 // We make use of a little bit of goto ickiness in order to avoid having to
5153 // duplicate the immediate matching logic for the undef toggled case.
5154 bool SecondTry = false;
5157 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5158 CnstBits = CnstBits.zextOrTrunc(64);
5159 uint64_t CnstVal = CnstBits.getZExtValue();
5161 // Certain magic vector constants (used to express things like NOT
5162 // and NEG) are passed through unmodified. This allows codegen patterns
5163 // for these operations to match. Special-purpose patterns will lower
5164 // these immediates to MOVIs if it proves necessary.
5165 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5168 // The many faces of MOVI...
5169 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
5170 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
5171 if (VT.getSizeInBits() == 128) {
5172 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
5173 DAG.getConstant(CnstVal, MVT::i32));
5174 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5177 // Support the V64 version via subregister insertion.
5178 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
5179 DAG.getConstant(CnstVal, MVT::i32));
5180 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5183 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5184 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5185 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5186 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5187 DAG.getConstant(CnstVal, MVT::i32),
5188 DAG.getConstant(0, MVT::i32));
5189 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5192 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5193 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5194 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5195 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5196 DAG.getConstant(CnstVal, MVT::i32),
5197 DAG.getConstant(8, MVT::i32));
5198 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5201 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5202 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5203 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5204 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5205 DAG.getConstant(CnstVal, MVT::i32),
5206 DAG.getConstant(16, MVT::i32));
5207 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5210 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5211 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5212 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5213 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5214 DAG.getConstant(CnstVal, MVT::i32),
5215 DAG.getConstant(24, MVT::i32));
5216 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5219 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5220 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5221 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5222 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5223 DAG.getConstant(CnstVal, MVT::i32),
5224 DAG.getConstant(0, MVT::i32));
5225 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5228 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5229 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5230 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5231 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5232 DAG.getConstant(CnstVal, MVT::i32),
5233 DAG.getConstant(8, MVT::i32));
5234 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5237 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5238 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5239 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5240 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5241 DAG.getConstant(CnstVal, MVT::i32),
5242 DAG.getConstant(264, MVT::i32));
5243 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5246 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5247 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5248 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5249 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5250 DAG.getConstant(CnstVal, MVT::i32),
5251 DAG.getConstant(272, MVT::i32));
5252 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5255 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
5256 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
5257 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5258 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
5259 DAG.getConstant(CnstVal, MVT::i32));
5260 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5263 // The few faces of FMOV...
5264 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
5265 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
5266 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5267 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
5268 DAG.getConstant(CnstVal, MVT::i32));
5269 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5272 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
5273 VT.getSizeInBits() == 128) {
5274 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
5275 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
5276 DAG.getConstant(CnstVal, MVT::i32));
5277 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5280 // The many faces of MVNI...
5282 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5283 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5284 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5285 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5286 DAG.getConstant(CnstVal, MVT::i32),
5287 DAG.getConstant(0, MVT::i32));
5288 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5291 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5292 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5293 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5294 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5295 DAG.getConstant(CnstVal, MVT::i32),
5296 DAG.getConstant(8, MVT::i32));
5297 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5300 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5301 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5302 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5303 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5304 DAG.getConstant(CnstVal, MVT::i32),
5305 DAG.getConstant(16, MVT::i32));
5306 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5309 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5310 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5311 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5312 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5313 DAG.getConstant(CnstVal, MVT::i32),
5314 DAG.getConstant(24, MVT::i32));
5315 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5318 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5319 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5320 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5321 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5322 DAG.getConstant(CnstVal, MVT::i32),
5323 DAG.getConstant(0, MVT::i32));
5324 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5327 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5328 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5329 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5330 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5331 DAG.getConstant(CnstVal, MVT::i32),
5332 DAG.getConstant(8, MVT::i32));
5333 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5336 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5337 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5338 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5339 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5340 DAG.getConstant(CnstVal, MVT::i32),
5341 DAG.getConstant(264, MVT::i32));
5342 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5345 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5346 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5347 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5348 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5349 DAG.getConstant(CnstVal, MVT::i32),
5350 DAG.getConstant(272, MVT::i32));
5351 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5358 CnstBits = UndefBits;
5363 // Scan through the operands to find some interesting properties we can
5365 // 1) If only one value is used, we can use a DUP, or
5366 // 2) if only the low element is not undef, we can just insert that, or
5367 // 3) if only one constant value is used (w/ some non-constant lanes),
5368 // we can splat the constant value into the whole vector then fill
5369 // in the non-constant lanes.
5370 // 4) FIXME: If different constant values are used, but we can intelligently
5371 // select the values we'll be overwriting for the non-constant
5372 // lanes such that we can directly materialize the vector
5373 // some other way (MOVI, e.g.), we can be sneaky.
5374 unsigned NumElts = VT.getVectorNumElements();
5375 bool isOnlyLowElement = true;
5376 bool usesOnlyOneValue = true;
5377 bool usesOnlyOneConstantValue = true;
5378 bool isConstant = true;
5379 unsigned NumConstantLanes = 0;
5381 SDValue ConstantValue;
5382 for (unsigned i = 0; i < NumElts; ++i) {
5383 SDValue V = Op.getOperand(i);
5384 if (V.getOpcode() == ISD::UNDEF)
5387 isOnlyLowElement = false;
5388 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5391 if (isa<ConstantSDNode>(V)) {
5393 if (!ConstantValue.getNode())
5395 else if (ConstantValue != V)
5396 usesOnlyOneConstantValue = false;
5399 if (!Value.getNode())
5401 else if (V != Value)
5402 usesOnlyOneValue = false;
5405 if (!Value.getNode())
5406 return DAG.getUNDEF(VT);
5408 if (isOnlyLowElement)
5409 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5411 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5412 // i32 and try again.
5413 if (usesOnlyOneValue) {
5415 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5416 Value.getValueType() != VT)
5417 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5419 // This is actually a DUPLANExx operation, which keeps everything vectory.
5421 // DUPLANE works on 128-bit vectors, widen it if necessary.
5422 SDValue Lane = Value.getOperand(1);
5423 Value = Value.getOperand(0);
5424 if (Value.getValueType().getSizeInBits() == 64)
5425 Value = WidenVector(Value, DAG);
5427 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5428 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5431 if (VT.getVectorElementType().isFloatingPoint()) {
5432 SmallVector<SDValue, 8> Ops;
5434 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5435 for (unsigned i = 0; i < NumElts; ++i)
5436 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5437 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5438 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
5439 Val = LowerBUILD_VECTOR(Val, DAG);
5441 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5445 // If there was only one constant value used and for more than one lane,
5446 // start by splatting that value, then replace the non-constant lanes. This
5447 // is better than the default, which will perform a separate initialization
5449 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5450 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5451 // Now insert the non-constant lanes.
5452 for (unsigned i = 0; i < NumElts; ++i) {
5453 SDValue V = Op.getOperand(i);
5454 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5455 if (!isa<ConstantSDNode>(V)) {
5456 // Note that type legalization likely mucked about with the VT of the
5457 // source operand, so we may have to convert it here before inserting.
5458 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5464 // If all elements are constants and the case above didn't get hit, fall back
5465 // to the default expansion, which will generate a load from the constant
5470 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5472 SDValue shuffle = ReconstructShuffle(Op, DAG);
5473 if (shuffle != SDValue())
5477 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5478 // know the default expansion would otherwise fall back on something even
5479 // worse. For a vector with one or two non-undef values, that's
5480 // scalar_to_vector for the elements followed by a shuffle (provided the
5481 // shuffle is valid for the target) and materialization element by element
5482 // on the stack followed by a load for everything else.
5483 if (!isConstant && !usesOnlyOneValue) {
5484 SDValue Vec = DAG.getUNDEF(VT);
5485 SDValue Op0 = Op.getOperand(0);
5486 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5488 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5489 // a) Avoid a RMW dependency on the full vector register, and
5490 // b) Allow the register coalescer to fold away the copy if the
5491 // value is already in an S or D register.
5492 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5493 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5495 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5496 DAG.getTargetConstant(SubIdx, MVT::i32));
5497 Vec = SDValue(N, 0);
5500 for (; i < NumElts; ++i) {
5501 SDValue V = Op.getOperand(i);
5502 if (V.getOpcode() == ISD::UNDEF)
5504 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5505 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5510 // Just use the default expansion. We failed to find a better alternative.
5514 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5515 SelectionDAG &DAG) const {
5516 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5518 // Check for non-constant lane.
5519 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5522 EVT VT = Op.getOperand(0).getValueType();
5524 // Insertion/extraction are legal for V128 types.
5525 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5526 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5529 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5530 VT != MVT::v1i64 && VT != MVT::v2f32)
5533 // For V64 types, we perform insertion by expanding the value
5534 // to a V128 type and perform the insertion on that.
5536 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5537 EVT WideTy = WideVec.getValueType();
5539 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5540 Op.getOperand(1), Op.getOperand(2));
5541 // Re-narrow the resultant vector.
5542 return NarrowVector(Node, DAG);
5545 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5546 SelectionDAG &DAG) const {
5547 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5549 // Check for non-constant lane.
5550 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5553 EVT VT = Op.getOperand(0).getValueType();
5555 // Insertion/extraction are legal for V128 types.
5556 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5557 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5560 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5561 VT != MVT::v1i64 && VT != MVT::v2f32)
5564 // For V64 types, we perform extraction by expanding the value
5565 // to a V128 type and perform the extraction on that.
5567 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5568 EVT WideTy = WideVec.getValueType();
5570 EVT ExtrTy = WideTy.getVectorElementType();
5571 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5574 // For extractions, we just return the result directly.
5575 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5579 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5580 SelectionDAG &DAG) const {
5581 EVT VT = Op.getOperand(0).getValueType();
5587 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5590 unsigned Val = Cst->getZExtValue();
5592 unsigned Size = Op.getValueType().getSizeInBits();
5596 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5599 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5602 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5605 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5608 llvm_unreachable("Unexpected vector type in extract_subvector!");
5611 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5613 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5619 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5621 if (VT.getVectorNumElements() == 4 &&
5622 (VT.is128BitVector() || VT.is64BitVector())) {
5623 unsigned PFIndexes[4];
5624 for (unsigned i = 0; i != 4; ++i) {
5628 PFIndexes[i] = M[i];
5631 // Compute the index in the perfect shuffle table.
5632 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5633 PFIndexes[2] * 9 + PFIndexes[3];
5634 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5635 unsigned Cost = (PFEntry >> 30);
5642 unsigned Imm, WhichResult;
5644 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5645 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5646 isEXTMask(M, VT, ReverseVEXT, Imm) ||
5647 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5648 isTRNMask(M, VT, WhichResult) || isUZPMask(M, VT, WhichResult) ||
5649 isZIPMask(M, VT, WhichResult) ||
5650 isTRN_v_undef_Mask(M, VT, WhichResult) ||
5651 isUZP_v_undef_Mask(M, VT, WhichResult) ||
5652 isZIP_v_undef_Mask(M, VT, WhichResult));
5655 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5656 /// operand of a vector shift operation, where all the elements of the
5657 /// build_vector must have the same constant integer value.
5658 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5659 // Ignore bit_converts.
5660 while (Op.getOpcode() == ISD::BITCAST)
5661 Op = Op.getOperand(0);
5662 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5663 APInt SplatBits, SplatUndef;
5664 unsigned SplatBitSize;
5666 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5667 HasAnyUndefs, ElementBits) ||
5668 SplatBitSize > ElementBits)
5670 Cnt = SplatBits.getSExtValue();
5674 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5675 /// operand of a vector shift left operation. That value must be in the range:
5676 /// 0 <= Value < ElementBits for a left shift; or
5677 /// 0 <= Value <= ElementBits for a long left shift.
5678 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5679 assert(VT.isVector() && "vector shift count is not a vector type");
5680 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5681 if (!getVShiftImm(Op, ElementBits, Cnt))
5683 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5686 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5687 /// operand of a vector shift right operation. For a shift opcode, the value
5688 /// is positive, but for an intrinsic the value count must be negative. The
5689 /// absolute value must be in the range:
5690 /// 1 <= |Value| <= ElementBits for a right shift; or
5691 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5692 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5694 assert(VT.isVector() && "vector shift count is not a vector type");
5695 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5696 if (!getVShiftImm(Op, ElementBits, Cnt))
5700 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5703 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5704 SelectionDAG &DAG) const {
5705 EVT VT = Op.getValueType();
5709 if (!Op.getOperand(1).getValueType().isVector())
5711 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5713 switch (Op.getOpcode()) {
5715 llvm_unreachable("unexpected shift opcode");
5718 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5719 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5720 DAG.getConstant(Cnt, MVT::i32));
5721 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5722 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5723 Op.getOperand(0), Op.getOperand(1));
5726 // Right shift immediate
5727 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5730 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5731 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5732 DAG.getConstant(Cnt, MVT::i32));
5735 // Right shift register. Note, there is not a shift right register
5736 // instruction, but the shift left register instruction takes a signed
5737 // value, where negative numbers specify a right shift.
5738 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5739 : Intrinsic::arm64_neon_ushl;
5740 // negate the shift amount
5741 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5742 SDValue NegShiftLeft =
5743 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5744 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5745 return NegShiftLeft;
5751 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5752 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5753 SDLoc dl, SelectionDAG &DAG) {
5754 EVT SrcVT = LHS.getValueType();
5756 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5757 APInt CnstBits(VT.getSizeInBits(), 0);
5758 APInt UndefBits(VT.getSizeInBits(), 0);
5759 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5760 bool IsZero = IsCnst && (CnstBits == 0);
5762 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5769 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5771 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5772 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5776 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5777 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5780 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5781 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5784 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5785 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5788 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5789 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5793 // If we ignore NaNs then we can use to the MI implementation.
5797 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5798 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5808 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5810 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5811 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5815 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5816 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5819 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5820 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5823 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5824 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5827 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5828 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5830 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5832 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5835 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5836 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5838 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5840 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5844 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5845 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5846 SDValue LHS = Op.getOperand(0);
5847 SDValue RHS = Op.getOperand(1);
5850 if (LHS.getValueType().getVectorElementType().isInteger()) {
5851 assert(LHS.getValueType() == RHS.getValueType());
5852 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5853 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5857 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5858 LHS.getValueType().getVectorElementType() == MVT::f64);
5860 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5861 // clean. Some of them require two branches to implement.
5862 ARM64CC::CondCode CC1, CC2;
5863 changeFPCCToARM64CC(CC, CC1, CC2);
5865 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5867 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5868 if (!Cmp1.getNode())
5871 if (CC2 != ARM64CC::AL) {
5873 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5874 if (!Cmp2.getNode())
5877 return DAG.getNode(ISD::OR, dl, Cmp1.getValueType(), Cmp1, Cmp2);
5883 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5884 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5885 /// specified in the intrinsic calls.
5886 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5888 unsigned Intrinsic) const {
5889 switch (Intrinsic) {
5890 case Intrinsic::arm64_neon_ld2:
5891 case Intrinsic::arm64_neon_ld3:
5892 case Intrinsic::arm64_neon_ld4:
5893 case Intrinsic::arm64_neon_ld2lane:
5894 case Intrinsic::arm64_neon_ld3lane:
5895 case Intrinsic::arm64_neon_ld4lane:
5896 case Intrinsic::arm64_neon_ld2r:
5897 case Intrinsic::arm64_neon_ld3r:
5898 case Intrinsic::arm64_neon_ld4r: {
5899 Info.opc = ISD::INTRINSIC_W_CHAIN;
5900 // Conservatively set memVT to the entire set of vectors loaded.
5901 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5902 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5903 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5906 Info.vol = false; // volatile loads with NEON intrinsics not supported
5907 Info.readMem = true;
5908 Info.writeMem = false;
5911 case Intrinsic::arm64_neon_st2:
5912 case Intrinsic::arm64_neon_st3:
5913 case Intrinsic::arm64_neon_st4:
5914 case Intrinsic::arm64_neon_st2lane:
5915 case Intrinsic::arm64_neon_st3lane:
5916 case Intrinsic::arm64_neon_st4lane: {
5917 Info.opc = ISD::INTRINSIC_VOID;
5918 // Conservatively set memVT to the entire set of vectors stored.
5919 unsigned NumElts = 0;
5920 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5921 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5922 if (!ArgTy->isVectorTy())
5924 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5926 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5927 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5930 Info.vol = false; // volatile stores with NEON intrinsics not supported
5931 Info.readMem = false;
5932 Info.writeMem = true;
5935 case Intrinsic::arm64_ldxr: {
5936 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5937 Info.opc = ISD::INTRINSIC_W_CHAIN;
5938 Info.memVT = MVT::getVT(PtrTy->getElementType());
5939 Info.ptrVal = I.getArgOperand(0);
5941 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5943 Info.readMem = true;
5944 Info.writeMem = false;
5947 case Intrinsic::arm64_stxr: {
5948 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5949 Info.opc = ISD::INTRINSIC_W_CHAIN;
5950 Info.memVT = MVT::getVT(PtrTy->getElementType());
5951 Info.ptrVal = I.getArgOperand(1);
5953 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5955 Info.readMem = false;
5956 Info.writeMem = true;
5959 case Intrinsic::arm64_ldxp: {
5960 Info.opc = ISD::INTRINSIC_W_CHAIN;
5961 Info.memVT = MVT::i128;
5962 Info.ptrVal = I.getArgOperand(0);
5966 Info.readMem = true;
5967 Info.writeMem = false;
5970 case Intrinsic::arm64_stxp: {
5971 Info.opc = ISD::INTRINSIC_W_CHAIN;
5972 Info.memVT = MVT::i128;
5973 Info.ptrVal = I.getArgOperand(2);
5977 Info.readMem = false;
5978 Info.writeMem = true;
5988 // Truncations from 64-bit GPR to 32-bit GPR is free.
5989 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5990 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5992 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5993 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5994 if (NumBits1 <= NumBits2)
5998 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5999 if (!VT1.isInteger() || !VT2.isInteger())
6001 unsigned NumBits1 = VT1.getSizeInBits();
6002 unsigned NumBits2 = VT2.getSizeInBits();
6003 if (NumBits1 <= NumBits2)
6008 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6010 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6011 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6013 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6014 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6015 if (NumBits1 == 32 && NumBits2 == 64)
6019 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6020 if (!VT1.isInteger() || !VT2.isInteger())
6022 unsigned NumBits1 = VT1.getSizeInBits();
6023 unsigned NumBits2 = VT2.getSizeInBits();
6024 if (NumBits1 == 32 && NumBits2 == 64)
6029 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6030 EVT VT1 = Val.getValueType();
6031 if (isZExtFree(VT1, VT2)) {
6035 if (Val.getOpcode() != ISD::LOAD)
6038 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6039 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
6040 VT2.isInteger() && VT1.getSizeInBits() <= 32);
6043 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
6044 unsigned &RequiredAligment) const {
6045 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6047 // Cyclone supports unaligned accesses.
6048 RequiredAligment = 0;
6049 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6050 return NumBits == 32 || NumBits == 64;
6053 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
6054 unsigned &RequiredAligment) const {
6055 if (!LoadedType.isSimple() ||
6056 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6058 // Cyclone supports unaligned accesses.
6059 RequiredAligment = 0;
6060 unsigned NumBits = LoadedType.getSizeInBits();
6061 return NumBits == 32 || NumBits == 64;
6064 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6065 unsigned AlignCheck) {
6066 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6067 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6070 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6071 unsigned SrcAlign, bool IsMemset,
6072 bool ZeroMemset, bool MemcpyStrSrc,
6073 MachineFunction &MF) const {
6074 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6075 // instruction to materialize the v2i64 zero and one store (with restrictive
6076 // addressing mode). Just do two i64 store of zero-registers.
6078 const Function *F = MF.getFunction();
6079 if (!IsMemset && Size >= 16 &&
6080 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
6081 Attribute::NoImplicitFloat) &&
6082 (memOpAlign(SrcAlign, DstAlign, 16) ||
6083 (allowsUnalignedMemoryAccesses(MVT::v2i64, 0, &Fast) && Fast)))
6086 return Size >= 8 ? MVT::i64 : MVT::i32;
6089 // 12-bit optionally shifted immediates are legal for adds.
6090 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6091 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6096 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6097 // immediates is the same as for an add or a sub.
6098 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6101 return isLegalAddImmediate(Immed);
6104 /// isLegalAddressingMode - Return true if the addressing mode represented
6105 /// by AM is legal for this target, for a load/store of the specified type.
6106 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6108 // ARM64 has five basic addressing modes:
6110 // reg + 9-bit signed offset
6111 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6113 // reg + SIZE_IN_BYTES * reg
6115 // No global is ever allowed as a base.
6119 // No reg+reg+imm addressing.
6120 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6123 // check reg + imm case:
6124 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6125 uint64_t NumBytes = 0;
6126 if (Ty->isSized()) {
6127 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6128 NumBytes = NumBits / 8;
6129 if (!isPowerOf2_64(NumBits))
6134 int64_t Offset = AM.BaseOffs;
6136 // 9-bit signed offset
6137 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6140 // 12-bit unsigned offset
6141 unsigned shift = Log2_64(NumBytes);
6142 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6143 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6144 (Offset >> shift) << shift == Offset)
6149 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6151 if (!AM.Scale || AM.Scale == 1 ||
6152 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6157 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6159 // Scaling factors are not free at all.
6160 // Operands | Rt Latency
6161 // -------------------------------------------
6163 // -------------------------------------------
6164 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6165 // Rt, [Xn, Wm, <extend> #imm] |
6166 if (isLegalAddressingMode(AM, Ty))
6167 // Scale represents reg2 * scale, thus account for 1 if
6168 // it is not equal to 0 or 1.
6169 return AM.Scale != 0 && AM.Scale != 1;
6173 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6174 VT = VT.getScalarType();
6179 switch (VT.getSimpleVT().SimpleTy) {
6191 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6192 // LR is a callee-save register, but we must treat it as clobbered by any call
6193 // site. Hence we include LR in the scratch registers, which are in turn added
6194 // as implicit-defs for stackmaps and patchpoints.
6195 static const MCPhysReg ScratchRegs[] = {
6196 ARM64::X16, ARM64::X17, ARM64::LR, 0
6201 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6203 assert(Ty->isIntegerTy());
6205 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6209 int64_t Val = Imm.getSExtValue();
6210 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
6213 if ((int64_t)Val < 0)
6216 Val &= (1LL << 32) - 1;
6218 unsigned LZ = countLeadingZeros((uint64_t)Val);
6219 unsigned Shift = (63 - LZ) / 16;
6220 // MOVZ is free so return true for one or fewer MOVK.
6221 return (Shift < 3) ? true : false;
6224 // Generate SUBS and CSEL for integer abs.
6225 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6226 EVT VT = N->getValueType(0);
6228 SDValue N0 = N->getOperand(0);
6229 SDValue N1 = N->getOperand(1);
6232 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6233 // and change it to SUB and CSEL.
6234 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6235 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6236 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6237 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6238 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6239 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6241 // Generate SUBS & CSEL.
6243 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6244 N0.getOperand(0), DAG.getConstant(0, VT));
6245 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6246 DAG.getConstant(ARM64CC::PL, MVT::i32),
6247 SDValue(Cmp.getNode(), 1));
6252 // performXorCombine - Attempts to handle integer ABS.
6253 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6254 TargetLowering::DAGCombinerInfo &DCI,
6255 const ARM64Subtarget *Subtarget) {
6256 if (DCI.isBeforeLegalizeOps())
6259 return performIntegerAbsCombine(N, DAG);
6262 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6263 TargetLowering::DAGCombinerInfo &DCI,
6264 const ARM64Subtarget *Subtarget) {
6265 if (DCI.isBeforeLegalizeOps())
6268 // Multiplication of a power of two plus/minus one can be done more
6269 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6270 // future CPUs have a cheaper MADD instruction, this may need to be
6271 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6272 // 64-bit is 5 cycles, so this is always a win.
6273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6274 APInt Value = C->getAPIntValue();
6275 EVT VT = N->getValueType(0);
6276 APInt VP1 = Value + 1;
6277 if (VP1.isPowerOf2()) {
6278 // Multiplying by one less than a power of two, replace with a shift
6280 SDValue ShiftedVal =
6281 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6282 DAG.getConstant(VP1.logBase2(), MVT::i64));
6283 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6285 APInt VM1 = Value - 1;
6286 if (VM1.isPowerOf2()) {
6287 // Multiplying by one more than a power of two, replace with a shift
6289 SDValue ShiftedVal =
6290 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6291 DAG.getConstant(VM1.logBase2(), MVT::i64));
6292 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6298 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6299 EVT VT = N->getValueType(0);
6300 if (VT != MVT::f32 && VT != MVT::f64)
6302 // Only optimize when the source and destination types have the same width.
6303 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6306 // If the result of an integer load is only used by an integer-to-float
6307 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6308 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6309 SDValue N0 = N->getOperand(0);
6310 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6311 // Do not change the width of a volatile load.
6312 !cast<LoadSDNode>(N0)->isVolatile()) {
6313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6314 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6315 LN0->getPointerInfo(), LN0->isVolatile(),
6316 LN0->isNonTemporal(), LN0->isInvariant(),
6317 LN0->getAlignment());
6319 // Make sure successors of the original load stay after it by updating them
6320 // to use the new Chain.
6321 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6324 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6325 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6331 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6332 /// searches for and classifies those shifts.
6333 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6335 if (N.getOpcode() == ISD::SHL)
6337 else if (N.getOpcode() == ISD::SRL)
6342 if (!isa<ConstantSDNode>(N.getOperand(1)))
6345 ShiftAmount = N->getConstantOperandVal(1);
6346 Src = N->getOperand(0);
6350 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6351 /// registers viewed as a high/low pair. This function looks for the pattern:
6352 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6353 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6355 static SDValue tryCombineToEXTR(SDNode *N,
6356 TargetLowering::DAGCombinerInfo &DCI) {
6357 SelectionDAG &DAG = DCI.DAG;
6359 EVT VT = N->getValueType(0);
6361 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6363 if (VT != MVT::i32 && VT != MVT::i64)
6367 uint32_t ShiftLHS = 0;
6369 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6373 uint32_t ShiftRHS = 0;
6375 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6378 // If they're both trying to come from the high part of the register, they're
6379 // not really an EXTR.
6380 if (LHSFromHi == RHSFromHi)
6383 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6387 std::swap(LHS, RHS);
6388 std::swap(ShiftLHS, ShiftRHS);
6391 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6392 DAG.getConstant(ShiftRHS, MVT::i64));
6395 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6396 const ARM64Subtarget *Subtarget) {
6397 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6398 if (!EnableARM64ExtrGeneration)
6400 SelectionDAG &DAG = DCI.DAG;
6401 EVT VT = N->getValueType(0);
6403 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6406 SDValue Res = tryCombineToEXTR(N, DCI);
6413 static SDValue performBitcastCombine(SDNode *N,
6414 TargetLowering::DAGCombinerInfo &DCI,
6415 SelectionDAG &DAG) {
6416 // Wait 'til after everything is legalized to try this. That way we have
6417 // legal vector types and such.
6418 if (DCI.isBeforeLegalizeOps())
6421 // Remove extraneous bitcasts around an extract_subvector.
6423 // (v4i16 (bitconvert
6424 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6426 // (extract_subvector ((v8i16 ...), (i64 4)))
6428 // Only interested in 64-bit vectors as the ultimate result.
6429 EVT VT = N->getValueType(0);
6432 if (VT.getSimpleVT().getSizeInBits() != 64)
6434 // Is the operand an extract_subvector starting at the beginning or halfway
6435 // point of the vector? A low half may also come through as an
6436 // EXTRACT_SUBREG, so look for that, too.
6437 SDValue Op0 = N->getOperand(0);
6438 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6439 !(Op0->isMachineOpcode() &&
6440 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6442 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6443 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6444 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6446 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6447 if (idx != ARM64::dsub)
6449 // The dsub reference is equivalent to a lane zero subvector reference.
6452 // Look through the bitcast of the input to the extract.
6453 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6455 SDValue Source = Op0->getOperand(0)->getOperand(0);
6456 // If the source type has twice the number of elements as our destination
6457 // type, we know this is an extract of the high or low half of the vector.
6458 EVT SVT = Source->getValueType(0);
6459 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6462 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6464 // Create the simplified form to just extract the low or high half of the
6465 // vector directly rather than bothering with the bitcasts.
6467 unsigned NumElements = VT.getVectorNumElements();
6469 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6470 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6472 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6473 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6479 static SDValue performConcatVectorsCombine(SDNode *N,
6480 TargetLowering::DAGCombinerInfo &DCI,
6481 SelectionDAG &DAG) {
6482 // Wait 'til after everything is legalized to try this. That way we have
6483 // legal vector types and such.
6484 if (DCI.isBeforeLegalizeOps())
6488 EVT VT = N->getValueType(0);
6490 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6491 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6492 // canonicalise to that.
6493 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6494 assert(VT.getVectorElementType().getSizeInBits() == 64);
6495 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6496 WidenVector(N->getOperand(0), DAG),
6497 DAG.getConstant(0, MVT::i64));
6500 // Canonicalise concat_vectors so that the right-hand vector has as few
6501 // bit-casts as possible before its real operation. The primary matching
6502 // destination for these operations will be the narrowing "2" instructions,
6503 // which depend on the operation being performed on this right-hand vector.
6505 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6507 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6509 SDValue Op1 = N->getOperand(1);
6510 if (Op1->getOpcode() != ISD::BITCAST)
6512 SDValue RHS = Op1->getOperand(0);
6513 MVT RHSTy = RHS.getValueType().getSimpleVT();
6514 // If the RHS is not a vector, this is not the pattern we're looking for.
6515 if (!RHSTy.isVector())
6518 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6520 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6521 RHSTy.getVectorNumElements() * 2);
6523 ISD::BITCAST, dl, VT,
6524 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6525 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6528 static SDValue tryCombineFixedPointConvert(SDNode *N,
6529 TargetLowering::DAGCombinerInfo &DCI,
6530 SelectionDAG &DAG) {
6531 // Wait 'til after everything is legalized to try this. That way we have
6532 // legal vector types and such.
6533 if (DCI.isBeforeLegalizeOps())
6535 // Transform a scalar conversion of a value from a lane extract into a
6536 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6537 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6538 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6540 // The second form interacts better with instruction selection and the
6541 // register allocator to avoid cross-class register copies that aren't
6542 // coalescable due to a lane reference.
6544 // Check the operand and see if it originates from a lane extract.
6545 SDValue Op1 = N->getOperand(1);
6546 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6547 // Yep, no additional predication needed. Perform the transform.
6548 SDValue IID = N->getOperand(0);
6549 SDValue Shift = N->getOperand(2);
6550 SDValue Vec = Op1.getOperand(0);
6551 SDValue Lane = Op1.getOperand(1);
6552 EVT ResTy = N->getValueType(0);
6556 // The vector width should be 128 bits by the time we get here, even
6557 // if it started as 64 bits (the extract_vector handling will have
6559 assert(Vec.getValueType().getSizeInBits() == 128 &&
6560 "unexpected vector size on extract_vector_elt!");
6561 if (Vec.getValueType() == MVT::v4i32)
6562 VecResTy = MVT::v4f32;
6563 else if (Vec.getValueType() == MVT::v2i64)
6564 VecResTy = MVT::v2f64;
6566 assert(0 && "unexpected vector type!");
6569 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6570 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6575 // AArch64 high-vector "long" operations are formed by performing the non-high
6576 // version on an extract_subvector of each operand which gets the high half:
6578 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6580 // However, there are cases which don't have an extract_high explicitly, but
6581 // have another operation that can be made compatible with one for free. For
6584 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6586 // This routine does the actual conversion of such DUPs, once outer routines
6587 // have determined that everything else is in order.
6588 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6589 // We can handle most types of duplicate, but the lane ones have an extra
6590 // operand saying *which* lane, so we need to know.
6592 switch (N.getOpcode()) {
6596 case ARM64ISD::DUPLANE8:
6597 case ARM64ISD::DUPLANE16:
6598 case ARM64ISD::DUPLANE32:
6599 case ARM64ISD::DUPLANE64:
6606 MVT NarrowTy = N.getSimpleValueType();
6607 if (!NarrowTy.is64BitVector())
6610 MVT ElementTy = NarrowTy.getVectorElementType();
6611 unsigned NumElems = NarrowTy.getVectorNumElements();
6612 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6616 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6619 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6621 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6622 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6625 static bool isEssentiallyExtractSubvector(SDValue N) {
6626 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6629 return N.getOpcode() == ISD::BITCAST &&
6630 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6633 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6634 struct GenericSetCCInfo {
6635 const SDValue *Opnd0;
6636 const SDValue *Opnd1;
6640 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6641 struct ARM64SetCCInfo {
6643 ARM64CC::CondCode CC;
6646 /// \brief Helper structure to keep track of SetCC information.
6648 GenericSetCCInfo Generic;
6649 ARM64SetCCInfo ARM64;
6652 /// \brief Helper structure to be able to read SetCC information.
6653 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6654 /// a GenericSetCCInfo.
6655 struct SetCCInfoAndKind {
6660 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6662 /// ARM64 lowered one.
6663 /// \p SetCCInfo is filled accordingly.
6664 /// \post SetCCInfo is meanginfull only when this function returns true.
6665 /// \return True when Op is a kind of SET_CC operation.
6666 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6667 // If this is a setcc, this is straight forward.
6668 if (Op.getOpcode() == ISD::SETCC) {
6669 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6670 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6671 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6672 SetCCInfo.IsARM64 = false;
6675 // Otherwise, check if this is a matching csel instruction.
6679 if (Op.getOpcode() != ARM64ISD::CSEL)
6681 // Set the information about the operands.
6682 // TODO: we want the operands of the Cmp not the csel
6683 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6684 SetCCInfo.IsARM64 = true;
6685 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6686 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6688 // Check that the operands matches the constraints:
6689 // (1) Both operands must be constants.
6690 // (2) One must be 1 and the other must be 0.
6691 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6692 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6695 if (!TValue || !FValue)
6699 if (!TValue->isOne()) {
6700 // Update the comparison when we are interested in !cc.
6701 std::swap(TValue, FValue);
6702 SetCCInfo.Info.ARM64.CC =
6703 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6705 return TValue->isOne() && FValue->isNullValue();
6708 // The folding we want to perform is:
6709 // (add x, (setcc cc ...) )
6711 // (csel x, (add x, 1), !cc ...)
6713 // The latter will get matched to a CSINC instruction.
6714 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6715 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6716 SDValue LHS = Op->getOperand(0);
6717 SDValue RHS = Op->getOperand(1);
6718 SetCCInfoAndKind InfoAndKind;
6720 // If neither operand is a SET_CC, give up.
6721 if (!isSetCC(LHS, InfoAndKind)) {
6722 std::swap(LHS, RHS);
6723 if (!isSetCC(LHS, InfoAndKind))
6727 // FIXME: This could be generatized to work for FP comparisons.
6728 EVT CmpVT = InfoAndKind.IsARM64
6729 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6730 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6731 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6737 if (InfoAndKind.IsARM64) {
6738 CCVal = DAG.getConstant(
6739 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6740 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6742 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6743 *InfoAndKind.Info.Generic.Opnd1,
6744 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6747 EVT VT = Op->getValueType(0);
6748 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6749 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6752 // The basic add/sub long vector instructions have variants with "2" on the end
6753 // which act on the high-half of their inputs. They are normally matched by
6756 // (add (zeroext (extract_high LHS)),
6757 // (zeroext (extract_high RHS)))
6758 // -> uaddl2 vD, vN, vM
6760 // However, if one of the extracts is something like a duplicate, this
6761 // instruction can still be used profitably. This function puts the DAG into a
6762 // more appropriate form for those patterns to trigger.
6763 static SDValue performAddSubLongCombine(SDNode *N,
6764 TargetLowering::DAGCombinerInfo &DCI,
6765 SelectionDAG &DAG) {
6766 if (DCI.isBeforeLegalizeOps())
6769 MVT VT = N->getSimpleValueType(0);
6770 if (!VT.is128BitVector()) {
6771 if (N->getOpcode() == ISD::ADD)
6772 return performSetccAddFolding(N, DAG);
6776 // Make sure both branches are extended in the same way.
6777 SDValue LHS = N->getOperand(0);
6778 SDValue RHS = N->getOperand(1);
6779 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6780 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6781 LHS.getOpcode() != RHS.getOpcode())
6784 unsigned ExtType = LHS.getOpcode();
6786 // It's not worth doing if at least one of the inputs isn't already an
6787 // extract, but we don't know which it'll be so we have to try both.
6788 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6789 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6793 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6794 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6795 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6799 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6802 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6805 // Massage DAGs which we can use the high-half "long" operations on into
6806 // something isel will recognize better. E.g.
6808 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6809 // (arm64_neon_umull (extract_high (v2i64 vec)))
6810 // (extract_high (v2i64 (dup128 scalar)))))
6812 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6813 TargetLowering::DAGCombinerInfo &DCI,
6814 SelectionDAG &DAG) {
6815 if (DCI.isBeforeLegalizeOps())
6818 SDValue LHS = N->getOperand(1);
6819 SDValue RHS = N->getOperand(2);
6820 assert(LHS.getValueType().is64BitVector() &&
6821 RHS.getValueType().is64BitVector() &&
6822 "unexpected shape for long operation");
6824 // Either node could be a DUP, but it's not worth doing both of them (you'd
6825 // just as well use the non-high version) so look for a corresponding extract
6826 // operation on the other "wing".
6827 if (isEssentiallyExtractSubvector(LHS)) {
6828 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6831 } else if (isEssentiallyExtractSubvector(RHS)) {
6832 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6837 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6838 N->getOperand(0), LHS, RHS);
6841 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6842 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6843 unsigned ElemBits = ElemTy.getSizeInBits();
6845 int64_t ShiftAmount;
6846 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6847 APInt SplatValue, SplatUndef;
6848 unsigned SplatBitSize;
6850 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6851 HasAnyUndefs, ElemBits) ||
6852 SplatBitSize != ElemBits)
6855 ShiftAmount = SplatValue.getSExtValue();
6856 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6857 ShiftAmount = CVN->getSExtValue();
6865 llvm_unreachable("Unknown shift intrinsic");
6866 case Intrinsic::arm64_neon_sqshl:
6867 Opcode = ARM64ISD::SQSHL_I;
6868 IsRightShift = false;
6870 case Intrinsic::arm64_neon_uqshl:
6871 Opcode = ARM64ISD::UQSHL_I;
6872 IsRightShift = false;
6874 case Intrinsic::arm64_neon_srshl:
6875 Opcode = ARM64ISD::SRSHR_I;
6876 IsRightShift = true;
6878 case Intrinsic::arm64_neon_urshl:
6879 Opcode = ARM64ISD::URSHR_I;
6880 IsRightShift = true;
6882 case Intrinsic::arm64_neon_sqshlu:
6883 Opcode = ARM64ISD::SQSHLU_I;
6884 IsRightShift = false;
6888 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6889 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6890 DAG.getConstant(-ShiftAmount, MVT::i32));
6891 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6892 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6893 DAG.getConstant(ShiftAmount, MVT::i32));
6898 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6899 // the intrinsics must be legal and take an i32, this means there's almost
6900 // certainly going to be a zext in the DAG which we can eliminate.
6901 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6902 SDValue AndN = N->getOperand(2);
6903 if (AndN.getOpcode() != ISD::AND)
6906 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6907 if (!CMask || CMask->getZExtValue() != Mask)
6910 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6911 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6914 static SDValue performIntrinsicCombine(SDNode *N,
6915 TargetLowering::DAGCombinerInfo &DCI,
6916 const ARM64Subtarget *Subtarget) {
6917 SelectionDAG &DAG = DCI.DAG;
6918 unsigned IID = getIntrinsicID(N);
6922 case Intrinsic::arm64_neon_vcvtfxs2fp:
6923 case Intrinsic::arm64_neon_vcvtfxu2fp:
6924 return tryCombineFixedPointConvert(N, DCI, DAG);
6926 case Intrinsic::arm64_neon_fmax:
6927 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6928 N->getOperand(1), N->getOperand(2));
6929 case Intrinsic::arm64_neon_fmin:
6930 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6931 N->getOperand(1), N->getOperand(2));
6932 case Intrinsic::arm64_neon_smull:
6933 case Intrinsic::arm64_neon_umull:
6934 case Intrinsic::arm64_neon_pmull:
6935 case Intrinsic::arm64_neon_sqdmull:
6936 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6937 case Intrinsic::arm64_neon_sqshl:
6938 case Intrinsic::arm64_neon_uqshl:
6939 case Intrinsic::arm64_neon_sqshlu:
6940 case Intrinsic::arm64_neon_srshl:
6941 case Intrinsic::arm64_neon_urshl:
6942 return tryCombineShiftImm(IID, N, DAG);
6943 case Intrinsic::arm64_crc32b:
6944 case Intrinsic::arm64_crc32cb:
6945 return tryCombineCRC32(0xff, N, DAG);
6946 case Intrinsic::arm64_crc32h:
6947 case Intrinsic::arm64_crc32ch:
6948 return tryCombineCRC32(0xffff, N, DAG);
6953 static SDValue performExtendCombine(SDNode *N,
6954 TargetLowering::DAGCombinerInfo &DCI,
6955 SelectionDAG &DAG) {
6956 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6957 // we can convert that DUP into another extract_high (of a bigger DUP), which
6958 // helps the backend to decide that an sabdl2 would be useful, saving a real
6959 // extract_high operation.
6960 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6961 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6962 SDNode *ABDNode = N->getOperand(0).getNode();
6963 unsigned IID = getIntrinsicID(ABDNode);
6964 if (IID == Intrinsic::arm64_neon_sabd ||
6965 IID == Intrinsic::arm64_neon_uabd) {
6966 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6967 if (!NewABD.getNode())
6970 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6975 // This is effectively a custom type legalization for ARM64.
6977 // Type legalization will split an extend of a small, legal, type to a larger
6978 // illegal type by first splitting the destination type, often creating
6979 // illegal source types, which then get legalized in isel-confusing ways,
6980 // leading to really terrible codegen. E.g.,
6981 // %result = v8i32 sext v8i8 %value
6983 // %losrc = extract_subreg %value, ...
6984 // %hisrc = extract_subreg %value, ...
6985 // %lo = v4i32 sext v4i8 %losrc
6986 // %hi = v4i32 sext v4i8 %hisrc
6987 // Things go rapidly downhill from there.
6989 // For ARM64, the [sz]ext vector instructions can only go up one element
6990 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6991 // take two instructions.
6993 // This implies that the most efficient way to do the extend from v8i8
6994 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6995 // the normal splitting to happen for the v8i16->v8i32.
6997 // This is pre-legalization to catch some cases where the default
6998 // type legalization will create ill-tempered code.
6999 if (!DCI.isBeforeLegalizeOps())
7002 // We're only interested in cleaning things up for non-legal vector types
7003 // here. If both the source and destination are legal, things will just
7004 // work naturally without any fiddling.
7005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7006 EVT ResVT = N->getValueType(0);
7007 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7009 // If the vector type isn't a simple VT, it's beyond the scope of what
7010 // we're worried about here. Let legalization do its thing and hope for
7012 if (!ResVT.isSimple())
7015 SDValue Src = N->getOperand(0);
7016 MVT SrcVT = Src->getValueType(0).getSimpleVT();
7017 // If the source VT is a 64-bit vector, we can play games and get the
7018 // better results we want.
7019 if (SrcVT.getSizeInBits() != 64)
7022 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7023 unsigned ElementCount = SrcVT.getVectorNumElements();
7024 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7026 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7028 // Now split the rest of the operation into two halves, each with a 64
7032 unsigned NumElements = ResVT.getVectorNumElements();
7033 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7034 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7035 ResVT.getVectorElementType(), NumElements / 2);
7037 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7038 LoVT.getVectorNumElements());
7039 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7040 DAG.getIntPtrConstant(0));
7041 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7042 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
7043 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7044 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7046 // Now combine the parts back together so we still have a single result
7047 // like the combiner expects.
7048 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7051 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7052 /// value. The load store optimizer pass will merge them to store pair stores.
7053 /// This has better performance than a splat of the scalar followed by a split
7054 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7055 /// followed by an ext.b and two stores.
7056 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7057 SDValue StVal = St->getValue();
7058 EVT VT = StVal.getValueType();
7060 // Don't replace floating point stores, they possibly won't be transformed to
7061 // stp because of the store pair suppress pass.
7062 if (VT.isFloatingPoint())
7065 // Check for insert vector elements.
7066 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7069 // We can express a splat as store pair(s) for 2 or 4 elements.
7070 unsigned NumVecElts = VT.getVectorNumElements();
7071 if (NumVecElts != 4 && NumVecElts != 2)
7073 SDValue SplatVal = StVal.getOperand(1);
7074 unsigned RemainInsertElts = NumVecElts - 1;
7076 // Check that this is a splat.
7077 while (--RemainInsertElts) {
7078 SDValue NextInsertElt = StVal.getOperand(0);
7079 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7081 if (NextInsertElt.getOperand(1) != SplatVal)
7083 StVal = NextInsertElt;
7085 unsigned OrigAlignment = St->getAlignment();
7086 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7087 unsigned Alignment = std::min(OrigAlignment, EltOffset);
7089 // Create scalar stores. This is at least as good as the code sequence for a
7090 // split unaligned store wich is a dup.s, ext.b, and two stores.
7091 // Most of the time the three stores should be replaced by store pair
7092 // instructions (stp).
7094 SDValue BasePtr = St->getBasePtr();
7096 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7097 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7099 unsigned Offset = EltOffset;
7100 while (--NumVecElts) {
7101 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7102 DAG.getConstant(Offset, MVT::i64));
7103 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7104 St->getPointerInfo(), St->isVolatile(),
7105 St->isNonTemporal(), Alignment);
7106 Offset += EltOffset;
7111 static SDValue performSTORECombine(SDNode *N,
7112 TargetLowering::DAGCombinerInfo &DCI,
7114 const ARM64Subtarget *Subtarget) {
7115 if (!DCI.isBeforeLegalize())
7118 StoreSDNode *S = cast<StoreSDNode>(N);
7119 if (S->isVolatile())
7122 // Cyclone has bad performance on unaligned 16B stores when crossing line and
7123 // page boundries. We want to split such stores.
7124 if (!Subtarget->isCyclone())
7127 // Don't split at Oz.
7128 MachineFunction &MF = DAG.getMachineFunction();
7129 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7130 AttributeSet::FunctionIndex, Attribute::MinSize);
7134 SDValue StVal = S->getValue();
7135 EVT VT = StVal.getValueType();
7137 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7138 // those up regresses performance on micro-benchmarks and olden/bh.
7139 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7142 // Split unaligned 16B stores. They are terrible for performance.
7143 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7144 // extensions can use this to mark that it does not want splitting to happen
7145 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7146 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7147 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7148 S->getAlignment() <= 2)
7151 // If we get a splat of a scalar convert this vector store to a store of
7152 // scalars. They will be merged into store pairs thereby removing two
7154 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7155 if (ReplacedSplat != SDValue())
7156 return ReplacedSplat;
7159 unsigned NumElts = VT.getVectorNumElements() / 2;
7160 // Split VT into two.
7162 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7163 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7164 DAG.getIntPtrConstant(0));
7165 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7166 DAG.getIntPtrConstant(NumElts));
7167 SDValue BasePtr = S->getBasePtr();
7169 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7170 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7171 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7172 DAG.getConstant(8, MVT::i64));
7173 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7174 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7178 // Optimize compare with zero and branch.
7179 static SDValue performBRCONDCombine(SDNode *N,
7180 TargetLowering::DAGCombinerInfo &DCI,
7181 SelectionDAG &DAG) {
7182 SDValue Chain = N->getOperand(0);
7183 SDValue Dest = N->getOperand(1);
7184 SDValue CCVal = N->getOperand(2);
7185 SDValue Cmp = N->getOperand(3);
7187 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7188 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7189 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
7192 unsigned CmpOpc = Cmp.getOpcode();
7193 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
7196 // Only attempt folding if there is only one use of the flag and no use of the
7198 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7201 SDValue LHS = Cmp.getOperand(0);
7202 SDValue RHS = Cmp.getOperand(1);
7204 assert(LHS.getValueType() == RHS.getValueType() &&
7205 "Expected the value type to be the same for both operands!");
7206 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7209 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7210 std::swap(LHS, RHS);
7212 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7215 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7216 LHS.getOpcode() == ISD::SRL)
7219 // Fold the compare into the branch instruction.
7221 if (CC == ARM64CC::EQ)
7222 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7224 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7226 // Do not add new nodes to DAG combiner worklist.
7227 DCI.CombineTo(N, BR, false);
7232 // vselect (v1i1 setcc) ->
7233 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
7234 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7235 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7237 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7238 SDValue N0 = N->getOperand(0);
7239 EVT CCVT = N0.getValueType();
7241 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7242 CCVT.getVectorElementType() != MVT::i1)
7245 EVT ResVT = N->getValueType(0);
7246 EVT CmpVT = N0.getOperand(0).getValueType();
7247 // Only combine when the result type is of the same size as the compared
7249 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7252 SDValue IfTrue = N->getOperand(1);
7253 SDValue IfFalse = N->getOperand(2);
7255 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7256 N0.getOperand(0), N0.getOperand(1),
7257 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7258 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7262 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7263 DAGCombinerInfo &DCI) const {
7264 SelectionDAG &DAG = DCI.DAG;
7265 switch (N->getOpcode()) {
7270 return performAddSubLongCombine(N, DCI, DAG);
7272 return performXorCombine(N, DAG, DCI, Subtarget);
7274 return performMulCombine(N, DAG, DCI, Subtarget);
7275 case ISD::SINT_TO_FP:
7276 case ISD::UINT_TO_FP:
7277 return performIntToFpCombine(N, DAG);
7279 return performORCombine(N, DCI, Subtarget);
7280 case ISD::INTRINSIC_WO_CHAIN:
7281 return performIntrinsicCombine(N, DCI, Subtarget);
7282 case ISD::ANY_EXTEND:
7283 case ISD::ZERO_EXTEND:
7284 case ISD::SIGN_EXTEND:
7285 return performExtendCombine(N, DCI, DAG);
7287 return performBitcastCombine(N, DCI, DAG);
7288 case ISD::CONCAT_VECTORS:
7289 return performConcatVectorsCombine(N, DCI, DAG);
7291 return performVSelectCombine(N, DCI.DAG);
7293 return performSTORECombine(N, DCI, DAG, Subtarget);
7294 case ARM64ISD::BRCOND:
7295 return performBRCONDCombine(N, DCI, DAG);
7300 // Check if the return value is used as only a return value, as otherwise
7301 // we can't perform a tail-call. In particular, we need to check for
7302 // target ISD nodes that are returns and any other "odd" constructs
7303 // that the generic analysis code won't necessarily catch.
7304 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7305 if (N->getNumValues() != 1)
7307 if (!N->hasNUsesOfValue(1, 0))
7310 SDValue TCChain = Chain;
7311 SDNode *Copy = *N->use_begin();
7312 if (Copy->getOpcode() == ISD::CopyToReg) {
7313 // If the copy has a glue operand, we conservatively assume it isn't safe to
7314 // perform a tail call.
7315 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7318 TCChain = Copy->getOperand(0);
7319 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7322 bool HasRet = false;
7323 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
7325 if (UI->getOpcode() != ARM64ISD::RET_FLAG)
7337 // Return whether the an instruction can potentially be optimized to a tail
7338 // call. This will cause the optimizers to attempt to move, or duplicate,
7339 // return instructions to help enable tail call optimizations for this
7341 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7342 if (!EnableARM64TailCalls)
7345 if (!CI->isTailCall())
7351 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7353 ISD::MemIndexedMode &AM,
7355 SelectionDAG &DAG) const {
7356 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7359 Base = Op->getOperand(0);
7360 // All of the indexed addressing mode instructions take a signed
7361 // 9 bit immediate offset.
7362 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7363 int64_t RHSC = (int64_t)RHS->getZExtValue();
7364 if (RHSC >= 256 || RHSC <= -256)
7366 IsInc = (Op->getOpcode() == ISD::ADD);
7367 Offset = Op->getOperand(1);
7373 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7375 ISD::MemIndexedMode &AM,
7376 SelectionDAG &DAG) const {
7379 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7380 VT = LD->getMemoryVT();
7381 Ptr = LD->getBasePtr();
7382 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7383 VT = ST->getMemoryVT();
7384 Ptr = ST->getBasePtr();
7389 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7391 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7395 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7398 ISD::MemIndexedMode &AM,
7399 SelectionDAG &DAG) const {
7402 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7403 VT = LD->getMemoryVT();
7404 Ptr = LD->getBasePtr();
7405 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7406 VT = ST->getMemoryVT();
7407 Ptr = ST->getBasePtr();
7412 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7414 // Post-indexing updates the base, so it's not a valid transform
7415 // if that's not the same as the load's pointer.
7418 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7422 /// The only 128-bit atomic operation is an stxp that succeeds. In particular
7423 /// neither ldp nor ldxp are atomic. So the canonical sequence for an atomic
7426 /// ldxp x0, x1, [x8]
7427 /// stxp w2, x0, x1, [x8]
7429 /// If the stxp succeeds then the ldxp managed to get both halves without an
7430 /// intervening stxp from a different thread and the read was atomic.
7431 static void ReplaceATOMIC_LOAD_128(SDNode *N, SmallVectorImpl<SDValue> &Results,
7432 SelectionDAG &DAG) {
7434 AtomicSDNode *AN = cast<AtomicSDNode>(N);
7435 EVT VT = AN->getMemoryVT();
7436 SDValue Zero = DAG.getConstant(0, VT);
7438 // FIXME: Really want ATOMIC_LOAD_NOP but that doesn't fit into the existing
7439 // scheme very well. Given the complexity of what we're already generating, an
7440 // extra couple of ORRs probably won't make much difference.
7441 SDValue Result = DAG.getAtomic(ISD::ATOMIC_LOAD_OR, DL, AN->getMemoryVT(),
7442 N->getOperand(0), N->getOperand(1), Zero,
7443 AN->getMemOperand(), AN->getOrdering(),
7444 AN->getSynchScope());
7446 Results.push_back(Result.getValue(0)); // Value
7447 Results.push_back(Result.getValue(1)); // Chain
7450 static void ReplaceATOMIC_OP_128(SDNode *N, SmallVectorImpl<SDValue> &Results,
7451 SelectionDAG &DAG, unsigned NewOp) {
7453 AtomicOrdering Ordering = cast<AtomicSDNode>(N)->getOrdering();
7454 assert(N->getValueType(0) == MVT::i128 &&
7455 "Only know how to expand i128 atomics");
7457 SmallVector<SDValue, 6> Ops;
7458 Ops.push_back(N->getOperand(1)); // Ptr
7460 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7461 N->getOperand(2), DAG.getIntPtrConstant(0)));
7462 // High part of Val1
7463 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7464 N->getOperand(2), DAG.getIntPtrConstant(1)));
7465 if (NewOp == ARM64::ATOMIC_CMP_SWAP_I128) {
7467 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7468 N->getOperand(3), DAG.getIntPtrConstant(0)));
7469 // High part of Val2
7470 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
7471 N->getOperand(3), DAG.getIntPtrConstant(1)));
7474 Ops.push_back(DAG.getTargetConstant(Ordering, MVT::i32));
7475 Ops.push_back(N->getOperand(0)); // Chain
7477 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
7478 SDNode *Result = DAG.getMachineNode(NewOp, DL, Tys, Ops);
7479 SDValue OpsF[] = { SDValue(Result, 0), SDValue(Result, 1) };
7480 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, OpsF, 2));
7481 Results.push_back(SDValue(Result, 2));
7484 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7485 SmallVectorImpl<SDValue> &Results,
7486 SelectionDAG &DAG) const {
7487 switch (N->getOpcode()) {
7489 llvm_unreachable("Don't know how to custom expand this");
7490 case ISD::ATOMIC_LOAD:
7491 ReplaceATOMIC_LOAD_128(N, Results, DAG);
7493 case ISD::ATOMIC_LOAD_ADD:
7494 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_ADD_I128);
7496 case ISD::ATOMIC_LOAD_SUB:
7497 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_SUB_I128);
7499 case ISD::ATOMIC_LOAD_AND:
7500 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_AND_I128);
7502 case ISD::ATOMIC_LOAD_OR:
7503 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_OR_I128);
7505 case ISD::ATOMIC_LOAD_XOR:
7506 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_XOR_I128);
7508 case ISD::ATOMIC_LOAD_NAND:
7509 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_NAND_I128);
7511 case ISD::ATOMIC_SWAP:
7512 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_SWAP_I128);
7514 case ISD::ATOMIC_LOAD_MIN:
7515 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_MIN_I128);
7517 case ISD::ATOMIC_LOAD_MAX:
7518 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_MAX_I128);
7520 case ISD::ATOMIC_LOAD_UMIN:
7521 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_UMIN_I128);
7523 case ISD::ATOMIC_LOAD_UMAX:
7524 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_LOAD_UMAX_I128);
7526 case ISD::ATOMIC_CMP_SWAP:
7527 ReplaceATOMIC_OP_128(N, Results, DAG, ARM64::ATOMIC_CMP_SWAP_I128);
7529 case ISD::FP_TO_UINT:
7530 case ISD::FP_TO_SINT:
7531 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7532 // Let normal code take care of it by not adding anything to Results.