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::f16, &ARM64::FPR16RegClass);
88 addRegisterClass(MVT::f32, &ARM64::FPR32RegClass);
89 addRegisterClass(MVT::f64, &ARM64::FPR64RegClass);
90 addRegisterClass(MVT::f128, &ARM64::FPR128RegClass);
91 addRegisterClass(MVT::v16i8, &ARM64::FPR8RegClass);
92 addRegisterClass(MVT::v8i16, &ARM64::FPR16RegClass);
94 // Someone set us up the NEON.
95 addDRTypeForNEON(MVT::v2f32);
96 addDRTypeForNEON(MVT::v8i8);
97 addDRTypeForNEON(MVT::v4i16);
98 addDRTypeForNEON(MVT::v2i32);
99 addDRTypeForNEON(MVT::v1i64);
100 addDRTypeForNEON(MVT::v1f64);
102 addQRTypeForNEON(MVT::v4f32);
103 addQRTypeForNEON(MVT::v2f64);
104 addQRTypeForNEON(MVT::v16i8);
105 addQRTypeForNEON(MVT::v8i16);
106 addQRTypeForNEON(MVT::v4i32);
107 addQRTypeForNEON(MVT::v2i64);
109 // Compute derived properties from the register classes
110 computeRegisterProperties();
112 // Provide all sorts of operation actions
113 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
114 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
115 setOperationAction(ISD::SETCC, MVT::i32, Custom);
116 setOperationAction(ISD::SETCC, MVT::i64, Custom);
117 setOperationAction(ISD::SETCC, MVT::f32, Custom);
118 setOperationAction(ISD::SETCC, MVT::f64, Custom);
119 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
120 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
121 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
123 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
124 setOperationAction(ISD::SELECT, MVT::i32, Custom);
125 setOperationAction(ISD::SELECT, MVT::i64, Custom);
126 setOperationAction(ISD::SELECT, MVT::f32, Custom);
127 setOperationAction(ISD::SELECT, MVT::f64, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
131 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
132 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
133 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
135 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
137 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
139 setOperationAction(ISD::FREM, MVT::f32, Expand);
140 setOperationAction(ISD::FREM, MVT::f64, Expand);
141 setOperationAction(ISD::FREM, MVT::f80, Expand);
143 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
144 // silliness like this:
145 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
146 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
147 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
148 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
149 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
150 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
151 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
152 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
153 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
154 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
155 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
156 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
157 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
158 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
159 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
160 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
162 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
163 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
164 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
165 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
166 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
167 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
168 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
169 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
171 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
172 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
173 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
174 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
175 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
177 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
179 // Custom lowering hooks are needed for XOR
180 // to fold it into CSINC/CSINV.
181 setOperationAction(ISD::XOR, MVT::i32, Custom);
182 setOperationAction(ISD::XOR, MVT::i64, Custom);
184 // Virtually no operation on f128 is legal, but LLVM can't expand them when
185 // there's a valid register class, so we need custom operations in most cases.
186 setOperationAction(ISD::FABS, MVT::f128, Expand);
187 setOperationAction(ISD::FADD, MVT::f128, Custom);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
189 setOperationAction(ISD::FCOS, MVT::f128, Expand);
190 setOperationAction(ISD::FDIV, MVT::f128, Custom);
191 setOperationAction(ISD::FMA, MVT::f128, Expand);
192 setOperationAction(ISD::FMUL, MVT::f128, Custom);
193 setOperationAction(ISD::FNEG, MVT::f128, Expand);
194 setOperationAction(ISD::FPOW, MVT::f128, Expand);
195 setOperationAction(ISD::FREM, MVT::f128, Expand);
196 setOperationAction(ISD::FRINT, MVT::f128, Expand);
197 setOperationAction(ISD::FSIN, MVT::f128, Expand);
198 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
199 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
200 setOperationAction(ISD::FSUB, MVT::f128, Custom);
201 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
202 setOperationAction(ISD::SETCC, MVT::f128, Custom);
203 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
204 setOperationAction(ISD::SELECT, MVT::f128, Custom);
205 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
206 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
208 // Lowering for many of the conversions is actually specified by the non-f128
209 // type. The LowerXXX function will be trivial when f128 isn't involved.
210 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
211 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
212 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
213 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
214 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
215 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
216 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
217 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
218 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
219 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
220 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
221 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
222 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
223 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
225 // Variable arguments.
226 setOperationAction(ISD::VASTART, MVT::Other, Custom);
227 setOperationAction(ISD::VAARG, MVT::Other, Custom);
228 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
229 setOperationAction(ISD::VAEND, MVT::Other, Expand);
231 // Variable-sized objects.
232 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
233 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
234 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
236 // Exception handling.
237 // FIXME: These are guesses. Has this been defined yet?
238 setExceptionPointerRegister(ARM64::X0);
239 setExceptionSelectorRegister(ARM64::X1);
241 // Constant pool entries
242 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
245 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
247 // Add/Sub overflow ops with MVT::Glues are lowered to CPSR dependences.
248 setOperationAction(ISD::ADDC, MVT::i32, Custom);
249 setOperationAction(ISD::ADDE, MVT::i32, Custom);
250 setOperationAction(ISD::SUBC, MVT::i32, Custom);
251 setOperationAction(ISD::SUBE, MVT::i32, Custom);
252 setOperationAction(ISD::ADDC, MVT::i64, Custom);
253 setOperationAction(ISD::ADDE, MVT::i64, Custom);
254 setOperationAction(ISD::SUBC, MVT::i64, Custom);
255 setOperationAction(ISD::SUBE, MVT::i64, Custom);
257 // ARM64 lacks both left-rotate and popcount instructions.
258 setOperationAction(ISD::ROTL, MVT::i32, Expand);
259 setOperationAction(ISD::ROTL, MVT::i64, Expand);
261 // ARM64 doesn't have a direct vector ->f32 conversion instructions for
262 // elements smaller than i32, so promote the input to i32 first.
263 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
264 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
265 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
266 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
267 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
268 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
269 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
270 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
271 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
273 // ARM64 doesn't have {U|S}MUL_LOHI.
274 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
275 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
277 // ARM64 doesn't have MUL.2d:
278 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
280 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
281 // counterparts, which ARM64 supports directly.
282 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
283 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
284 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
285 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
287 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
288 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
290 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
291 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
292 setOperationAction(ISD::SREM, MVT::i32, Expand);
293 setOperationAction(ISD::SREM, MVT::i64, Expand);
294 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
295 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
296 setOperationAction(ISD::UREM, MVT::i32, Expand);
297 setOperationAction(ISD::UREM, MVT::i64, Expand);
299 // Custom lower Add/Sub/Mul with overflow.
300 setOperationAction(ISD::SADDO, MVT::i32, Custom);
301 setOperationAction(ISD::SADDO, MVT::i64, Custom);
302 setOperationAction(ISD::UADDO, MVT::i32, Custom);
303 setOperationAction(ISD::UADDO, MVT::i64, Custom);
304 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
305 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
306 setOperationAction(ISD::USUBO, MVT::i32, Custom);
307 setOperationAction(ISD::USUBO, MVT::i64, Custom);
308 setOperationAction(ISD::SMULO, MVT::i32, Custom);
309 setOperationAction(ISD::SMULO, MVT::i64, Custom);
310 setOperationAction(ISD::UMULO, MVT::i32, Custom);
311 setOperationAction(ISD::UMULO, MVT::i64, Custom);
313 setOperationAction(ISD::FSIN, MVT::f32, Expand);
314 setOperationAction(ISD::FSIN, MVT::f64, Expand);
315 setOperationAction(ISD::FCOS, MVT::f32, Expand);
316 setOperationAction(ISD::FCOS, MVT::f64, Expand);
317 setOperationAction(ISD::FPOW, MVT::f32, Expand);
318 setOperationAction(ISD::FPOW, MVT::f64, Expand);
319 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
320 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
322 // ARM64 has implementations of a lot of rounding-like FP operations.
323 static MVT RoundingTypes[] = { MVT::f32, MVT::f64, MVT::v2f32,
324 MVT::v4f32, MVT::v2f64 };
325 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
326 MVT Ty = RoundingTypes[I];
327 setOperationAction(ISD::FFLOOR, Ty, Legal);
328 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
329 setOperationAction(ISD::FCEIL, Ty, Legal);
330 setOperationAction(ISD::FRINT, Ty, Legal);
331 setOperationAction(ISD::FTRUNC, Ty, Legal);
332 setOperationAction(ISD::FROUND, Ty, Legal);
335 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
337 if (Subtarget->isTargetMachO()) {
338 // For iOS, we don't want to the normal expansion of a libcall to
339 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
341 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
342 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
344 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
345 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
348 // ARM64 does not have floating-point extending loads, i1 sign-extending load,
349 // floating-point truncating stores, or v2i32->v2i16 truncating store.
350 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
351 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
352 setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
353 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
354 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
355 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
356 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
357 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
358 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
359 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
360 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
361 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
362 // Indexed loads and stores are supported.
363 for (unsigned im = (unsigned)ISD::PRE_INC;
364 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
365 setIndexedLoadAction(im, MVT::i8, Legal);
366 setIndexedLoadAction(im, MVT::i16, Legal);
367 setIndexedLoadAction(im, MVT::i32, Legal);
368 setIndexedLoadAction(im, MVT::i64, Legal);
369 setIndexedLoadAction(im, MVT::f64, Legal);
370 setIndexedLoadAction(im, MVT::f32, Legal);
371 setIndexedStoreAction(im, MVT::i8, Legal);
372 setIndexedStoreAction(im, MVT::i16, Legal);
373 setIndexedStoreAction(im, MVT::i32, Legal);
374 setIndexedStoreAction(im, MVT::i64, Legal);
375 setIndexedStoreAction(im, MVT::f64, Legal);
376 setIndexedStoreAction(im, MVT::f32, Legal);
379 // Likewise, narrowing and extending vector loads/stores aren't handled
381 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
382 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
384 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
387 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
388 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
389 setTruncStoreAction((MVT::SimpleValueType)VT,
390 (MVT::SimpleValueType)InnerVT, Expand);
391 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
392 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
393 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
397 setOperationAction(ISD::TRAP, MVT::Other, Legal);
398 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
400 // We combine OR nodes for bitfield operations.
401 setTargetDAGCombine(ISD::OR);
403 // Vector add and sub nodes may conceal a high-half opportunity.
404 // Also, try to fold ADD into CSINC/CSINV..
405 setTargetDAGCombine(ISD::ADD);
406 setTargetDAGCombine(ISD::SUB);
408 setTargetDAGCombine(ISD::XOR);
409 setTargetDAGCombine(ISD::SINT_TO_FP);
410 setTargetDAGCombine(ISD::UINT_TO_FP);
412 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
414 setTargetDAGCombine(ISD::ANY_EXTEND);
415 setTargetDAGCombine(ISD::ZERO_EXTEND);
416 setTargetDAGCombine(ISD::SIGN_EXTEND);
417 setTargetDAGCombine(ISD::BITCAST);
418 setTargetDAGCombine(ISD::CONCAT_VECTORS);
419 setTargetDAGCombine(ISD::STORE);
421 setTargetDAGCombine(ISD::MUL);
423 setTargetDAGCombine(ISD::VSELECT);
425 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
426 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
427 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
429 setStackPointerRegisterToSaveRestore(ARM64::SP);
431 setSchedulingPreference(Sched::Hybrid);
434 MaskAndBranchFoldingIsLegal = true;
436 setMinFunctionAlignment(2);
438 RequireStrictAlign = StrictAlign;
441 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
442 if (VT == MVT::v2f32) {
443 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
444 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
446 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
447 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
448 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
449 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
450 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
452 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
453 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
456 // Mark vector float intrinsics as expand.
457 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
458 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
459 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
460 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
461 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
462 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
463 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
464 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
465 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
466 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
470 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
471 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
472 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
473 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
474 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
475 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
476 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
477 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
478 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
479 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
480 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
482 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
483 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
484 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
485 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
487 // CNT supports only B element sizes.
488 if (VT != MVT::v8i8 && VT != MVT::v16i8)
489 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
491 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
492 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
493 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
494 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
495 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
497 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
498 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
501 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
502 addRegisterClass(VT, &ARM64::FPR64RegClass);
503 addTypeForNEON(VT, MVT::v2i32);
506 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
507 addRegisterClass(VT, &ARM64::FPR128RegClass);
508 addTypeForNEON(VT, MVT::v4i32);
511 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
514 return VT.changeVectorElementTypeToInteger();
517 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
518 /// Mask are known to be either zero or one and return them in the
519 /// KnownZero/KnownOne bitsets.
520 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
521 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
522 const SelectionDAG &DAG, unsigned Depth) const {
523 switch (Op.getOpcode()) {
526 case ARM64ISD::CSEL: {
527 APInt KnownZero2, KnownOne2;
528 DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
529 DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
530 KnownZero &= KnownZero2;
531 KnownOne &= KnownOne2;
534 case ISD::INTRINSIC_W_CHAIN: {
535 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
536 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
539 case Intrinsic::arm64_ldaxr:
540 case Intrinsic::arm64_ldxr: {
541 unsigned BitWidth = KnownOne.getBitWidth();
542 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
543 unsigned MemBits = VT.getScalarType().getSizeInBits();
544 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
550 case ISD::INTRINSIC_WO_CHAIN:
551 case ISD::INTRINSIC_VOID: {
552 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
556 case Intrinsic::arm64_neon_umaxv:
557 case Intrinsic::arm64_neon_uminv: {
558 // Figure out the datatype of the vector operand. The UMINV instruction
559 // will zero extend the result, so we can mark as known zero all the
560 // bits larger than the element datatype. 32-bit or larget doesn't need
561 // this as those are legal types and will be handled by isel directly.
562 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
563 unsigned BitWidth = KnownZero.getBitWidth();
564 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
565 assert(BitWidth >= 8 && "Unexpected width!");
566 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
568 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
569 assert(BitWidth >= 16 && "Unexpected width!");
570 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
580 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
584 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
585 // FIXME: On ARM64, this depends on the type.
586 // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
587 // and the offset has to be a multiple of the related size in bytes.
592 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
593 const TargetLibraryInfo *libInfo) const {
594 return ARM64::createFastISel(funcInfo, libInfo);
597 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
601 case ARM64ISD::CALL: return "ARM64ISD::CALL";
602 case ARM64ISD::ADRP: return "ARM64ISD::ADRP";
603 case ARM64ISD::ADDlow: return "ARM64ISD::ADDlow";
604 case ARM64ISD::LOADgot: return "ARM64ISD::LOADgot";
605 case ARM64ISD::RET_FLAG: return "ARM64ISD::RET_FLAG";
606 case ARM64ISD::BRCOND: return "ARM64ISD::BRCOND";
607 case ARM64ISD::CSEL: return "ARM64ISD::CSEL";
608 case ARM64ISD::FCSEL: return "ARM64ISD::FCSEL";
609 case ARM64ISD::CSINV: return "ARM64ISD::CSINV";
610 case ARM64ISD::CSNEG: return "ARM64ISD::CSNEG";
611 case ARM64ISD::CSINC: return "ARM64ISD::CSINC";
612 case ARM64ISD::THREAD_POINTER: return "ARM64ISD::THREAD_POINTER";
613 case ARM64ISD::TLSDESC_CALL: return "ARM64ISD::TLSDESC_CALL";
614 case ARM64ISD::ADC: return "ARM64ISD::ADC";
615 case ARM64ISD::SBC: return "ARM64ISD::SBC";
616 case ARM64ISD::ADDS: return "ARM64ISD::ADDS";
617 case ARM64ISD::SUBS: return "ARM64ISD::SUBS";
618 case ARM64ISD::ADCS: return "ARM64ISD::ADCS";
619 case ARM64ISD::SBCS: return "ARM64ISD::SBCS";
620 case ARM64ISD::ANDS: return "ARM64ISD::ANDS";
621 case ARM64ISD::FCMP: return "ARM64ISD::FCMP";
622 case ARM64ISD::FMIN: return "ARM64ISD::FMIN";
623 case ARM64ISD::FMAX: return "ARM64ISD::FMAX";
624 case ARM64ISD::DUP: return "ARM64ISD::DUP";
625 case ARM64ISD::DUPLANE8: return "ARM64ISD::DUPLANE8";
626 case ARM64ISD::DUPLANE16: return "ARM64ISD::DUPLANE16";
627 case ARM64ISD::DUPLANE32: return "ARM64ISD::DUPLANE32";
628 case ARM64ISD::DUPLANE64: return "ARM64ISD::DUPLANE64";
629 case ARM64ISD::MOVI: return "ARM64ISD::MOVI";
630 case ARM64ISD::MOVIshift: return "ARM64ISD::MOVIshift";
631 case ARM64ISD::MOVIedit: return "ARM64ISD::MOVIedit";
632 case ARM64ISD::MOVImsl: return "ARM64ISD::MOVImsl";
633 case ARM64ISD::FMOV: return "ARM64ISD::FMOV";
634 case ARM64ISD::MVNIshift: return "ARM64ISD::MVNIshift";
635 case ARM64ISD::MVNImsl: return "ARM64ISD::MVNImsl";
636 case ARM64ISD::BICi: return "ARM64ISD::BICi";
637 case ARM64ISD::ORRi: return "ARM64ISD::ORRi";
638 case ARM64ISD::NEG: return "ARM64ISD::NEG";
639 case ARM64ISD::EXTR: return "ARM64ISD::EXTR";
640 case ARM64ISD::ZIP1: return "ARM64ISD::ZIP1";
641 case ARM64ISD::ZIP2: return "ARM64ISD::ZIP2";
642 case ARM64ISD::UZP1: return "ARM64ISD::UZP1";
643 case ARM64ISD::UZP2: return "ARM64ISD::UZP2";
644 case ARM64ISD::TRN1: return "ARM64ISD::TRN1";
645 case ARM64ISD::TRN2: return "ARM64ISD::TRN2";
646 case ARM64ISD::REV16: return "ARM64ISD::REV16";
647 case ARM64ISD::REV32: return "ARM64ISD::REV32";
648 case ARM64ISD::REV64: return "ARM64ISD::REV64";
649 case ARM64ISD::EXT: return "ARM64ISD::EXT";
650 case ARM64ISD::VSHL: return "ARM64ISD::VSHL";
651 case ARM64ISD::VLSHR: return "ARM64ISD::VLSHR";
652 case ARM64ISD::VASHR: return "ARM64ISD::VASHR";
653 case ARM64ISD::CMEQ: return "ARM64ISD::CMEQ";
654 case ARM64ISD::CMGE: return "ARM64ISD::CMGE";
655 case ARM64ISD::CMGT: return "ARM64ISD::CMGT";
656 case ARM64ISD::CMHI: return "ARM64ISD::CMHI";
657 case ARM64ISD::CMHS: return "ARM64ISD::CMHS";
658 case ARM64ISD::FCMEQ: return "ARM64ISD::FCMEQ";
659 case ARM64ISD::FCMGE: return "ARM64ISD::FCMGE";
660 case ARM64ISD::FCMGT: return "ARM64ISD::FCMGT";
661 case ARM64ISD::CMEQz: return "ARM64ISD::CMEQz";
662 case ARM64ISD::CMGEz: return "ARM64ISD::CMGEz";
663 case ARM64ISD::CMGTz: return "ARM64ISD::CMGTz";
664 case ARM64ISD::CMLEz: return "ARM64ISD::CMLEz";
665 case ARM64ISD::CMLTz: return "ARM64ISD::CMLTz";
666 case ARM64ISD::FCMEQz: return "ARM64ISD::FCMEQz";
667 case ARM64ISD::FCMGEz: return "ARM64ISD::FCMGEz";
668 case ARM64ISD::FCMGTz: return "ARM64ISD::FCMGTz";
669 case ARM64ISD::FCMLEz: return "ARM64ISD::FCMLEz";
670 case ARM64ISD::FCMLTz: return "ARM64ISD::FCMLTz";
671 case ARM64ISD::NOT: return "ARM64ISD::NOT";
672 case ARM64ISD::BIT: return "ARM64ISD::BIT";
673 case ARM64ISD::CBZ: return "ARM64ISD::CBZ";
674 case ARM64ISD::CBNZ: return "ARM64ISD::CBNZ";
675 case ARM64ISD::TBZ: return "ARM64ISD::TBZ";
676 case ARM64ISD::TBNZ: return "ARM64ISD::TBNZ";
677 case ARM64ISD::TC_RETURN: return "ARM64ISD::TC_RETURN";
678 case ARM64ISD::SITOF: return "ARM64ISD::SITOF";
679 case ARM64ISD::UITOF: return "ARM64ISD::UITOF";
680 case ARM64ISD::SQSHL_I: return "ARM64ISD::SQSHL_I";
681 case ARM64ISD::UQSHL_I: return "ARM64ISD::UQSHL_I";
682 case ARM64ISD::SRSHR_I: return "ARM64ISD::SRSHR_I";
683 case ARM64ISD::URSHR_I: return "ARM64ISD::URSHR_I";
684 case ARM64ISD::SQSHLU_I: return "ARM64ISD::SQSHLU_I";
685 case ARM64ISD::WrapperLarge: return "ARM64ISD::WrapperLarge";
690 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
691 MachineBasicBlock *MBB) const {
692 // We materialise the F128CSEL pseudo-instruction as some control flow and a
696 // [... previous instrs leading to comparison ...]
702 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
704 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
705 MachineFunction *MF = MBB->getParent();
706 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
707 DebugLoc DL = MI->getDebugLoc();
708 MachineFunction::iterator It = MBB;
711 unsigned DestReg = MI->getOperand(0).getReg();
712 unsigned IfTrueReg = MI->getOperand(1).getReg();
713 unsigned IfFalseReg = MI->getOperand(2).getReg();
714 unsigned CondCode = MI->getOperand(3).getImm();
715 bool CPSRKilled = MI->getOperand(4).isKill();
717 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
718 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
719 MF->insert(It, TrueBB);
720 MF->insert(It, EndBB);
722 // Transfer rest of current basic-block to EndBB
723 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
725 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
727 BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
728 BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
729 MBB->addSuccessor(TrueBB);
730 MBB->addSuccessor(EndBB);
732 // TrueBB falls through to the end.
733 TrueBB->addSuccessor(EndBB);
736 TrueBB->addLiveIn(ARM64::CPSR);
737 EndBB->addLiveIn(ARM64::CPSR);
740 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
746 MI->eraseFromParent();
751 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
752 MachineBasicBlock *BB) const {
753 switch (MI->getOpcode()) {
758 assert(0 && "Unexpected instruction for custom inserter!");
761 case ARM64::F128CSEL:
762 return EmitF128CSEL(MI, BB);
764 case TargetOpcode::STACKMAP:
765 case TargetOpcode::PATCHPOINT:
766 return emitPatchPoint(MI, BB);
768 llvm_unreachable("Unexpected instruction for custom inserter!");
771 //===----------------------------------------------------------------------===//
772 // ARM64 Lowering private implementation.
773 //===----------------------------------------------------------------------===//
775 //===----------------------------------------------------------------------===//
777 //===----------------------------------------------------------------------===//
779 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
780 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
783 llvm_unreachable("Unknown condition code!");
807 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
808 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
809 ARM64CC::CondCode &CondCode2) {
810 CondCode2 = ARM64CC::AL;
813 llvm_unreachable("Unknown FP condition!");
816 CondCode = ARM64CC::EQ;
820 CondCode = ARM64CC::GT;
824 CondCode = ARM64CC::GE;
827 CondCode = ARM64CC::MI;
830 CondCode = ARM64CC::LS;
833 CondCode = ARM64CC::MI;
834 CondCode2 = ARM64CC::GT;
837 CondCode = ARM64CC::VC;
840 CondCode = ARM64CC::VS;
843 CondCode = ARM64CC::EQ;
844 CondCode2 = ARM64CC::VS;
847 CondCode = ARM64CC::HI;
850 CondCode = ARM64CC::PL;
854 CondCode = ARM64CC::LT;
858 CondCode = ARM64CC::LE;
862 CondCode = ARM64CC::NE;
867 static bool isLegalArithImmed(uint64_t C) {
868 // Matches ARM64DAGToDAGISel::SelectArithImmed().
869 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
872 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
873 SDLoc dl, SelectionDAG &DAG) {
874 EVT VT = LHS.getValueType();
876 if (VT.isFloatingPoint())
877 return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
879 // The CMP instruction is just an alias for SUBS, and representing it as
880 // SUBS means that it's possible to get CSE with subtract operations.
881 // A later phase can perform the optimization of setting the destination
882 // register to WZR/XZR if it ends up being unused.
884 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on the
885 // grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags can be
886 // set differently by this operation. It comes down to whether "SInt(~op2)+1
887 // == SInt(~op2+1)" (and the same for UInt). If they are then everything is
888 // fine. If not then the optimization is wrong. Thus general comparisons are
889 // only valid if op2 != 0.
891 // So, finally, the only LLVM-native comparisons that don't mention C and V
892 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in the
893 // absence of information about op2.
894 unsigned Opcode = ARM64ISD::SUBS;
895 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
896 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
897 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
898 Opcode = ARM64ISD::ADDS;
899 RHS = RHS.getOperand(1);
902 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
906 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
907 SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
908 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
909 EVT VT = RHS.getValueType();
910 uint64_t C = RHSC->getZExtValue();
911 if (!isLegalArithImmed(C)) {
912 // Constant does not fit, try adjusting it by one?
918 if ((VT == MVT::i32 && C != 0x80000000 &&
919 isLegalArithImmed((uint32_t)(C - 1))) ||
920 (VT == MVT::i64 && C != 0x80000000ULL &&
921 isLegalArithImmed(C - 1ULL))) {
922 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
923 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
924 RHS = DAG.getConstant(C, VT);
929 if ((VT == MVT::i32 && C != 0 &&
930 isLegalArithImmed((uint32_t)(C - 1))) ||
931 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
932 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
933 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
934 RHS = DAG.getConstant(C, VT);
939 if ((VT == MVT::i32 && C != 0x7fffffff &&
940 isLegalArithImmed((uint32_t)(C + 1))) ||
941 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
942 isLegalArithImmed(C + 1ULL))) {
943 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
944 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
945 RHS = DAG.getConstant(C, VT);
950 if ((VT == MVT::i32 && C != 0xffffffff &&
951 isLegalArithImmed((uint32_t)(C + 1))) ||
952 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
953 isLegalArithImmed(C + 1ULL))) {
954 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
955 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
956 RHS = DAG.getConstant(C, VT);
963 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
964 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
965 ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
969 static std::pair<SDValue, SDValue>
970 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
971 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
972 "Unsupported value type");
973 SDValue Value, Overflow;
975 SDValue LHS = Op.getOperand(0);
976 SDValue RHS = Op.getOperand(1);
978 switch (Op.getOpcode()) {
980 llvm_unreachable("Unknown overflow instruction!");
982 Opc = ARM64ISD::ADDS;
986 Opc = ARM64ISD::ADDS;
990 Opc = ARM64ISD::SUBS;
994 Opc = ARM64ISD::SUBS;
997 // Multiply needs a little bit extra work.
1001 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1002 if (Op.getValueType() == MVT::i32) {
1003 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1004 // For a 32 bit multiply with overflow check we want the instruction
1005 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1006 // need to generate the following pattern:
1007 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1008 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1009 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1010 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1011 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1012 DAG.getConstant(0, MVT::i64));
1013 // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1014 // operation. We need to clear out the upper 32 bits, because we used a
1015 // widening multiply that wrote all 64 bits. In the end this should be a
1017 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1019 // The signed overflow check requires more than just a simple check for
1020 // any bit set in the upper 32 bits of the result. These bits could be
1021 // just the sign bits of a negative number. To perform the overflow
1022 // check we have to arithmetic shift right the 32nd bit of the result by
1023 // 31 bits. Then we compare the result to the upper 32 bits.
1024 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1025 DAG.getConstant(32, MVT::i64));
1026 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1027 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1028 DAG.getConstant(31, MVT::i64));
1029 // It is important that LowerBits is last, otherwise the arithmetic
1030 // shift will not be folded into the compare (SUBS).
1031 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1032 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1035 // The overflow check for unsigned multiply is easy. We only need to
1036 // check if any of the upper 32 bits are set. This can be done with a
1037 // CMP (shifted register). For that we need to generate the following
1039 // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1040 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1041 DAG.getConstant(32, MVT::i64));
1042 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1044 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1045 UpperBits).getValue(1);
1049 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1050 // For the 64 bit multiply
1051 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1053 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1054 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1055 DAG.getConstant(63, MVT::i64));
1056 // It is important that LowerBits is last, otherwise the arithmetic
1057 // shift will not be folded into the compare (SUBS).
1058 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1059 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1062 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1063 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1065 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1066 UpperBits).getValue(1);
1073 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1075 // Emit the ARM64 operation with overflow check.
1076 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1077 Overflow = Value.getValue(1);
1079 return std::make_pair(Value, Overflow);
1082 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1083 RTLIB::Libcall Call) const {
1084 SmallVector<SDValue, 2> Ops;
1085 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1086 Ops.push_back(Op.getOperand(i));
1088 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1092 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1093 SDValue Sel = Op.getOperand(0);
1094 SDValue Other = Op.getOperand(1);
1096 // If neither operand is a SELECT_CC, give up.
1097 if (Sel.getOpcode() != ISD::SELECT_CC)
1098 std::swap(Sel, Other);
1099 if (Sel.getOpcode() != ISD::SELECT_CC)
1102 // The folding we want to perform is:
1103 // (xor x, (select_cc a, b, cc, 0, -1) )
1105 // (csel x, (xor x, -1), cc ...)
1107 // The latter will get matched to a CSINV instruction.
1109 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1110 SDValue LHS = Sel.getOperand(0);
1111 SDValue RHS = Sel.getOperand(1);
1112 SDValue TVal = Sel.getOperand(2);
1113 SDValue FVal = Sel.getOperand(3);
1116 // FIXME: This could be generalized to non-integer comparisons.
1117 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1120 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1121 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1123 // The the values aren't constants, this isn't the pattern we're looking for.
1124 if (!CFVal || !CTVal)
1127 // We can commute the SELECT_CC by inverting the condition. This
1128 // might be needed to make this fit into a CSINV pattern.
1129 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1130 std::swap(TVal, FVal);
1131 std::swap(CTVal, CFVal);
1132 CC = ISD::getSetCCInverse(CC, true);
1135 // If the constants line up, perform the transform!
1136 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1138 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1141 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1142 DAG.getConstant(-1ULL, Other.getValueType()));
1144 return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1151 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1152 EVT VT = Op.getValueType();
1154 // Let legalize expand this if it isn't a legal type yet.
1155 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1158 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1161 bool ExtraOp = false;
1162 switch (Op.getOpcode()) {
1164 assert(0 && "Invalid code");
1166 Opc = ARM64ISD::ADDS;
1169 Opc = ARM64ISD::SUBS;
1172 Opc = ARM64ISD::ADCS;
1176 Opc = ARM64ISD::SBCS;
1182 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1183 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1187 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1188 // Let legalize expand this if it isn't a legal type yet.
1189 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1192 ARM64CC::CondCode CC;
1193 // The actual operation that sets the overflow or carry flag.
1194 SDValue Value, Overflow;
1195 std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1197 // We use 0 and 1 as false and true values.
1198 SDValue TVal = DAG.getConstant(1, MVT::i32);
1199 SDValue FVal = DAG.getConstant(0, MVT::i32);
1201 // We use an inverted condition, because the conditional select is inverted
1202 // too. This will allow it to be selected to a single instruction:
1203 // CSINC Wd, WZR, WZR, invert(cond).
1204 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1205 Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1208 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1209 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1212 // Prefetch operands are:
1213 // 1: Address to prefetch
1215 // 3: int locality (0 = no locality ... 3 = extreme locality)
1216 // 4: bool isDataCache
1217 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1219 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1220 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1221 // The data thing is not used.
1222 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1224 bool IsStream = !Locality;
1225 // When the locality number is set
1227 // The front-end should have filtered out the out-of-range values
1228 assert(Locality <= 3 && "Prefetch locality out-of-range");
1229 // The locality degree is the opposite of the cache speed.
1230 // Put the number the other way around.
1231 // The encoding starts at 0 for level 1
1232 Locality = 3 - Locality;
1235 // built the mask value encoding the expected behavior.
1236 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1237 (Locality << 1) | // Cache level bits
1238 (unsigned)IsStream; // Stream bit
1239 return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1240 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1243 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1244 SelectionDAG &DAG) const {
1245 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1248 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1250 return LowerF128Call(Op, DAG, LC);
1253 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1254 SelectionDAG &DAG) const {
1255 if (Op.getOperand(0).getValueType() != MVT::f128) {
1256 // It's legal except when f128 is involved
1261 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1263 // FP_ROUND node has a second operand indicating whether it is known to be
1264 // precise. That doesn't take part in the LibCall so we can't directly use
1266 SDValue SrcVal = Op.getOperand(0);
1267 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1268 /*isSigned*/ false, SDLoc(Op)).first;
1271 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1272 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1273 // Any additional optimization in this function should be recorded
1274 // in the cost tables.
1275 EVT InVT = Op.getOperand(0).getValueType();
1276 EVT VT = Op.getValueType();
1278 // FP_TO_XINT conversion from the same type are legal.
1279 if (VT.getSizeInBits() == InVT.getSizeInBits())
1282 if (InVT == MVT::v2f64) {
1284 SDValue Cv = DAG.getNode(Op.getOpcode(), dl, MVT::v2i64, Op.getOperand(0));
1285 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1288 // Type changing conversions are illegal.
1292 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1293 SelectionDAG &DAG) const {
1294 if (Op.getOperand(0).getValueType().isVector())
1295 return LowerVectorFP_TO_INT(Op, DAG);
1297 if (Op.getOperand(0).getValueType() != MVT::f128) {
1298 // It's legal except when f128 is involved
1303 if (Op.getOpcode() == ISD::FP_TO_SINT)
1304 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1306 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1308 SmallVector<SDValue, 2> Ops;
1309 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1310 Ops.push_back(Op.getOperand(i));
1312 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1316 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1317 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1318 // Any additional optimization in this function should be recorded
1319 // in the cost tables.
1320 EVT VT = Op.getValueType();
1322 SDValue In = Op.getOperand(0);
1323 EVT InVT = In.getValueType();
1325 // v2i32 to v2f32 is legal.
1326 if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1329 // This function only handles v2f64 outputs.
1330 if (VT == MVT::v2f64) {
1331 // Extend the input argument to a v2i64 that we can feed into the
1332 // floating point conversion. Zero or sign extend based on whether
1333 // we're doing a signed or unsigned float conversion.
1335 Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1336 assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1337 SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1338 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1341 // Scalarize v2i64 to v2f32 conversions.
1342 std::vector<SDValue> BuildVectorOps;
1343 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1344 SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1345 DAG.getConstant(i, MVT::i64));
1346 Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1347 BuildVectorOps.push_back(Sclr);
1350 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &BuildVectorOps[0],
1351 BuildVectorOps.size());
1354 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1355 SelectionDAG &DAG) const {
1356 if (Op.getValueType().isVector())
1357 return LowerVectorINT_TO_FP(Op, DAG);
1359 // i128 conversions are libcalls.
1360 if (Op.getOperand(0).getValueType() == MVT::i128)
1363 // Other conversions are legal, unless it's to the completely software-based
1365 if (Op.getValueType() != MVT::f128)
1369 if (Op.getOpcode() == ISD::SINT_TO_FP)
1370 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1372 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1374 return LowerF128Call(Op, DAG, LC);
1377 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1378 // For iOS, we want to call an alternative entry point: __sincos_stret,
1379 // which returns the values in two S / D registers.
1381 SDValue Arg = Op.getOperand(0);
1382 EVT ArgVT = Arg.getValueType();
1383 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1390 Entry.isSExt = false;
1391 Entry.isZExt = false;
1392 Args.push_back(Entry);
1394 const char *LibcallName =
1395 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1396 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1398 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1399 TargetLowering::CallLoweringInfo CLI(
1400 DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1401 CallingConv::Fast, /*isTaillCall=*/false,
1402 /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1403 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1404 return CallResult.first;
1407 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1408 SelectionDAG &DAG) const {
1409 switch (Op.getOpcode()) {
1411 llvm_unreachable("unimplemented operand");
1413 case ISD::GlobalAddress:
1414 return LowerGlobalAddress(Op, DAG);
1415 case ISD::GlobalTLSAddress:
1416 return LowerGlobalTLSAddress(Op, DAG);
1418 return LowerSETCC(Op, DAG);
1420 return LowerBR_CC(Op, DAG);
1422 return LowerSELECT(Op, DAG);
1423 case ISD::SELECT_CC:
1424 return LowerSELECT_CC(Op, DAG);
1425 case ISD::JumpTable:
1426 return LowerJumpTable(Op, DAG);
1427 case ISD::ConstantPool:
1428 return LowerConstantPool(Op, DAG);
1429 case ISD::BlockAddress:
1430 return LowerBlockAddress(Op, DAG);
1432 return LowerVASTART(Op, DAG);
1434 return LowerVACOPY(Op, DAG);
1436 return LowerVAARG(Op, DAG);
1441 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1448 return LowerXALUO(Op, DAG);
1450 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1452 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1454 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1456 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1458 return LowerFP_ROUND(Op, DAG);
1459 case ISD::FP_EXTEND:
1460 return LowerFP_EXTEND(Op, DAG);
1461 case ISD::FRAMEADDR:
1462 return LowerFRAMEADDR(Op, DAG);
1463 case ISD::RETURNADDR:
1464 return LowerRETURNADDR(Op, DAG);
1465 case ISD::INSERT_VECTOR_ELT:
1466 return LowerINSERT_VECTOR_ELT(Op, DAG);
1467 case ISD::EXTRACT_VECTOR_ELT:
1468 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1469 case ISD::BUILD_VECTOR:
1470 return LowerBUILD_VECTOR(Op, DAG);
1471 case ISD::VECTOR_SHUFFLE:
1472 return LowerVECTOR_SHUFFLE(Op, DAG);
1473 case ISD::EXTRACT_SUBVECTOR:
1474 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1478 return LowerVectorSRA_SRL_SHL(Op, DAG);
1479 case ISD::SHL_PARTS:
1480 return LowerShiftLeftParts(Op, DAG);
1481 case ISD::SRL_PARTS:
1482 case ISD::SRA_PARTS:
1483 return LowerShiftRightParts(Op, DAG);
1485 return LowerCTPOP(Op, DAG);
1486 case ISD::FCOPYSIGN:
1487 return LowerFCOPYSIGN(Op, DAG);
1489 return LowerVectorAND(Op, DAG);
1491 return LowerVectorOR(Op, DAG);
1493 return LowerXOR(Op, DAG);
1495 return LowerPREFETCH(Op, DAG);
1496 case ISD::SINT_TO_FP:
1497 case ISD::UINT_TO_FP:
1498 return LowerINT_TO_FP(Op, DAG);
1499 case ISD::FP_TO_SINT:
1500 case ISD::FP_TO_UINT:
1501 return LowerFP_TO_INT(Op, DAG);
1503 return LowerFSINCOS(Op, DAG);
1507 /// getFunctionAlignment - Return the Log2 alignment of this function.
1508 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
1512 //===----------------------------------------------------------------------===//
1513 // Calling Convention Implementation
1514 //===----------------------------------------------------------------------===//
1516 #include "ARM64GenCallingConv.inc"
1518 /// Selects the correct CCAssignFn for a the given CallingConvention
1520 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1521 bool IsVarArg) const {
1524 llvm_unreachable("Unsupported calling convention.");
1525 case CallingConv::WebKit_JS:
1526 return CC_ARM64_WebKit_JS;
1527 case CallingConv::C:
1528 case CallingConv::Fast:
1529 if (!Subtarget->isTargetDarwin())
1530 return CC_ARM64_AAPCS;
1531 return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
1535 SDValue ARM64TargetLowering::LowerFormalArguments(
1536 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1537 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1538 SmallVectorImpl<SDValue> &InVals) const {
1539 MachineFunction &MF = DAG.getMachineFunction();
1540 MachineFrameInfo *MFI = MF.getFrameInfo();
1542 // Assign locations to all of the incoming arguments.
1543 SmallVector<CCValAssign, 16> ArgLocs;
1544 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1545 getTargetMachine(), ArgLocs, *DAG.getContext());
1547 // At this point, Ins[].VT may already be promoted to i32. To correctly
1548 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1549 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1550 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1551 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1553 unsigned NumArgs = Ins.size();
1554 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1555 unsigned CurArgIdx = 0;
1556 for (unsigned i = 0; i != NumArgs; ++i) {
1557 MVT ValVT = Ins[i].VT;
1558 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1559 CurArgIdx = Ins[i].OrigArgIndex;
1561 // Get type of the original argument.
1562 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1563 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1564 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1566 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1568 else if (ActualMVT == MVT::i16)
1571 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1573 AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1574 assert(!Res && "Call operand has unhandled type");
1578 SmallVector<SDValue, 16> ArgValues;
1579 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1580 CCValAssign &VA = ArgLocs[i];
1582 // Arguments stored in registers.
1583 if (VA.isRegLoc()) {
1584 EVT RegVT = VA.getLocVT();
1587 const TargetRegisterClass *RC;
1589 if (RegVT == MVT::i32)
1590 RC = &ARM64::GPR32RegClass;
1591 else if (RegVT == MVT::i64)
1592 RC = &ARM64::GPR64RegClass;
1593 else if (RegVT == MVT::f32)
1594 RC = &ARM64::FPR32RegClass;
1595 else if (RegVT == MVT::f64 || RegVT == MVT::v1i64 ||
1596 RegVT == MVT::v1f64 || RegVT == MVT::v2i32 ||
1597 RegVT == MVT::v4i16 || RegVT == MVT::v8i8)
1598 RC = &ARM64::FPR64RegClass;
1599 else if (RegVT == MVT::v2i64 || RegVT == MVT::v4i32 ||
1600 RegVT == MVT::v8i16 || RegVT == MVT::v16i8)
1601 RC = &ARM64::FPR128RegClass;
1603 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1605 // Transform the arguments in physical registers into virtual ones.
1606 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1607 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1609 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1610 // to 64 bits. Insert an assert[sz]ext to capture this, then
1611 // truncate to the right size.
1612 switch (VA.getLocInfo()) {
1614 llvm_unreachable("Unknown loc info!");
1615 case CCValAssign::Full:
1617 case CCValAssign::BCvt:
1618 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1620 case CCValAssign::SExt:
1621 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
1622 DAG.getValueType(VA.getValVT()));
1623 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1625 case CCValAssign::ZExt:
1626 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
1627 DAG.getValueType(VA.getValVT()));
1628 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1632 InVals.push_back(ArgValue);
1634 } else { // VA.isRegLoc()
1635 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1636 unsigned ArgOffset = VA.getLocMemOffset();
1637 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1638 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
1640 // Create load nodes to retrieve arguments from the stack.
1641 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1642 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
1643 MachinePointerInfo::getFixedStack(FI), false,
1650 if (!Subtarget->isTargetDarwin()) {
1651 // The AAPCS variadic function ABI is identical to the non-variadic
1652 // one. As a result there may be more arguments in registers and we should
1653 // save them for future reference.
1654 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1657 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
1658 // This will point to the next argument passed via stack.
1659 unsigned StackOffset = CCInfo.getNextStackOffset();
1660 // We currently pass all varargs at 8-byte alignment.
1661 StackOffset = ((StackOffset + 7) & ~7);
1662 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1668 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1669 SelectionDAG &DAG, SDLoc DL,
1670 SDValue &Chain) const {
1671 MachineFunction &MF = DAG.getMachineFunction();
1672 MachineFrameInfo *MFI = MF.getFrameInfo();
1673 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
1675 SmallVector<SDValue, 8> MemOps;
1677 static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
1678 ARM64::X3, ARM64::X4, ARM64::X5,
1679 ARM64::X6, ARM64::X7 };
1680 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1681 unsigned FirstVariadicGPR =
1682 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1684 static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
1685 ARM64::Q3, ARM64::Q4, ARM64::Q5,
1686 ARM64::Q6, ARM64::Q7 };
1687 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1688 unsigned FirstVariadicFPR =
1689 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1691 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1693 if (GPRSaveSize != 0) {
1694 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1696 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1698 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1699 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
1700 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1702 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1703 MachinePointerInfo::getStack(i * 8), false, false, 0);
1704 MemOps.push_back(Store);
1705 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1706 DAG.getConstant(8, getPointerTy()));
1710 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1712 if (FPRSaveSize != 0) {
1713 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1715 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1717 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1718 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
1719 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
1721 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1722 MachinePointerInfo::getStack(i * 16), false, false, 0);
1723 MemOps.push_back(Store);
1724 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1725 DAG.getConstant(16, getPointerTy()));
1729 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1730 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1731 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1732 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1734 if (!MemOps.empty()) {
1735 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
1740 /// LowerCallResult - Lower the result values of a call into the
1741 /// appropriate copies out of appropriate physical registers.
1742 SDValue ARM64TargetLowering::LowerCallResult(
1743 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1744 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1745 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1746 SDValue ThisVal) const {
1747 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1748 : RetCC_ARM64_AAPCS;
1749 // Assign locations to each value returned by this call.
1750 SmallVector<CCValAssign, 16> RVLocs;
1751 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1752 getTargetMachine(), RVLocs, *DAG.getContext());
1753 CCInfo.AnalyzeCallResult(Ins, RetCC);
1755 // Copy all of the result registers out of their specified physreg.
1756 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1757 CCValAssign VA = RVLocs[i];
1759 // Pass 'this' value directly from the argument to return value, to avoid
1760 // reg unit interference
1761 if (i == 0 && isThisReturn) {
1762 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1763 "unexpected return calling convention register assignment");
1764 InVals.push_back(ThisVal);
1769 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1770 Chain = Val.getValue(1);
1771 InFlag = Val.getValue(2);
1773 switch (VA.getLocInfo()) {
1775 llvm_unreachable("Unknown loc info!");
1776 case CCValAssign::Full:
1778 case CCValAssign::BCvt:
1779 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1783 InVals.push_back(Val);
1789 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
1790 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1791 bool isCalleeStructRet, bool isCallerStructRet,
1792 const SmallVectorImpl<ISD::OutputArg> &Outs,
1793 const SmallVectorImpl<SDValue> &OutVals,
1794 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1795 // Look for obvious safe cases to perform tail call optimization that do not
1796 // require ABI changes. This is what gcc calls sibcall.
1798 // Do not sibcall optimize vararg calls unless the call site is not passing
1800 if (isVarArg && !Outs.empty())
1803 // Also avoid sibcall optimization if either caller or callee uses struct
1804 // return semantics.
1805 if (isCalleeStructRet || isCallerStructRet)
1808 // Note that currently ARM64 "C" calling convention and "Fast" calling
1809 // convention are compatible. If/when that ever changes, we'll need to
1810 // add checks here to make sure any interactions are OK.
1812 // If the callee takes no arguments then go on to check the results of the
1814 if (!Outs.empty()) {
1815 // Check if stack adjustment is needed. For now, do not do this if any
1816 // argument is passed on the stack.
1817 SmallVector<CCValAssign, 16> ArgLocs;
1818 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1819 getTargetMachine(), ArgLocs, *DAG.getContext());
1820 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
1821 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
1822 if (CCInfo.getNextStackOffset()) {
1823 // Check if the arguments are already laid out in the right way as
1824 // the caller's fixed stack objects.
1825 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1826 ++i, ++realArgIdx) {
1827 CCValAssign &VA = ArgLocs[i];
1828 if (VA.getLocInfo() == CCValAssign::Indirect)
1830 if (VA.needsCustom()) {
1831 // Just don't handle anything that needs custom adjustments for now.
1832 // If need be, we can revisit later, but we shouldn't ever end up
1835 } else if (!VA.isRegLoc()) {
1836 // Likewise, don't try to handle stack based arguments for the
1846 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
1847 /// and add input and output parameter nodes.
1848 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1849 SmallVectorImpl<SDValue> &InVals) const {
1850 SelectionDAG &DAG = CLI.DAG;
1852 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1853 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1854 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1855 SDValue Chain = CLI.Chain;
1856 SDValue Callee = CLI.Callee;
1857 bool &IsTailCall = CLI.IsTailCall;
1858 CallingConv::ID CallConv = CLI.CallConv;
1859 bool IsVarArg = CLI.IsVarArg;
1861 MachineFunction &MF = DAG.getMachineFunction();
1862 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1863 bool IsThisReturn = false;
1865 // If tail calls are explicitly disabled, make sure not to use them.
1866 if (!EnableARM64TailCalls)
1870 // Check if it's really possible to do a tail call.
1871 IsTailCall = isEligibleForTailCallOptimization(
1872 Callee, CallConv, IsVarArg, IsStructRet,
1873 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
1874 // We don't support GuaranteedTailCallOpt, only automatically
1875 // detected sibcalls.
1876 // FIXME: Re-evaluate. Is this true? Should it be true?
1881 // Analyze operands of the call, assigning locations to each operand.
1882 SmallVector<CCValAssign, 16> ArgLocs;
1883 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1884 getTargetMachine(), ArgLocs, *DAG.getContext());
1887 // Handle fixed and variable vector arguments differently.
1888 // Variable vector arguments always go into memory.
1889 unsigned NumArgs = Outs.size();
1891 for (unsigned i = 0; i != NumArgs; ++i) {
1892 MVT ArgVT = Outs[i].VT;
1893 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1894 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
1895 /*IsVarArg=*/ !Outs[i].IsFixed);
1896 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1897 assert(!Res && "Call operand has unhandled type");
1901 // At this point, Outs[].VT may already be promoted to i32. To correctly
1902 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1903 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1904 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
1905 // we use a special version of AnalyzeCallOperands to pass in ValVT and
1907 unsigned NumArgs = Outs.size();
1908 for (unsigned i = 0; i != NumArgs; ++i) {
1909 MVT ValVT = Outs[i].VT;
1910 // Get type of the original argument.
1911 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
1912 /*AllowUnknown*/ true);
1913 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
1914 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1915 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1917 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1919 else if (ActualMVT == MVT::i16)
1922 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1923 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
1924 assert(!Res && "Call operand has unhandled type");
1929 // Get a count of how many bytes are to be pushed on the stack.
1930 unsigned NumBytes = CCInfo.getNextStackOffset();
1932 // Adjust the stack pointer for the new arguments...
1933 // These operations are automatically eliminated by the prolog/epilog pass
1936 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
1938 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
1940 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1941 SmallVector<SDValue, 8> MemOpChains;
1943 // Walk the register/memloc assignments, inserting copies/loads.
1944 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1945 ++i, ++realArgIdx) {
1946 CCValAssign &VA = ArgLocs[i];
1947 SDValue Arg = OutVals[realArgIdx];
1948 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1950 // Promote the value if needed.
1951 switch (VA.getLocInfo()) {
1953 llvm_unreachable("Unknown loc info!");
1954 case CCValAssign::Full:
1956 case CCValAssign::SExt:
1957 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1959 case CCValAssign::ZExt:
1960 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1962 case CCValAssign::AExt:
1963 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1965 case CCValAssign::BCvt:
1966 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1968 case CCValAssign::FPExt:
1969 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
1973 if (VA.isRegLoc()) {
1974 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
1975 assert(VA.getLocVT() == MVT::i64 &&
1976 "unexpected calling convention register assignment");
1977 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
1978 "unexpected use of 'returned'");
1979 IsThisReturn = true;
1981 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1983 assert(VA.isMemLoc());
1984 // There's no reason we can't support stack args w/ tailcall, but
1985 // we currently don't, so assert if we see one.
1986 assert(!IsTailCall && "stack argument with tail call!?");
1987 unsigned LocMemOffset = VA.getLocMemOffset();
1988 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1989 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
1991 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
1992 // promoted to a legal register type i32, we should truncate Arg back to
1994 if (Arg.getValueType().isSimple() &&
1995 Arg.getValueType().getSimpleVT() == MVT::i32 &&
1996 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
1997 VA.getLocVT() == MVT::i16))
1998 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2000 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2001 MachinePointerInfo::getStack(LocMemOffset),
2003 MemOpChains.push_back(Store);
2007 if (!MemOpChains.empty())
2008 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOpChains[0],
2009 MemOpChains.size());
2011 // Build a sequence of copy-to-reg nodes chained together with token chain
2012 // and flag operands which copy the outgoing args into the appropriate regs.
2014 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2015 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2016 RegsToPass[i].second, InFlag);
2017 InFlag = Chain.getValue(1);
2020 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2021 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2022 // node so that legalize doesn't hack it.
2023 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2024 Subtarget->isTargetMachO()) {
2025 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2026 const GlobalValue *GV = G->getGlobal();
2027 bool InternalLinkage = GV->hasInternalLinkage();
2028 if (InternalLinkage)
2029 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2031 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2033 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2035 } else if (ExternalSymbolSDNode *S =
2036 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2037 const char *Sym = S->getSymbol();
2039 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2040 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2042 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2043 const GlobalValue *GV = G->getGlobal();
2044 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2045 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2046 const char *Sym = S->getSymbol();
2047 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2050 std::vector<SDValue> Ops;
2051 Ops.push_back(Chain);
2052 Ops.push_back(Callee);
2054 // Add argument registers to the end of the list so that they are known live
2056 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2057 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2058 RegsToPass[i].second.getValueType()));
2060 // Add a register mask operand representing the call-preserved registers.
2061 const uint32_t *Mask;
2062 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2063 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2065 // For 'this' returns, use the X0-preserving mask if applicable
2066 Mask = ARI->getThisReturnPreservedMask(CallConv);
2068 IsThisReturn = false;
2069 Mask = ARI->getCallPreservedMask(CallConv);
2072 Mask = ARI->getCallPreservedMask(CallConv);
2074 assert(Mask && "Missing call preserved mask for calling convention");
2075 Ops.push_back(DAG.getRegisterMask(Mask));
2077 if (InFlag.getNode())
2078 Ops.push_back(InFlag);
2080 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2082 // If we're doing a tall call, use a TC_RETURN here rather than an
2083 // actual call instruction.
2085 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, &Ops[0], Ops.size());
2087 // Returns a chain and a flag for retval copy to use.
2088 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
2089 InFlag = Chain.getValue(1);
2091 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2092 DAG.getIntPtrConstant(0, true), InFlag, DL);
2094 InFlag = Chain.getValue(1);
2096 // Handle result values, copying them out of physregs into vregs that we
2098 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2099 InVals, IsThisReturn,
2100 IsThisReturn ? OutVals[0] : SDValue());
2103 bool ARM64TargetLowering::CanLowerReturn(
2104 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2105 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2106 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2107 : RetCC_ARM64_AAPCS;
2108 SmallVector<CCValAssign, 16> RVLocs;
2109 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2110 return CCInfo.CheckReturn(Outs, RetCC);
2114 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2116 const SmallVectorImpl<ISD::OutputArg> &Outs,
2117 const SmallVectorImpl<SDValue> &OutVals,
2118 SDLoc DL, SelectionDAG &DAG) const {
2119 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2120 : RetCC_ARM64_AAPCS;
2121 SmallVector<CCValAssign, 16> RVLocs;
2122 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2123 getTargetMachine(), RVLocs, *DAG.getContext());
2124 CCInfo.AnalyzeReturn(Outs, RetCC);
2126 // Copy the result values into the output registers.
2128 SmallVector<SDValue, 4> RetOps(1, Chain);
2129 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2130 ++i, ++realRVLocIdx) {
2131 CCValAssign &VA = RVLocs[i];
2132 assert(VA.isRegLoc() && "Can only return in registers!");
2133 SDValue Arg = OutVals[realRVLocIdx];
2135 switch (VA.getLocInfo()) {
2137 llvm_unreachable("Unknown loc info!");
2138 case CCValAssign::Full:
2140 case CCValAssign::BCvt:
2141 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2145 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2146 Flag = Chain.getValue(1);
2147 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2150 RetOps[0] = Chain; // Update chain.
2152 // Add the flag if we have it.
2154 RetOps.push_back(Flag);
2156 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, &RetOps[0],
2160 //===----------------------------------------------------------------------===//
2161 // Other Lowering Code
2162 //===----------------------------------------------------------------------===//
2164 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2165 SelectionDAG &DAG) const {
2166 EVT PtrVT = getPointerTy();
2168 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2169 unsigned char OpFlags =
2170 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2172 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2173 "unexpected offset in global node");
2175 // This also catched the large code model case for Darwin.
2176 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2177 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2178 // FIXME: Once remat is capable of dealing with instructions with register
2179 // operands, expand this into two nodes instead of using a wrapper node.
2180 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2183 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2184 const unsigned char MO_NC = ARM64II::MO_NC;
2186 ARM64ISD::WrapperLarge, DL, PtrVT,
2187 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2188 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2189 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2190 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2192 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2193 // the only correct model on Darwin.
2194 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2195 OpFlags | ARM64II::MO_PAGE);
2196 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2197 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2199 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2200 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2204 /// \brief Convert a TLS address reference into the correct sequence of loads
2205 /// and calls to compute the variable's address (for Darwin, currently) and
2206 /// return an SDValue containing the final node.
2208 /// Darwin only has one TLS scheme which must be capable of dealing with the
2209 /// fully general situation, in the worst case. This means:
2210 /// + "extern __thread" declaration.
2211 /// + Defined in a possibly unknown dynamic library.
2213 /// The general system is that each __thread variable has a [3 x i64] descriptor
2214 /// which contains information used by the runtime to calculate the address. The
2215 /// only part of this the compiler needs to know about is the first xword, which
2216 /// contains a function pointer that must be called with the address of the
2217 /// entire descriptor in "x0".
2219 /// Since this descriptor may be in a different unit, in general even the
2220 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2222 /// adrp x0, _var@TLVPPAGE
2223 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2224 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2225 /// ; the function pointer
2226 /// blr x1 ; Uses descriptor address in x0
2227 /// ; Address of _var is now in x0.
2229 /// If the address of _var's descriptor *is* known to the linker, then it can
2230 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2231 /// a slight efficiency gain.
2233 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2234 SelectionDAG &DAG) const {
2235 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2238 MVT PtrVT = getPointerTy();
2239 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2242 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2243 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2245 // The first entry in the descriptor is a function pointer that we must call
2246 // to obtain the address of the variable.
2247 SDValue Chain = DAG.getEntryNode();
2248 SDValue FuncTLVGet =
2249 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2250 false, true, true, 8);
2251 Chain = FuncTLVGet.getValue(1);
2253 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2254 MFI->setAdjustsStack(true);
2256 // TLS calls preserve all registers except those that absolutely must be
2257 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2259 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2260 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2261 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2263 // Finally, we can make the call. This is just a degenerate version of a
2264 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2265 // the address of the variable in this thread.
2266 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2267 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2268 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2269 DAG.getRegisterMask(Mask), Chain.getValue(1));
2270 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2273 /// When accessing thread-local variables under either the general-dynamic or
2274 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2275 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2276 /// is a function pointer to carry out the resolution. This function takes the
2277 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2278 /// other registers (except LR, CPSR) are preserved.
2280 /// Thus, the ideal call sequence on AArch64 is:
2282 /// adrp x0, :tlsdesc:thread_var
2283 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2284 /// add x0, x0, :tlsdesc_lo12:thread_var
2285 /// .tlsdesccall thread_var
2287 /// (TPIDR_EL0 offset now in x0).
2289 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2290 /// relocation to help the linker relax this sequence if it turns out to be too
2293 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2295 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2296 SDValue DescAddr, SDLoc DL,
2297 SelectionDAG &DAG) const {
2298 EVT PtrVT = getPointerTy();
2300 // The function we need to call is simply the first entry in the GOT for this
2301 // descriptor, load it in preparation.
2302 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2304 // TLS calls preserve all registers except those that absolutely must be
2305 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2307 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2308 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2309 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2311 // The function takes only one argument: the address of the descriptor itself
2313 SDValue Glue, Chain;
2314 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2315 Glue = Chain.getValue(1);
2317 // We're now ready to populate the argument list, as with a normal call:
2318 SmallVector<SDValue, 6> Ops;
2319 Ops.push_back(Chain);
2320 Ops.push_back(Func);
2321 Ops.push_back(SymAddr);
2322 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2323 Ops.push_back(DAG.getRegisterMask(Mask));
2324 Ops.push_back(Glue);
2326 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2327 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, &Ops[0], Ops.size());
2328 Glue = Chain.getValue(1);
2330 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2333 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2334 SelectionDAG &DAG) const {
2335 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2336 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2337 "ELF TLS only supported in small memory model");
2338 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2340 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2343 EVT PtrVT = getPointerTy();
2345 const GlobalValue *GV = GA->getGlobal();
2347 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2349 if (Model == TLSModel::LocalExec) {
2350 SDValue HiVar = DAG.getTargetGlobalAddress(
2351 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2352 SDValue LoVar = DAG.getTargetGlobalAddress(
2353 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2355 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2356 DAG.getTargetConstant(16, MVT::i32)),
2358 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2359 DAG.getTargetConstant(0, MVT::i32)),
2361 } else if (Model == TLSModel::InitialExec) {
2362 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2363 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2364 } else if (Model == TLSModel::LocalDynamic) {
2365 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2366 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2367 // the beginning of the module's TLS region, followed by a DTPREL offset
2370 // These accesses will need deduplicating if there's more than one.
2371 ARM64FunctionInfo *MFI =
2372 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2373 MFI->incNumLocalDynamicTLSAccesses();
2375 // Accesses used in this sequence go via the TLS descriptor which lives in
2376 // the GOT. Prepare an address we can use to handle this.
2377 SDValue HiDesc = DAG.getTargetExternalSymbol(
2378 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2379 SDValue LoDesc = DAG.getTargetExternalSymbol(
2380 "_TLS_MODULE_BASE_", PtrVT,
2381 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2383 // First argument to the descriptor call is the address of the descriptor
2385 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2386 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2388 // The call needs a relocation too for linker relaxation. It doesn't make
2389 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2391 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2394 // Now we can calculate the offset from TPIDR_EL0 to this module's
2395 // thread-local area.
2396 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2398 // Now use :dtprel_whatever: operations to calculate this variable's offset
2399 // in its thread-storage area.
2400 SDValue HiVar = DAG.getTargetGlobalAddress(
2401 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2402 SDValue LoVar = DAG.getTargetGlobalAddress(
2403 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2406 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2407 DAG.getTargetConstant(16, MVT::i32)),
2409 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2410 DAG.getTargetConstant(0, MVT::i32)),
2413 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2414 } else if (Model == TLSModel::GeneralDynamic) {
2415 // Accesses used in this sequence go via the TLS descriptor which lives in
2416 // the GOT. Prepare an address we can use to handle this.
2417 SDValue HiDesc = DAG.getTargetGlobalAddress(
2418 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2419 SDValue LoDesc = DAG.getTargetGlobalAddress(
2421 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2423 // First argument to the descriptor call is the address of the descriptor
2425 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2426 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2428 // The call needs a relocation too for linker relaxation. It doesn't make
2429 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2432 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2434 // Finally we can make a call to calculate the offset from tpidr_el0.
2435 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2437 llvm_unreachable("Unsupported ELF TLS access model");
2439 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2442 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2443 SelectionDAG &DAG) const {
2444 if (Subtarget->isTargetDarwin())
2445 return LowerDarwinGlobalTLSAddress(Op, DAG);
2446 else if (Subtarget->isTargetELF())
2447 return LowerELFGlobalTLSAddress(Op, DAG);
2449 llvm_unreachable("Unexpected platform trying to use TLS");
2451 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2452 SDValue Chain = Op.getOperand(0);
2453 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2454 SDValue LHS = Op.getOperand(2);
2455 SDValue RHS = Op.getOperand(3);
2456 SDValue Dest = Op.getOperand(4);
2459 // Handle f128 first, since lowering it will result in comparing the return
2460 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2461 // is expecting to deal with.
2462 if (LHS.getValueType() == MVT::f128) {
2463 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2465 // If softenSetCCOperands returned a scalar, we need to compare the result
2466 // against zero to select between true and false values.
2467 if (RHS.getNode() == 0) {
2468 RHS = DAG.getConstant(0, LHS.getValueType());
2473 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2475 unsigned Opc = LHS.getOpcode();
2476 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2477 cast<ConstantSDNode>(RHS)->isOne() &&
2478 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2479 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2480 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2481 "Unexpected condition code.");
2482 // Only lower legal XALUO ops.
2483 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2486 // The actual operation with overflow check.
2487 ARM64CC::CondCode OFCC;
2488 SDValue Value, Overflow;
2489 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2491 if (CC == ISD::SETNE)
2492 OFCC = getInvertedCondCode(OFCC);
2493 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2495 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2499 if (LHS.getValueType().isInteger()) {
2500 assert((LHS.getValueType() == RHS.getValueType()) &&
2501 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2503 // If the RHS of the comparison is zero, we can potentially fold this
2504 // to a specialized branch.
2505 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2506 if (RHSC && RHSC->getZExtValue() == 0) {
2507 if (CC == ISD::SETEQ) {
2508 // See if we can use a TBZ to fold in an AND as well.
2509 // TBZ has a smaller branch displacement than CBZ. If the offset is
2510 // out of bounds, a late MI-layer pass rewrites branches.
2511 // 403.gcc is an example that hits this case.
2512 if (LHS.getOpcode() == ISD::AND &&
2513 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2514 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2515 SDValue Test = LHS.getOperand(0);
2516 uint64_t Mask = LHS.getConstantOperandVal(1);
2518 // TBZ only operates on i64's, but the ext should be free.
2519 if (Test.getValueType() == MVT::i32)
2520 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2522 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
2523 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2526 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2527 } else if (CC == ISD::SETNE) {
2528 // See if we can use a TBZ to fold in an AND as well.
2529 // TBZ has a smaller branch displacement than CBZ. If the offset is
2530 // out of bounds, a late MI-layer pass rewrites branches.
2531 // 403.gcc is an example that hits this case.
2532 if (LHS.getOpcode() == ISD::AND &&
2533 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2534 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2535 SDValue Test = LHS.getOperand(0);
2536 uint64_t Mask = LHS.getConstantOperandVal(1);
2538 // TBNZ only operates on i64's, but the ext should be free.
2539 if (Test.getValueType() == MVT::i32)
2540 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2542 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2543 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2546 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2551 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2552 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2556 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2558 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2559 // clean. Some of them require two branches to implement.
2560 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2561 ARM64CC::CondCode CC1, CC2;
2562 changeFPCCToARM64CC(CC, CC1, CC2);
2563 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2565 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2566 if (CC2 != ARM64CC::AL) {
2567 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2568 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2575 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2576 SelectionDAG &DAG) const {
2577 EVT VT = Op.getValueType();
2580 SDValue In1 = Op.getOperand(0);
2581 SDValue In2 = Op.getOperand(1);
2582 EVT SrcVT = In2.getValueType();
2584 if (SrcVT == MVT::f32 && VT == MVT::f64)
2585 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2586 else if (SrcVT == MVT::f64 && VT == MVT::f32)
2587 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
2589 // FIXME: Src type is different, bail out for now. Can VT really be a
2596 SDValue EltMask, VecVal1, VecVal2;
2597 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
2600 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
2602 if (!VT.isVector()) {
2603 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2604 DAG.getUNDEF(VecVT), In1);
2605 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2606 DAG.getUNDEF(VecVT), In2);
2608 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2609 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2611 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
2615 // We want to materialize a mask with the the high bit set, but the AdvSIMD
2616 // immediate moves cannot materialize that in a single instruction for
2617 // 64-bit elements. Instead, materialize zero and then negate it.
2618 EltMask = DAG.getConstant(0, EltVT);
2620 if (!VT.isVector()) {
2621 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2622 DAG.getUNDEF(VecVT), In1);
2623 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2624 DAG.getUNDEF(VecVT), In2);
2626 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2627 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2630 llvm_unreachable("Invalid type for copysign!");
2633 std::vector<SDValue> BuildVectorOps;
2634 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
2635 BuildVectorOps.push_back(EltMask);
2637 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT,
2638 &BuildVectorOps[0], BuildVectorOps.size());
2640 // If we couldn't materialize the mask above, then the mask vector will be
2641 // the zero vector, and we need to negate it here.
2642 if (VT == MVT::f64 || VT == MVT::v2f64) {
2643 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
2644 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
2645 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
2649 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
2652 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
2653 else if (VT == MVT::f64)
2654 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
2656 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
2659 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
2660 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
2661 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
2664 // While there is no integer popcount instruction, it can
2665 // be more efficiently lowered to the following sequence that uses
2666 // AdvSIMD registers/instructions as long as the copies to/from
2667 // the AdvSIMD registers are cheap.
2668 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
2669 // CNT V0.8B, V0.8B // 8xbyte pop-counts
2670 // ADDV B0, V0.8B // sum 8xbyte pop-counts
2671 // UMOV X0, V0.B[0] // copy byte result back to integer reg
2672 SDValue Val = Op.getOperand(0);
2674 EVT VT = Op.getValueType();
2675 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
2678 if (VT == MVT::i32) {
2679 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
2681 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
2683 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
2686 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
2687 SDValue UaddLV = DAG.getNode(
2688 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2689 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
2692 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
2696 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2698 if (Op.getValueType().isVector())
2699 return LowerVSETCC(Op, DAG);
2701 SDValue LHS = Op.getOperand(0);
2702 SDValue RHS = Op.getOperand(1);
2703 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2706 // We chose ZeroOrOneBooleanContents, so use zero and one.
2707 EVT VT = Op.getValueType();
2708 SDValue TVal = DAG.getConstant(1, VT);
2709 SDValue FVal = DAG.getConstant(0, VT);
2711 // Handle f128 first, since one possible outcome is a normal integer
2712 // comparison which gets picked up by the next if statement.
2713 if (LHS.getValueType() == MVT::f128) {
2714 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2716 // If softenSetCCOperands returned a scalar, use it.
2717 if (RHS.getNode() == 0) {
2718 assert(LHS.getValueType() == Op.getValueType() &&
2719 "Unexpected setcc expansion!");
2724 if (LHS.getValueType().isInteger()) {
2727 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
2729 // Note that we inverted the condition above, so we reverse the order of
2730 // the true and false operands here. This will allow the setcc to be
2731 // matched to a single CSINC instruction.
2732 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
2735 // Now we know we're dealing with FP values.
2736 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2738 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
2739 // and do the comparison.
2740 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2742 ARM64CC::CondCode CC1, CC2;
2743 changeFPCCToARM64CC(CC, CC1, CC2);
2744 if (CC2 == ARM64CC::AL) {
2745 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
2746 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2748 // Note that we inverted the condition above, so we reverse the order of
2749 // the true and false operands here. This will allow the setcc to be
2750 // matched to a single CSINC instruction.
2751 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
2753 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2754 // clean. Some of them require two CSELs to implement. As is in this case,
2755 // we emit the first CSEL and then emit a second using the output of the
2756 // first as the RHS. We're effectively OR'ing the two CC's together.
2758 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
2759 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2760 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2762 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2763 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
2767 /// A SELECT_CC operation is really some kind of max or min if both values being
2768 /// compared are, in some sense, equal to the results in either case. However,
2769 /// it is permissible to compare f32 values and produce directly extended f64
2772 /// Extending the comparison operands would also be allowed, but is less likely
2773 /// to happen in practice since their use is right here. Note that truncate
2774 /// operations would *not* be semantically equivalent.
2775 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
2779 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
2780 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
2781 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
2782 Result.getValueType() == MVT::f64) {
2784 APFloat CmpVal = CCmp->getValueAPF();
2785 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
2786 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
2789 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
2792 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2793 SDValue CC = Op->getOperand(0);
2794 SDValue TVal = Op->getOperand(1);
2795 SDValue FVal = Op->getOperand(2);
2798 unsigned Opc = CC.getOpcode();
2799 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
2801 if (CC.getResNo() == 1 &&
2802 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2803 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2804 // Only lower legal XALUO ops.
2805 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
2808 ARM64CC::CondCode OFCC;
2809 SDValue Value, Overflow;
2810 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
2811 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2813 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
2817 if (CC.getOpcode() == ISD::SETCC)
2818 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
2819 cast<CondCodeSDNode>(CC.getOperand(2))->get());
2821 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
2825 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
2826 SelectionDAG &DAG) const {
2827 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2828 SDValue LHS = Op.getOperand(0);
2829 SDValue RHS = Op.getOperand(1);
2830 SDValue TVal = Op.getOperand(2);
2831 SDValue FVal = Op.getOperand(3);
2834 // Handle f128 first, because it will result in a comparison of some RTLIB
2835 // call result against zero.
2836 if (LHS.getValueType() == MVT::f128) {
2837 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2839 // If softenSetCCOperands returned a scalar, we need to compare the result
2840 // against zero to select between true and false values.
2841 if (RHS.getNode() == 0) {
2842 RHS = DAG.getConstant(0, LHS.getValueType());
2847 // Handle integers first.
2848 if (LHS.getValueType().isInteger()) {
2849 assert((LHS.getValueType() == RHS.getValueType()) &&
2850 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2852 unsigned Opcode = ARM64ISD::CSEL;
2854 // If both the TVal and the FVal are constants, see if we can swap them in
2855 // order to for a CSINV or CSINC out of them.
2856 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2857 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2859 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2860 std::swap(TVal, FVal);
2861 std::swap(CTVal, CFVal);
2862 CC = ISD::getSetCCInverse(CC, true);
2863 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
2864 std::swap(TVal, FVal);
2865 std::swap(CTVal, CFVal);
2866 CC = ISD::getSetCCInverse(CC, true);
2867 } else if (TVal.getOpcode() == ISD::XOR) {
2868 // If TVal is a NOT we want to swap TVal and FVal so that we can match
2869 // with a CSINV rather than a CSEL.
2870 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
2872 if (CVal && CVal->isAllOnesValue()) {
2873 std::swap(TVal, FVal);
2874 std::swap(CTVal, CFVal);
2875 CC = ISD::getSetCCInverse(CC, true);
2877 } else if (TVal.getOpcode() == ISD::SUB) {
2878 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
2879 // that we can match with a CSNEG rather than a CSEL.
2880 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
2882 if (CVal && CVal->isNullValue()) {
2883 std::swap(TVal, FVal);
2884 std::swap(CTVal, CFVal);
2885 CC = ISD::getSetCCInverse(CC, true);
2887 } else if (CTVal && CFVal) {
2888 const int64_t TrueVal = CTVal->getSExtValue();
2889 const int64_t FalseVal = CFVal->getSExtValue();
2892 // If both TVal and FVal are constants, see if FVal is the
2893 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
2894 // instead of a CSEL in that case.
2895 if (TrueVal == ~FalseVal) {
2896 Opcode = ARM64ISD::CSINV;
2897 } else if (TrueVal == -FalseVal) {
2898 Opcode = ARM64ISD::CSNEG;
2899 } else if (TVal.getValueType() == MVT::i32) {
2900 // If our operands are only 32-bit wide, make sure we use 32-bit
2901 // arithmetic for the check whether we can use CSINC. This ensures that
2902 // the addition in the check will wrap around properly in case there is
2903 // an overflow (which would not be the case if we do the check with
2904 // 64-bit arithmetic).
2905 const uint32_t TrueVal32 = CTVal->getZExtValue();
2906 const uint32_t FalseVal32 = CFVal->getZExtValue();
2908 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
2909 Opcode = ARM64ISD::CSINC;
2911 if (TrueVal32 > FalseVal32) {
2915 // 64-bit check whether we can use CSINC.
2916 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
2917 Opcode = ARM64ISD::CSINC;
2919 if (TrueVal > FalseVal) {
2924 // Swap TVal and FVal if necessary.
2926 std::swap(TVal, FVal);
2927 std::swap(CTVal, CFVal);
2928 CC = ISD::getSetCCInverse(CC, true);
2931 if (Opcode != ARM64ISD::CSEL) {
2932 // Drop FVal since we can get its value by simply inverting/negating
2939 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2941 EVT VT = Op.getValueType();
2942 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
2945 // Now we know we're dealing with FP values.
2946 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2947 assert(LHS.getValueType() == RHS.getValueType());
2948 EVT VT = Op.getValueType();
2950 // Try to match this select into a max/min operation, which have dedicated
2951 // opcode in the instruction set.
2952 // NOTE: This is not correct in the presence of NaNs, so we only enable this
2954 if (getTargetMachine().Options.NoNaNsFPMath) {
2955 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
2956 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
2957 CC = ISD::getSetCCSwappedOperands(CC);
2958 std::swap(TVal, FVal);
2961 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
2962 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
2972 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
2980 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
2986 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
2987 // and do the comparison.
2988 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2990 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2991 // clean. Some of them require two CSELs to implement.
2992 ARM64CC::CondCode CC1, CC2;
2993 changeFPCCToARM64CC(CC, CC1, CC2);
2994 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2995 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2997 // If we need a second CSEL, emit it, using the output of the first as the
2998 // RHS. We're effectively OR'ing the two CC's together.
2999 if (CC2 != ARM64CC::AL) {
3000 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3001 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3004 // Otherwise, return the output of the first CSEL.
3008 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3009 SelectionDAG &DAG) const {
3010 // Jump table entries as PC relative offsets. No additional tweaking
3011 // is necessary here. Just get the address of the jump table.
3012 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3013 EVT PtrVT = getPointerTy();
3016 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3017 !Subtarget->isTargetMachO()) {
3018 const unsigned char MO_NC = ARM64II::MO_NC;
3020 ARM64ISD::WrapperLarge, DL, PtrVT,
3021 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G3),
3022 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G2 | MO_NC),
3023 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G1 | MO_NC),
3024 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G0 | MO_NC));
3027 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3028 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3029 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3030 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3031 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3034 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3035 SelectionDAG &DAG) const {
3036 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3037 EVT PtrVT = getPointerTy();
3040 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3041 // Use the GOT for the large code model on iOS.
3042 if (Subtarget->isTargetMachO()) {
3043 SDValue GotAddr = DAG.getTargetConstantPool(
3044 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3046 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3049 const unsigned char MO_NC = ARM64II::MO_NC;
3051 ARM64ISD::WrapperLarge, DL, PtrVT,
3052 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3053 CP->getOffset(), ARM64II::MO_G3),
3054 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3055 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3056 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3057 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3058 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3059 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3061 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3062 // ELF, the only valid one on Darwin.
3064 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3065 CP->getOffset(), ARM64II::MO_PAGE);
3066 SDValue Lo = DAG.getTargetConstantPool(
3067 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3068 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3070 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3071 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3075 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3076 SelectionDAG &DAG) const {
3077 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3078 EVT PtrVT = getPointerTy();
3080 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3081 !Subtarget->isTargetMachO()) {
3082 const unsigned char MO_NC = ARM64II::MO_NC;
3084 ARM64ISD::WrapperLarge, DL, PtrVT,
3085 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3086 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3087 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3088 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3090 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3091 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3093 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3094 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3098 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3099 SelectionDAG &DAG) const {
3100 ARM64FunctionInfo *FuncInfo =
3101 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3105 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3106 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3107 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3108 MachinePointerInfo(SV), false, false, 0);
3111 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3112 SelectionDAG &DAG) const {
3113 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3114 // Standard, section B.3.
3115 MachineFunction &MF = DAG.getMachineFunction();
3116 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3119 SDValue Chain = Op.getOperand(0);
3120 SDValue VAList = Op.getOperand(1);
3121 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3122 SmallVector<SDValue, 4> MemOps;
3124 // void *__stack at offset 0
3126 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3127 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3128 MachinePointerInfo(SV), false, false, 8));
3130 // void *__gr_top at offset 8
3131 int GPRSize = FuncInfo->getVarArgsGPRSize();
3133 SDValue GRTop, GRTopAddr;
3135 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3136 DAG.getConstant(8, getPointerTy()));
3138 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3139 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3140 DAG.getConstant(GPRSize, getPointerTy()));
3142 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3143 MachinePointerInfo(SV, 8), false, false, 8));
3146 // void *__vr_top at offset 16
3147 int FPRSize = FuncInfo->getVarArgsFPRSize();
3149 SDValue VRTop, VRTopAddr;
3150 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3151 DAG.getConstant(16, getPointerTy()));
3153 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3154 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3155 DAG.getConstant(FPRSize, getPointerTy()));
3157 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3158 MachinePointerInfo(SV, 16), false, false, 8));
3161 // int __gr_offs at offset 24
3162 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3163 DAG.getConstant(24, getPointerTy()));
3164 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3165 GROffsAddr, MachinePointerInfo(SV, 24), false,
3168 // int __vr_offs at offset 28
3169 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3170 DAG.getConstant(28, getPointerTy()));
3171 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3172 VROffsAddr, MachinePointerInfo(SV, 28), false,
3175 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
3179 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3180 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3181 : LowerAAPCS_VASTART(Op, DAG);
3184 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3185 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3187 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3188 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3189 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3191 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3192 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3193 8, false, false, MachinePointerInfo(DestSV),
3194 MachinePointerInfo(SrcSV));
3197 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3198 assert(Subtarget->isTargetDarwin() &&
3199 "automatic va_arg instruction only works on Darwin");
3201 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3202 EVT VT = Op.getValueType();
3204 SDValue Chain = Op.getOperand(0);
3205 SDValue Addr = Op.getOperand(1);
3206 unsigned Align = Op.getConstantOperandVal(3);
3208 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3209 MachinePointerInfo(V), false, false, false, 0);
3210 Chain = VAList.getValue(1);
3213 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3214 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3215 DAG.getConstant(Align - 1, getPointerTy()));
3216 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3217 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3220 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3221 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3223 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3224 // up to 64 bits. At the very least, we have to increase the striding of the
3225 // vaargs list to match this, and for FP values we need to introduce
3226 // FP_ROUND nodes as well.
3227 if (VT.isInteger() && !VT.isVector())
3229 bool NeedFPTrunc = false;
3230 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3235 // Increment the pointer, VAList, to the next vaarg
3236 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3237 DAG.getConstant(ArgSize, getPointerTy()));
3238 // Store the incremented VAList to the legalized pointer
3239 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3242 // Load the actual argument out of the pointer VAList
3244 // Load the value as an f64.
3245 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3246 MachinePointerInfo(), false, false, false, 0);
3247 // Round the value down to an f32.
3248 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3249 DAG.getIntPtrConstant(1));
3250 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3251 // Merge the rounded value with the chain output of the load.
3252 return DAG.getMergeValues(Ops, 2, DL);
3255 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3259 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3260 SelectionDAG &DAG) const {
3261 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3262 MFI->setFrameAddressIsTaken(true);
3264 EVT VT = Op.getValueType();
3266 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3267 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3269 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3270 MachinePointerInfo(), false, false, false, 0);
3274 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3275 SelectionDAG &DAG) const {
3276 MachineFunction &MF = DAG.getMachineFunction();
3277 MachineFrameInfo *MFI = MF.getFrameInfo();
3278 MFI->setReturnAddressIsTaken(true);
3280 EVT VT = Op.getValueType();
3282 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3284 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3285 SDValue Offset = DAG.getConstant(8, getPointerTy());
3286 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3287 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3288 MachinePointerInfo(), false, false, false, 0);
3291 // Return LR, which contains the return address. Mark it an implicit live-in.
3292 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3293 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3296 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3297 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3298 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3299 SelectionDAG &DAG) const {
3300 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3301 EVT VT = Op.getValueType();
3302 unsigned VTBits = VT.getSizeInBits();
3304 SDValue ShOpLo = Op.getOperand(0);
3305 SDValue ShOpHi = Op.getOperand(1);
3306 SDValue ShAmt = Op.getOperand(2);
3308 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3310 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3312 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3313 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3314 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3315 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3316 DAG.getConstant(VTBits, MVT::i64));
3317 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3319 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3320 ISD::SETGE, dl, DAG);
3321 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3323 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3324 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3326 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3328 // ARM64 shifts larger than the register width are wrapped rather than
3329 // clamped, so we can't just emit "hi >> x".
3330 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3331 SDValue TrueValHi = Opc == ISD::SRA
3332 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3333 DAG.getConstant(VTBits - 1, MVT::i64))
3334 : DAG.getConstant(0, VT);
3336 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3338 SDValue Ops[2] = { Lo, Hi };
3339 return DAG.getMergeValues(Ops, 2, dl);
3342 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3343 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3344 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3345 SelectionDAG &DAG) const {
3346 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3347 EVT VT = Op.getValueType();
3348 unsigned VTBits = VT.getSizeInBits();
3350 SDValue ShOpLo = Op.getOperand(0);
3351 SDValue ShOpHi = Op.getOperand(1);
3352 SDValue ShAmt = Op.getOperand(2);
3355 assert(Op.getOpcode() == ISD::SHL_PARTS);
3356 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3357 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3358 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3359 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3360 DAG.getConstant(VTBits, MVT::i64));
3361 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3362 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3364 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3366 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3367 ISD::SETGE, dl, DAG);
3368 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3369 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3371 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3372 // so we can't just emit "lo << a" if a is too big.
3373 SDValue TrueValLo = DAG.getConstant(0, VT);
3374 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3376 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3378 SDValue Ops[2] = { Lo, Hi };
3379 return DAG.getMergeValues(Ops, 2, dl);
3383 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3384 // The ARM64 target doesn't support folding offsets into global addresses.
3388 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3389 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3390 // FIXME: We should be able to handle f128 as well with a clever lowering.
3391 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3395 return ARM64_AM::getFP64Imm(Imm) != -1;
3396 else if (VT == MVT::f32)
3397 return ARM64_AM::getFP32Imm(Imm) != -1;
3401 //===----------------------------------------------------------------------===//
3402 // ARM64 Optimization Hooks
3403 //===----------------------------------------------------------------------===//
3405 //===----------------------------------------------------------------------===//
3406 // ARM64 Inline Assembly Support
3407 //===----------------------------------------------------------------------===//
3409 // Table of Constraints
3410 // TODO: This is the current set of constraints supported by ARM for the
3411 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3413 // r - A general register
3414 // w - An FP/SIMD register of some size in the range v0-v31
3415 // x - An FP/SIMD register of some size in the range v0-v15
3416 // I - Constant that can be used with an ADD instruction
3417 // J - Constant that can be used with a SUB instruction
3418 // K - Constant that can be used with a 32-bit logical instruction
3419 // L - Constant that can be used with a 64-bit logical instruction
3420 // M - Constant that can be used as a 32-bit MOV immediate
3421 // N - Constant that can be used as a 64-bit MOV immediate
3422 // Q - A memory reference with base register and no offset
3423 // S - A symbolic address
3424 // Y - Floating point constant zero
3425 // Z - Integer constant zero
3427 // Note that general register operands will be output using their 64-bit x
3428 // register name, whatever the size of the variable, unless the asm operand
3429 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3430 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3433 /// getConstraintType - Given a constraint letter, return the type of
3434 /// constraint it is for this target.
3435 ARM64TargetLowering::ConstraintType
3436 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3437 if (Constraint.size() == 1) {
3438 switch (Constraint[0]) {
3445 return C_RegisterClass;
3446 // An address with a single base register. Due to the way we
3447 // currently handle addresses it is the same as 'r'.
3452 return TargetLowering::getConstraintType(Constraint);
3455 /// Examine constraint type and operand type and determine a weight value.
3456 /// This object must already have been set up with the operand type
3457 /// and the current alternative constraint selected.
3458 TargetLowering::ConstraintWeight
3459 ARM64TargetLowering::getSingleConstraintMatchWeight(
3460 AsmOperandInfo &info, const char *constraint) const {
3461 ConstraintWeight weight = CW_Invalid;
3462 Value *CallOperandVal = info.CallOperandVal;
3463 // If we don't have a value, we can't do a match,
3464 // but allow it at the lowest weight.
3465 if (CallOperandVal == NULL)
3467 Type *type = CallOperandVal->getType();
3468 // Look at the constraint type.
3469 switch (*constraint) {
3471 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3475 if (type->isFloatingPointTy() || type->isVectorTy())
3476 weight = CW_Register;
3479 weight = CW_Constant;
3485 std::pair<unsigned, const TargetRegisterClass *>
3486 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3488 if (Constraint.size() == 1) {
3489 switch (Constraint[0]) {
3491 if (VT.getSizeInBits() == 64)
3492 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3493 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3496 return std::make_pair(0U, &ARM64::FPR32RegClass);
3497 if (VT.getSizeInBits() == 64)
3498 return std::make_pair(0U, &ARM64::FPR64RegClass);
3499 if (VT.getSizeInBits() == 128)
3500 return std::make_pair(0U, &ARM64::FPR128RegClass);
3502 // The instructions that this constraint is designed for can
3503 // only take 128-bit registers so just use that regclass.
3505 if (VT.getSizeInBits() == 128)
3506 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
3510 if (StringRef("{cc}").equals_lower(Constraint))
3511 return std::make_pair(unsigned(ARM64::CPSR), &ARM64::CCRRegClass);
3513 // Use the default implementation in TargetLowering to convert the register
3514 // constraint into a member of a register class.
3515 std::pair<unsigned, const TargetRegisterClass *> Res;
3516 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3518 // Not found as a standard register?
3519 if (Res.second == 0) {
3520 unsigned Size = Constraint.size();
3521 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3522 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3523 const std::string Reg =
3524 std::string(&Constraint[2], &Constraint[Size - 1]);
3525 int RegNo = atoi(Reg.c_str());
3526 if (RegNo >= 0 && RegNo <= 31) {
3527 // v0 - v31 are aliases of q0 - q31.
3528 // By default we'll emit v0-v31 for this unless there's a modifier where
3529 // we'll emit the correct register as well.
3530 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
3531 Res.second = &ARM64::FPR128RegClass;
3539 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3540 /// vector. If it is invalid, don't add anything to Ops.
3541 void ARM64TargetLowering::LowerAsmOperandForConstraint(
3542 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3543 SelectionDAG &DAG) const {
3544 SDValue Result(0, 0);
3546 // Currently only support length 1 constraints.
3547 if (Constraint.length() != 1)
3550 char ConstraintLetter = Constraint[0];
3551 switch (ConstraintLetter) {
3555 // This set of constraints deal with valid constants for various instructions.
3556 // Validate and return a target constant for them if we can.
3558 // 'z' maps to xzr or wzr so it needs an input of 0.
3559 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3560 if (!C || C->getZExtValue() != 0)
3563 if (Op.getValueType() == MVT::i64)
3564 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
3566 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
3576 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3580 // Grab the value and do some validation.
3581 uint64_t CVal = C->getZExtValue();
3582 switch (ConstraintLetter) {
3583 // The I constraint applies only to simple ADD or SUB immediate operands:
3584 // i.e. 0 to 4095 with optional shift by 12
3585 // The J constraint applies only to ADD or SUB immediates that would be
3586 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
3587 // instruction [or vice versa], in other words -1 to -4095 with optional
3588 // left shift by 12.
3590 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
3594 uint64_t NVal = -C->getSExtValue();
3595 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
3599 // The K and L constraints apply *only* to logical immediates, including
3600 // what used to be the MOVI alias for ORR (though the MOVI alias has now
3601 // been removed and MOV should be used). So these constraints have to
3602 // distinguish between bit patterns that are valid 32-bit or 64-bit
3603 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
3604 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
3607 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3611 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3614 // The M and N constraints are a superset of K and L respectively, for use
3615 // with the MOV (immediate) alias. As well as the logical immediates they
3616 // also match 32 or 64-bit immediates that can be loaded either using a
3617 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
3618 // (M) or 64-bit 0x1234000000000000 (N) etc.
3619 // As a note some of this code is liberally stolen from the asm parser.
3621 if (!isUInt<32>(CVal))
3623 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3625 if ((CVal & 0xFFFF) == CVal)
3627 if ((CVal & 0xFFFF0000ULL) == CVal)
3629 uint64_t NCVal = ~(uint32_t)CVal;
3630 if ((NCVal & 0xFFFFULL) == NCVal)
3632 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3637 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3639 if ((CVal & 0xFFFFULL) == CVal)
3641 if ((CVal & 0xFFFF0000ULL) == CVal)
3643 if ((CVal & 0xFFFF00000000ULL) == CVal)
3645 if ((CVal & 0xFFFF000000000000ULL) == CVal)
3647 uint64_t NCVal = ~CVal;
3648 if ((NCVal & 0xFFFFULL) == NCVal)
3650 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3652 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
3654 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
3662 // All assembler immediates are 64-bit integers.
3663 Result = DAG.getTargetConstant(CVal, MVT::i64);
3667 if (Result.getNode()) {
3668 Ops.push_back(Result);
3672 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3675 //===----------------------------------------------------------------------===//
3676 // ARM64 Advanced SIMD Support
3677 //===----------------------------------------------------------------------===//
3679 /// WidenVector - Given a value in the V64 register class, produce the
3680 /// equivalent value in the V128 register class.
3681 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
3682 EVT VT = V64Reg.getValueType();
3683 unsigned NarrowSize = VT.getVectorNumElements();
3684 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3685 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
3688 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
3689 V64Reg, DAG.getConstant(0, MVT::i32));
3692 /// getExtFactor - Determine the adjustment factor for the position when
3693 /// generating an "extract from vector registers" instruction.
3694 static unsigned getExtFactor(SDValue &V) {
3695 EVT EltType = V.getValueType().getVectorElementType();
3696 return EltType.getSizeInBits() / 8;
3699 /// NarrowVector - Given a value in the V128 register class, produce the
3700 /// equivalent value in the V64 register class.
3701 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
3702 EVT VT = V128Reg.getValueType();
3703 unsigned WideSize = VT.getVectorNumElements();
3704 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3705 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
3708 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
3711 // Gather data to see if the operation can be modelled as a
3712 // shuffle in combination with VEXTs.
3713 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
3714 SelectionDAG &DAG) const {
3716 EVT VT = Op.getValueType();
3717 unsigned NumElts = VT.getVectorNumElements();
3719 SmallVector<SDValue, 2> SourceVecs;
3720 SmallVector<unsigned, 2> MinElts;
3721 SmallVector<unsigned, 2> MaxElts;
3723 for (unsigned i = 0; i < NumElts; ++i) {
3724 SDValue V = Op.getOperand(i);
3725 if (V.getOpcode() == ISD::UNDEF)
3727 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3728 // A shuffle can only come from building a vector from various
3729 // elements of other vectors.
3733 // Record this extraction against the appropriate vector if possible...
3734 SDValue SourceVec = V.getOperand(0);
3735 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3736 bool FoundSource = false;
3737 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3738 if (SourceVecs[j] == SourceVec) {
3739 if (MinElts[j] > EltNo)
3741 if (MaxElts[j] < EltNo)
3748 // Or record a new source if not...
3750 SourceVecs.push_back(SourceVec);
3751 MinElts.push_back(EltNo);
3752 MaxElts.push_back(EltNo);
3756 // Currently only do something sane when at most two source vectors
3758 if (SourceVecs.size() > 2)
3761 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3762 int VEXTOffsets[2] = { 0, 0 };
3764 // This loop extracts the usage patterns of the source vectors
3765 // and prepares appropriate SDValues for a shuffle if possible.
3766 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3767 if (SourceVecs[i].getValueType() == VT) {
3768 // No VEXT necessary
3769 ShuffleSrcs[i] = SourceVecs[i];
3772 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3773 // It probably isn't worth padding out a smaller vector just to
3774 // break it down again in a shuffle.
3778 // Don't attempt to extract subvectors from BUILD_VECTOR sources
3779 // that expand or trunc the original value.
3780 // TODO: We can try to bitcast and ANY_EXTEND the result but
3781 // we need to consider the cost of vector ANY_EXTEND, and the
3782 // legality of all the types.
3783 if (SourceVecs[i].getValueType().getVectorElementType() !=
3784 VT.getVectorElementType())
3787 // Since only 64-bit and 128-bit vectors are legal on ARM and
3788 // we've eliminated the other cases...
3789 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3790 "unexpected vector sizes in ReconstructShuffle");
3792 if (MaxElts[i] - MinElts[i] >= NumElts) {
3793 // Span too large for a VEXT to cope
3797 if (MinElts[i] >= NumElts) {
3798 // The extraction can just take the second half
3799 VEXTOffsets[i] = NumElts;
3801 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3802 DAG.getIntPtrConstant(NumElts));
3803 } else if (MaxElts[i] < NumElts) {
3804 // The extraction can just take the first half
3806 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3807 SourceVecs[i], DAG.getIntPtrConstant(0));
3809 // An actual VEXT is needed
3810 VEXTOffsets[i] = MinElts[i];
3811 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3812 SourceVecs[i], DAG.getIntPtrConstant(0));
3814 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3815 DAG.getIntPtrConstant(NumElts));
3816 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
3817 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
3818 DAG.getConstant(Imm, MVT::i32));
3822 SmallVector<int, 8> Mask;
3824 for (unsigned i = 0; i < NumElts; ++i) {
3825 SDValue Entry = Op.getOperand(i);
3826 if (Entry.getOpcode() == ISD::UNDEF) {
3831 SDValue ExtractVec = Entry.getOperand(0);
3833 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
3834 if (ExtractVec == SourceVecs[0]) {
3835 Mask.push_back(ExtractElt - VEXTOffsets[0]);
3837 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
3841 // Final check before we try to produce nonsense...
3842 if (isShuffleMaskLegal(Mask, VT))
3843 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
3849 // check if an EXT instruction can handle the shuffle mask when the
3850 // vector sources of the shuffle are the same.
3851 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3852 unsigned NumElts = VT.getVectorNumElements();
3854 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3860 // If this is a VEXT shuffle, the immediate value is the index of the first
3861 // element. The other shuffle indices must be the successive elements after
3863 unsigned ExpectedElt = Imm;
3864 for (unsigned i = 1; i < NumElts; ++i) {
3865 // Increment the expected index. If it wraps around, just follow it
3866 // back to index zero and keep going.
3868 if (ExpectedElt == NumElts)
3872 continue; // ignore UNDEF indices
3873 if (ExpectedElt != static_cast<unsigned>(M[i]))
3880 // check if an EXT instruction can handle the shuffle mask when the
3881 // vector sources of the shuffle are different.
3882 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
3884 unsigned NumElts = VT.getVectorNumElements();
3887 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3893 // If this is a VEXT shuffle, the immediate value is the index of the first
3894 // element. The other shuffle indices must be the successive elements after
3896 unsigned ExpectedElt = Imm;
3897 for (unsigned i = 1; i < NumElts; ++i) {
3898 // Increment the expected index. If it wraps around, it may still be
3899 // a VEXT but the source vectors must be swapped.
3901 if (ExpectedElt == NumElts * 2) {
3907 continue; // ignore UNDEF indices
3908 if (ExpectedElt != static_cast<unsigned>(M[i]))
3912 // Adjust the index value if the source operands will be swapped.
3919 /// isREVMask - Check if a vector shuffle corresponds to a REV
3920 /// instruction with the specified blocksize. (The order of the elements
3921 /// within each block of the vector is reversed.)
3922 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3923 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
3924 "Only possible block sizes for REV are: 16, 32, 64");
3926 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3930 unsigned NumElts = VT.getVectorNumElements();
3931 unsigned BlockElts = M[0] + 1;
3932 // If the first shuffle index is UNDEF, be optimistic.
3934 BlockElts = BlockSize / EltSz;
3936 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3939 for (unsigned i = 0; i < NumElts; ++i) {
3941 continue; // ignore UNDEF indices
3942 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
3949 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3950 unsigned NumElts = VT.getVectorNumElements();
3951 WhichResult = (M[0] == 0 ? 0 : 1);
3952 unsigned Idx = WhichResult * NumElts / 2;
3953 for (unsigned i = 0; i != NumElts; i += 2) {
3954 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
3955 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
3963 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3964 unsigned NumElts = VT.getVectorNumElements();
3965 WhichResult = (M[0] == 0 ? 0 : 1);
3966 for (unsigned i = 0; i != NumElts; ++i) {
3968 continue; // ignore UNDEF indices
3969 if ((unsigned)M[i] != 2 * i + WhichResult)
3976 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3977 unsigned NumElts = VT.getVectorNumElements();
3978 WhichResult = (M[0] == 0 ? 0 : 1);
3979 for (unsigned i = 0; i < NumElts; i += 2) {
3980 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
3981 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
3987 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
3988 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3989 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3990 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3991 unsigned NumElts = VT.getVectorNumElements();
3992 WhichResult = (M[0] == 0 ? 0 : 1);
3993 unsigned Idx = WhichResult * NumElts / 2;
3994 for (unsigned i = 0; i != NumElts; i += 2) {
3995 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
3996 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4004 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4005 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4006 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4007 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4008 unsigned Half = VT.getVectorNumElements() / 2;
4009 WhichResult = (M[0] == 0 ? 0 : 1);
4010 for (unsigned j = 0; j != 2; ++j) {
4011 unsigned Idx = WhichResult;
4012 for (unsigned i = 0; i != Half; ++i) {
4013 int MIdx = M[i + j * Half];
4014 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4023 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4024 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4025 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4026 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4027 unsigned NumElts = VT.getVectorNumElements();
4028 WhichResult = (M[0] == 0 ? 0 : 1);
4029 for (unsigned i = 0; i < NumElts; i += 2) {
4030 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4031 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4037 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4038 /// the specified operations to build the shuffle.
4039 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4040 SDValue RHS, SelectionDAG &DAG,
4042 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4043 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4044 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4047 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4056 OP_VUZPL, // VUZP, left result
4057 OP_VUZPR, // VUZP, right result
4058 OP_VZIPL, // VZIP, left result
4059 OP_VZIPR, // VZIP, right result
4060 OP_VTRNL, // VTRN, left result
4061 OP_VTRNR // VTRN, right result
4064 if (OpNum == OP_COPY) {
4065 if (LHSID == (1 * 9 + 2) * 9 + 3)
4067 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4071 SDValue OpLHS, OpRHS;
4072 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4073 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4074 EVT VT = OpLHS.getValueType();
4078 llvm_unreachable("Unknown shuffle opcode!");
4080 // VREV divides the vector in half and swaps within the half.
4081 if (VT.getVectorElementType() == MVT::i32 ||
4082 VT.getVectorElementType() == MVT::f32)
4083 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4084 // vrev <4 x i16> -> REV32
4085 if (VT.getVectorElementType() == MVT::i16)
4086 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4087 // vrev <4 x i8> -> REV16
4088 assert(VT.getVectorElementType() == MVT::i8);
4089 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4094 EVT EltTy = VT.getVectorElementType();
4096 if (EltTy == MVT::i8)
4097 Opcode = ARM64ISD::DUPLANE8;
4098 else if (EltTy == MVT::i16)
4099 Opcode = ARM64ISD::DUPLANE16;
4100 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4101 Opcode = ARM64ISD::DUPLANE32;
4102 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4103 Opcode = ARM64ISD::DUPLANE64;
4105 llvm_unreachable("Invalid vector element type?");
4107 if (VT.getSizeInBits() == 64)
4108 OpLHS = WidenVector(OpLHS, DAG);
4109 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4110 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4115 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4116 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4117 DAG.getConstant(Imm, MVT::i32));
4120 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4122 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4124 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4126 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4128 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4130 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4134 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4135 SelectionDAG &DAG) {
4136 // Check to see if we can use the TBL instruction.
4137 SDValue V1 = Op.getOperand(0);
4138 SDValue V2 = Op.getOperand(1);
4141 EVT EltVT = Op.getValueType().getVectorElementType();
4142 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4144 SmallVector<SDValue, 8> TBLMask;
4145 for (int Val : ShuffleMask) {
4146 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4147 unsigned Offset = Byte + Val * BytesPerElt;
4148 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4152 MVT IndexVT = MVT::v8i8;
4153 unsigned IndexLen = 8;
4154 if (Op.getValueType().getSizeInBits() == 128) {
4155 IndexVT = MVT::v16i8;
4159 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4160 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4163 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4165 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4166 Shuffle = DAG.getNode(
4167 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4168 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4169 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4171 if (IndexLen == 8) {
4172 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4173 Shuffle = DAG.getNode(
4174 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4175 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4176 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4178 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4179 // cannot currently represent the register constraints on the input
4181 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4182 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4183 // &TBLMask[0], IndexLen));
4184 Shuffle = DAG.getNode(
4185 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4186 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4187 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4190 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4193 static unsigned getDUPLANEOp(EVT EltType) {
4194 if (EltType == MVT::i8)
4195 return ARM64ISD::DUPLANE8;
4196 if (EltType == MVT::i16)
4197 return ARM64ISD::DUPLANE16;
4198 if (EltType == MVT::i32 || EltType == MVT::f32)
4199 return ARM64ISD::DUPLANE32;
4200 if (EltType == MVT::i64 || EltType == MVT::f64)
4201 return ARM64ISD::DUPLANE64;
4203 llvm_unreachable("Invalid vector element type?");
4206 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4207 SelectionDAG &DAG) const {
4209 EVT VT = Op.getValueType();
4211 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4213 // Convert shuffles that are directly supported on NEON to target-specific
4214 // DAG nodes, instead of keeping them as shuffles and matching them again
4215 // during code selection. This is more efficient and avoids the possibility
4216 // of inconsistencies between legalization and selection.
4217 ArrayRef<int> ShuffleMask = SVN->getMask();
4219 SDValue V1 = Op.getOperand(0);
4220 SDValue V2 = Op.getOperand(1);
4222 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4223 V1.getValueType().getSimpleVT())) {
4224 int Lane = SVN->getSplatIndex();
4225 // If this is undef splat, generate it via "just" vdup, if possible.
4229 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4230 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4232 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4233 // constant. If so, we can just reference the lane's definition directly.
4234 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4235 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4236 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4238 // Otherwise, duplicate from the lane of the input vector.
4239 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4241 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4242 // to make a vector of the same size as this SHUFFLE. We can ignore the
4243 // extract entirely, and canonicalise the concat using WidenVector.
4244 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4245 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4246 V1 = V1.getOperand(0);
4247 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4248 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4249 Lane -= Idx * VT.getVectorNumElements() / 2;
4250 V1 = WidenVector(V1.getOperand(Idx), DAG);
4251 } else if (VT.getSizeInBits() == 64)
4252 V1 = WidenVector(V1, DAG);
4254 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4257 if (isREVMask(ShuffleMask, VT, 64))
4258 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4259 if (isREVMask(ShuffleMask, VT, 32))
4260 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4261 if (isREVMask(ShuffleMask, VT, 16))
4262 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4264 bool ReverseEXT = false;
4266 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4269 Imm *= getExtFactor(V1);
4270 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4271 DAG.getConstant(Imm, MVT::i32));
4272 } else if (V2->getOpcode() == ISD::UNDEF &&
4273 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4274 Imm *= getExtFactor(V1);
4275 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4276 DAG.getConstant(Imm, MVT::i32));
4279 unsigned WhichResult;
4280 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4281 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4282 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4284 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4285 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4286 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4288 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4289 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4290 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4293 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4294 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4295 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4297 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4298 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4299 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4301 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4302 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4303 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4306 // If the shuffle is not directly supported and it has 4 elements, use
4307 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4308 unsigned NumElts = VT.getVectorNumElements();
4310 unsigned PFIndexes[4];
4311 for (unsigned i = 0; i != 4; ++i) {
4312 if (ShuffleMask[i] < 0)
4315 PFIndexes[i] = ShuffleMask[i];
4318 // Compute the index in the perfect shuffle table.
4319 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4320 PFIndexes[2] * 9 + PFIndexes[3];
4321 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4322 unsigned Cost = (PFEntry >> 30);
4325 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4328 return GenerateTBL(Op, ShuffleMask, DAG);
4331 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4333 EVT VT = BVN->getValueType(0);
4334 APInt SplatBits, SplatUndef;
4335 unsigned SplatBitSize;
4337 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4338 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4340 for (unsigned i = 0; i < NumSplats; ++i) {
4341 CnstBits <<= SplatBitSize;
4342 UndefBits <<= SplatBitSize;
4343 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4344 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4353 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4354 SelectionDAG &DAG) const {
4355 BuildVectorSDNode *BVN =
4356 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4357 SDValue LHS = Op.getOperand(0);
4359 EVT VT = Op.getValueType();
4364 APInt CnstBits(VT.getSizeInBits(), 0);
4365 APInt UndefBits(VT.getSizeInBits(), 0);
4366 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4367 // We only have BIC vector immediate instruction, which is and-not.
4368 CnstBits = ~CnstBits;
4370 // We make use of a little bit of goto ickiness in order to avoid having to
4371 // duplicate the immediate matching logic for the undef toggled case.
4372 bool SecondTry = false;
4375 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4376 CnstBits = CnstBits.zextOrTrunc(64);
4377 uint64_t CnstVal = CnstBits.getZExtValue();
4379 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4380 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4381 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4382 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4383 DAG.getConstant(CnstVal, MVT::i32),
4384 DAG.getConstant(0, MVT::i32));
4385 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4388 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4389 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4390 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4391 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4392 DAG.getConstant(CnstVal, MVT::i32),
4393 DAG.getConstant(8, MVT::i32));
4394 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4397 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4398 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4399 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4400 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4401 DAG.getConstant(CnstVal, MVT::i32),
4402 DAG.getConstant(16, MVT::i32));
4403 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4406 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4407 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4408 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4409 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4410 DAG.getConstant(CnstVal, MVT::i32),
4411 DAG.getConstant(24, MVT::i32));
4412 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4415 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4416 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4417 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4418 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4419 DAG.getConstant(CnstVal, MVT::i32),
4420 DAG.getConstant(0, MVT::i32));
4421 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4424 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4425 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4426 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4427 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4428 DAG.getConstant(CnstVal, MVT::i32),
4429 DAG.getConstant(8, MVT::i32));
4430 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4437 CnstBits = ~UndefBits;
4441 // We can always fall back to a non-immediate AND.
4446 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4447 // consists of only the same constant int value, returned in reference arg
4449 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4450 uint64_t &ConstVal) {
4451 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4454 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4457 EVT VT = Bvec->getValueType(0);
4458 unsigned NumElts = VT.getVectorNumElements();
4459 for (unsigned i = 1; i < NumElts; ++i)
4460 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4462 ConstVal = FirstElt->getZExtValue();
4466 static unsigned getIntrinsicID(const SDNode *N) {
4467 unsigned Opcode = N->getOpcode();
4470 return Intrinsic::not_intrinsic;
4471 case ISD::INTRINSIC_WO_CHAIN: {
4472 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4473 if (IID < Intrinsic::num_intrinsics)
4475 return Intrinsic::not_intrinsic;
4480 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4481 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4482 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4483 // Also, logical shift right -> sri, with the same structure.
4484 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4485 EVT VT = N->getValueType(0);
4492 // Is the first op an AND?
4493 const SDValue And = N->getOperand(0);
4494 if (And.getOpcode() != ISD::AND)
4497 // Is the second op an shl or lshr?
4498 SDValue Shift = N->getOperand(1);
4499 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4500 // or ARM64ISD::VLSHR vector, #shift
4501 unsigned ShiftOpc = Shift.getOpcode();
4502 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4504 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4506 // Is the shift amount constant?
4507 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4511 // Is the and mask vector all constant?
4513 if (!isAllConstantBuildVector(And.getOperand(1), C1))
4516 // Is C1 == ~C2, taking into account how much one can shift elements of a
4518 uint64_t C2 = C2node->getZExtValue();
4519 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4520 if (C2 > ElemSizeInBits)
4522 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4523 if ((C1 & ElemMask) != (~C2 & ElemMask))
4526 SDValue X = And.getOperand(0);
4527 SDValue Y = Shift.getOperand(0);
4530 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4532 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4533 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4535 DEBUG(dbgs() << "arm64-lower: transformed: \n");
4536 DEBUG(N->dump(&DAG));
4537 DEBUG(dbgs() << "into: \n");
4538 DEBUG(ResultSLI->dump(&DAG));
4544 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4545 SelectionDAG &DAG) const {
4546 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4547 if (EnableARM64SlrGeneration) {
4548 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4553 BuildVectorSDNode *BVN =
4554 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4555 SDValue LHS = Op.getOperand(1);
4557 EVT VT = Op.getValueType();
4559 // OR commutes, so try swapping the operands.
4561 LHS = Op.getOperand(0);
4562 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4567 APInt CnstBits(VT.getSizeInBits(), 0);
4568 APInt UndefBits(VT.getSizeInBits(), 0);
4569 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4570 // We make use of a little bit of goto ickiness in order to avoid having to
4571 // duplicate the immediate matching logic for the undef toggled case.
4572 bool SecondTry = false;
4575 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4576 CnstBits = CnstBits.zextOrTrunc(64);
4577 uint64_t CnstVal = CnstBits.getZExtValue();
4579 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4580 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4581 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4582 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4583 DAG.getConstant(CnstVal, MVT::i32),
4584 DAG.getConstant(0, MVT::i32));
4585 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4588 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4589 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4590 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4591 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4592 DAG.getConstant(CnstVal, MVT::i32),
4593 DAG.getConstant(8, MVT::i32));
4594 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4597 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4598 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4599 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4600 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4601 DAG.getConstant(CnstVal, MVT::i32),
4602 DAG.getConstant(16, MVT::i32));
4603 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4606 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4607 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4608 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4609 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4610 DAG.getConstant(CnstVal, MVT::i32),
4611 DAG.getConstant(24, MVT::i32));
4612 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4615 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4616 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4617 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4618 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4619 DAG.getConstant(CnstVal, MVT::i32),
4620 DAG.getConstant(0, MVT::i32));
4621 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4624 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4625 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4626 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4627 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4628 DAG.getConstant(CnstVal, MVT::i32),
4629 DAG.getConstant(8, MVT::i32));
4630 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4637 CnstBits = UndefBits;
4641 // We can always fall back to a non-immediate OR.
4646 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4647 SelectionDAG &DAG) const {
4648 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4650 EVT VT = Op.getValueType();
4652 APInt CnstBits(VT.getSizeInBits(), 0);
4653 APInt UndefBits(VT.getSizeInBits(), 0);
4654 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4655 // We make use of a little bit of goto ickiness in order to avoid having to
4656 // duplicate the immediate matching logic for the undef toggled case.
4657 bool SecondTry = false;
4660 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4661 CnstBits = CnstBits.zextOrTrunc(64);
4662 uint64_t CnstVal = CnstBits.getZExtValue();
4664 // Certain magic vector constants (used to express things like NOT
4665 // and NEG) are passed through unmodified. This allows codegen patterns
4666 // for these operations to match. Special-purpose patterns will lower
4667 // these immediates to MOVIs if it proves necessary.
4668 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4671 // The many faces of MOVI...
4672 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4673 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4674 if (VT.getSizeInBits() == 128) {
4675 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4676 DAG.getConstant(CnstVal, MVT::i32));
4677 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4680 // Support the V64 version via subregister insertion.
4681 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4682 DAG.getConstant(CnstVal, MVT::i32));
4683 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4686 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4687 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4688 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4689 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4690 DAG.getConstant(CnstVal, MVT::i32),
4691 DAG.getConstant(0, MVT::i32));
4692 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4695 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4696 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4697 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4698 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4699 DAG.getConstant(CnstVal, MVT::i32),
4700 DAG.getConstant(8, MVT::i32));
4701 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4704 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4705 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4706 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4707 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4708 DAG.getConstant(CnstVal, MVT::i32),
4709 DAG.getConstant(16, MVT::i32));
4710 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4713 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4714 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4715 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4716 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4717 DAG.getConstant(CnstVal, MVT::i32),
4718 DAG.getConstant(24, MVT::i32));
4719 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4722 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4723 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4724 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4725 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4726 DAG.getConstant(CnstVal, MVT::i32),
4727 DAG.getConstant(0, MVT::i32));
4728 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4731 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4732 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4733 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4734 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4735 DAG.getConstant(CnstVal, MVT::i32),
4736 DAG.getConstant(8, MVT::i32));
4737 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4740 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4741 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4742 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4743 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4744 DAG.getConstant(CnstVal, MVT::i32),
4745 DAG.getConstant(264, MVT::i32));
4746 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4749 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4750 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
4751 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4752 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4753 DAG.getConstant(CnstVal, MVT::i32),
4754 DAG.getConstant(272, MVT::i32));
4755 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4758 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
4759 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
4760 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
4761 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
4762 DAG.getConstant(CnstVal, MVT::i32));
4763 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4766 // The few faces of FMOV...
4767 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
4768 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
4769 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
4770 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
4771 DAG.getConstant(CnstVal, MVT::i32));
4772 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4775 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
4776 VT.getSizeInBits() == 128) {
4777 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
4778 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
4779 DAG.getConstant(CnstVal, MVT::i32));
4780 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4783 // The many faces of MVNI...
4785 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4786 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4787 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4788 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4789 DAG.getConstant(CnstVal, MVT::i32),
4790 DAG.getConstant(0, MVT::i32));
4791 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4794 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4795 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4796 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4797 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4798 DAG.getConstant(CnstVal, MVT::i32),
4799 DAG.getConstant(8, MVT::i32));
4800 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4803 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4804 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4805 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4806 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4807 DAG.getConstant(CnstVal, MVT::i32),
4808 DAG.getConstant(16, MVT::i32));
4809 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4812 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4813 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4814 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4815 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4816 DAG.getConstant(CnstVal, MVT::i32),
4817 DAG.getConstant(24, MVT::i32));
4818 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4821 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4822 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4823 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4824 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4825 DAG.getConstant(CnstVal, MVT::i32),
4826 DAG.getConstant(0, MVT::i32));
4827 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4830 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4831 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4832 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4833 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4834 DAG.getConstant(CnstVal, MVT::i32),
4835 DAG.getConstant(8, MVT::i32));
4836 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4839 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4840 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4841 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4842 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
4843 DAG.getConstant(CnstVal, MVT::i32),
4844 DAG.getConstant(264, MVT::i32));
4845 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4848 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4849 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
4850 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4851 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
4852 DAG.getConstant(CnstVal, MVT::i32),
4853 DAG.getConstant(272, MVT::i32));
4854 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4861 CnstBits = UndefBits;
4866 // Scan through the operands to find some interesting properties we can
4868 // 1) If only one value is used, we can use a DUP, or
4869 // 2) if only the low element is not undef, we can just insert that, or
4870 // 3) if only one constant value is used (w/ some non-constant lanes),
4871 // we can splat the constant value into the whole vector then fill
4872 // in the non-constant lanes.
4873 // 4) FIXME: If different constant values are used, but we can intelligently
4874 // select the values we'll be overwriting for the non-constant
4875 // lanes such that we can directly materialize the vector
4876 // some other way (MOVI, e.g.), we can be sneaky.
4877 unsigned NumElts = VT.getVectorNumElements();
4878 bool isOnlyLowElement = true;
4879 bool usesOnlyOneValue = true;
4880 bool usesOnlyOneConstantValue = true;
4881 bool isConstant = true;
4882 unsigned NumConstantLanes = 0;
4884 SDValue ConstantValue;
4885 for (unsigned i = 0; i < NumElts; ++i) {
4886 SDValue V = Op.getOperand(i);
4887 if (V.getOpcode() == ISD::UNDEF)
4890 isOnlyLowElement = false;
4891 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4894 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
4896 if (!ConstantValue.getNode())
4898 else if (ConstantValue != V)
4899 usesOnlyOneConstantValue = false;
4902 if (!Value.getNode())
4904 else if (V != Value)
4905 usesOnlyOneValue = false;
4908 if (!Value.getNode())
4909 return DAG.getUNDEF(VT);
4911 if (isOnlyLowElement)
4912 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4914 // Use DUP for non-constant splats. For f32 constant splats, reduce to
4915 // i32 and try again.
4916 if (usesOnlyOneValue) {
4918 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4919 Value.getValueType() != VT)
4920 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
4922 // This is actually a DUPLANExx operation, which keeps everything vectory.
4924 // DUPLANE works on 128-bit vectors, widen it if necessary.
4925 SDValue Lane = Value.getOperand(1);
4926 Value = Value.getOperand(0);
4927 if (Value.getValueType().getSizeInBits() == 64)
4928 Value = WidenVector(Value, DAG);
4930 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
4931 return DAG.getNode(Opcode, dl, VT, Value, Lane);
4934 if (VT.getVectorElementType().isFloatingPoint()) {
4935 SmallVector<SDValue, 8> Ops;
4937 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4938 for (unsigned i = 0; i < NumElts; ++i)
4939 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
4940 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
4941 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4942 Val = LowerBUILD_VECTOR(Val, DAG);
4944 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4948 // If there was only one constant value used and for more than one lane,
4949 // start by splatting that value, then replace the non-constant lanes. This
4950 // is better than the default, which will perform a separate initialization
4952 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
4953 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
4954 // Now insert the non-constant lanes.
4955 for (unsigned i = 0; i < NumElts; ++i) {
4956 SDValue V = Op.getOperand(i);
4957 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
4958 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
4959 // Note that type legalization likely mucked about with the VT of the
4960 // source operand, so we may have to convert it here before inserting.
4961 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
4967 // If all elements are constants and the case above didn't get hit, fall back
4968 // to the default expansion, which will generate a load from the constant
4973 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4975 SDValue shuffle = ReconstructShuffle(Op, DAG);
4976 if (shuffle != SDValue())
4980 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4981 // know the default expansion would otherwise fall back on something even
4982 // worse. For a vector with one or two non-undef values, that's
4983 // scalar_to_vector for the elements followed by a shuffle (provided the
4984 // shuffle is valid for the target) and materialization element by element
4985 // on the stack followed by a load for everything else.
4986 if (!isConstant && !usesOnlyOneValue) {
4987 SDValue Vec = DAG.getUNDEF(VT);
4988 SDValue Op0 = Op.getOperand(0);
4989 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
4991 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
4992 // a) Avoid a RMW dependency on the full vector register, and
4993 // b) Allow the register coalescer to fold away the copy if the
4994 // value is already in an S or D register.
4995 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
4996 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
4998 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
4999 DAG.getTargetConstant(SubIdx, MVT::i32));
5000 Vec = SDValue(N, 0);
5003 for (; i < NumElts; ++i) {
5004 SDValue V = Op.getOperand(i);
5005 if (V.getOpcode() == ISD::UNDEF)
5007 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5008 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5013 // Just use the default expansion. We failed to find a better alternative.
5017 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5018 SelectionDAG &DAG) const {
5019 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5021 // Check for non-constant lane.
5022 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5025 EVT VT = Op.getOperand(0).getValueType();
5027 // Insertion/extraction are legal for V128 types.
5028 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5029 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5032 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5033 VT != MVT::v1i64 && VT != MVT::v2f32)
5036 // For V64 types, we perform insertion by expanding the value
5037 // to a V128 type and perform the insertion on that.
5039 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5040 EVT WideTy = WideVec.getValueType();
5042 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5043 Op.getOperand(1), Op.getOperand(2));
5044 // Re-narrow the resultant vector.
5045 return NarrowVector(Node, DAG);
5048 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5049 SelectionDAG &DAG) const {
5050 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5052 // Check for non-constant lane.
5053 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5056 EVT VT = Op.getOperand(0).getValueType();
5058 // Insertion/extraction are legal for V128 types.
5059 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5060 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5063 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5064 VT != MVT::v1i64 && VT != MVT::v2f32)
5067 // For V64 types, we perform extraction by expanding the value
5068 // to a V128 type and perform the extraction on that.
5070 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5071 EVT WideTy = WideVec.getValueType();
5073 EVT ExtrTy = WideTy.getVectorElementType();
5074 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5077 // For extractions, we just return the result directly.
5078 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5082 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5083 SelectionDAG &DAG) const {
5084 EVT VT = Op.getOperand(0).getValueType();
5090 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5093 unsigned Val = Cst->getZExtValue();
5095 unsigned Size = Op.getValueType().getSizeInBits();
5099 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5102 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5105 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5108 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5111 llvm_unreachable("Unexpected vector type in extract_subvector!");
5114 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5116 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5122 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5124 if (VT.getVectorNumElements() == 4 &&
5125 (VT.is128BitVector() || VT.is64BitVector())) {
5126 unsigned PFIndexes[4];
5127 for (unsigned i = 0; i != 4; ++i) {
5131 PFIndexes[i] = M[i];
5134 // Compute the index in the perfect shuffle table.
5135 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5136 PFIndexes[2] * 9 + PFIndexes[3];
5137 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5138 unsigned Cost = (PFEntry >> 30);
5145 unsigned Imm, WhichResult;
5147 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5148 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5149 isEXTMask(M, VT, ReverseVEXT, Imm) ||
5150 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5151 isTRNMask(M, VT, WhichResult) || isUZPMask(M, VT, WhichResult) ||
5152 isZIPMask(M, VT, WhichResult) ||
5153 isTRN_v_undef_Mask(M, VT, WhichResult) ||
5154 isUZP_v_undef_Mask(M, VT, WhichResult) ||
5155 isZIP_v_undef_Mask(M, VT, WhichResult));
5158 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5159 /// operand of a vector shift operation, where all the elements of the
5160 /// build_vector must have the same constant integer value.
5161 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5162 // Ignore bit_converts.
5163 while (Op.getOpcode() == ISD::BITCAST)
5164 Op = Op.getOperand(0);
5165 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5166 APInt SplatBits, SplatUndef;
5167 unsigned SplatBitSize;
5169 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5170 HasAnyUndefs, ElementBits) ||
5171 SplatBitSize > ElementBits)
5173 Cnt = SplatBits.getSExtValue();
5177 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5178 /// operand of a vector shift left operation. That value must be in the range:
5179 /// 0 <= Value < ElementBits for a left shift; or
5180 /// 0 <= Value <= ElementBits for a long left shift.
5181 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5182 assert(VT.isVector() && "vector shift count is not a vector type");
5183 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5184 if (!getVShiftImm(Op, ElementBits, Cnt))
5186 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5189 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5190 /// operand of a vector shift right operation. For a shift opcode, the value
5191 /// is positive, but for an intrinsic the value count must be negative. The
5192 /// absolute value must be in the range:
5193 /// 1 <= |Value| <= ElementBits for a right shift; or
5194 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5195 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5197 assert(VT.isVector() && "vector shift count is not a vector type");
5198 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5199 if (!getVShiftImm(Op, ElementBits, Cnt))
5203 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5206 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5207 SelectionDAG &DAG) const {
5208 EVT VT = Op.getValueType();
5212 if (!Op.getOperand(1).getValueType().isVector())
5214 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5216 switch (Op.getOpcode()) {
5218 llvm_unreachable("unexpected shift opcode");
5221 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5222 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5223 DAG.getConstant(Cnt, MVT::i32));
5224 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5225 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5226 Op.getOperand(0), Op.getOperand(1));
5229 // Right shift immediate
5230 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5233 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5234 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5235 DAG.getConstant(Cnt, MVT::i32));
5238 // Right shift register. Note, there is not a shift right register
5239 // instruction, but the shift left register instruction takes a signed
5240 // value, where negative numbers specify a right shift.
5241 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5242 : Intrinsic::arm64_neon_ushl;
5243 // negate the shift amount
5244 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5245 SDValue NegShiftLeft =
5246 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5247 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5248 return NegShiftLeft;
5254 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5255 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5256 SDLoc dl, SelectionDAG &DAG) {
5257 EVT SrcVT = LHS.getValueType();
5259 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5260 APInt CnstBits(VT.getSizeInBits(), 0);
5261 APInt UndefBits(VT.getSizeInBits(), 0);
5262 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5263 bool IsZero = IsCnst && (CnstBits == 0);
5265 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5272 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5274 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5275 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5279 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5280 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5283 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5284 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5287 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5288 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5291 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5292 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5296 // If we ignore NaNs then we can use to the MI implementation.
5300 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5301 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5311 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5313 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5314 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5318 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5319 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5322 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5323 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5326 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5327 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5330 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5331 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5333 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5335 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5338 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5339 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5341 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5343 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5347 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5348 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5349 SDValue LHS = Op.getOperand(0);
5350 SDValue RHS = Op.getOperand(1);
5353 if (LHS.getValueType().getVectorElementType().isInteger()) {
5354 assert(LHS.getValueType() == RHS.getValueType());
5355 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5356 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5360 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5361 LHS.getValueType().getVectorElementType() == MVT::f64);
5363 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5364 // clean. Some of them require two branches to implement.
5365 ARM64CC::CondCode CC1, CC2;
5366 changeFPCCToARM64CC(CC, CC1, CC2);
5368 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5370 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5371 if (!Cmp1.getNode())
5374 if (CC2 != ARM64CC::AL) {
5376 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5377 if (!Cmp2.getNode())
5380 return DAG.getNode(ISD::OR, dl, Cmp1.getValueType(), Cmp1, Cmp2);
5386 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5387 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5388 /// specified in the intrinsic calls.
5389 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5391 unsigned Intrinsic) const {
5392 switch (Intrinsic) {
5393 case Intrinsic::arm64_neon_ld2:
5394 case Intrinsic::arm64_neon_ld3:
5395 case Intrinsic::arm64_neon_ld4:
5396 case Intrinsic::arm64_neon_ld2lane:
5397 case Intrinsic::arm64_neon_ld3lane:
5398 case Intrinsic::arm64_neon_ld4lane:
5399 case Intrinsic::arm64_neon_ld2r:
5400 case Intrinsic::arm64_neon_ld3r:
5401 case Intrinsic::arm64_neon_ld4r: {
5402 Info.opc = ISD::INTRINSIC_W_CHAIN;
5403 // Conservatively set memVT to the entire set of vectors loaded.
5404 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5405 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5406 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5409 Info.vol = false; // volatile loads with NEON intrinsics not supported
5410 Info.readMem = true;
5411 Info.writeMem = false;
5414 case Intrinsic::arm64_neon_st2:
5415 case Intrinsic::arm64_neon_st3:
5416 case Intrinsic::arm64_neon_st4:
5417 case Intrinsic::arm64_neon_st2lane:
5418 case Intrinsic::arm64_neon_st3lane:
5419 case Intrinsic::arm64_neon_st4lane: {
5420 Info.opc = ISD::INTRINSIC_VOID;
5421 // Conservatively set memVT to the entire set of vectors stored.
5422 unsigned NumElts = 0;
5423 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5424 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5425 if (!ArgTy->isVectorTy())
5427 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5429 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5430 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5433 Info.vol = false; // volatile stores with NEON intrinsics not supported
5434 Info.readMem = false;
5435 Info.writeMem = true;
5438 case Intrinsic::arm64_ldaxr:
5439 case Intrinsic::arm64_ldxr: {
5440 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5441 Info.opc = ISD::INTRINSIC_W_CHAIN;
5442 Info.memVT = MVT::getVT(PtrTy->getElementType());
5443 Info.ptrVal = I.getArgOperand(0);
5445 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5447 Info.readMem = true;
5448 Info.writeMem = false;
5451 case Intrinsic::arm64_stlxr:
5452 case Intrinsic::arm64_stxr: {
5453 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5454 Info.opc = ISD::INTRINSIC_W_CHAIN;
5455 Info.memVT = MVT::getVT(PtrTy->getElementType());
5456 Info.ptrVal = I.getArgOperand(1);
5458 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5460 Info.readMem = false;
5461 Info.writeMem = true;
5464 case Intrinsic::arm64_ldaxp:
5465 case Intrinsic::arm64_ldxp: {
5466 Info.opc = ISD::INTRINSIC_W_CHAIN;
5467 Info.memVT = MVT::i128;
5468 Info.ptrVal = I.getArgOperand(0);
5472 Info.readMem = true;
5473 Info.writeMem = false;
5476 case Intrinsic::arm64_stlxp:
5477 case Intrinsic::arm64_stxp: {
5478 Info.opc = ISD::INTRINSIC_W_CHAIN;
5479 Info.memVT = MVT::i128;
5480 Info.ptrVal = I.getArgOperand(2);
5484 Info.readMem = false;
5485 Info.writeMem = true;
5495 // Truncations from 64-bit GPR to 32-bit GPR is free.
5496 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5497 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5499 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5500 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5501 if (NumBits1 <= NumBits2)
5505 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5506 if (!VT1.isInteger() || !VT2.isInteger())
5508 unsigned NumBits1 = VT1.getSizeInBits();
5509 unsigned NumBits2 = VT2.getSizeInBits();
5510 if (NumBits1 <= NumBits2)
5515 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5517 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5518 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5520 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5521 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5522 if (NumBits1 == 32 && NumBits2 == 64)
5526 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5527 if (!VT1.isInteger() || !VT2.isInteger())
5529 unsigned NumBits1 = VT1.getSizeInBits();
5530 unsigned NumBits2 = VT2.getSizeInBits();
5531 if (NumBits1 == 32 && NumBits2 == 64)
5536 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5537 EVT VT1 = Val.getValueType();
5538 if (isZExtFree(VT1, VT2)) {
5542 if (Val.getOpcode() != ISD::LOAD)
5545 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5546 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5547 VT2.isInteger() && VT1.getSizeInBits() <= 32);
5550 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5551 unsigned &RequiredAligment) const {
5552 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5554 // Cyclone supports unaligned accesses.
5555 RequiredAligment = 0;
5556 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5557 return NumBits == 32 || NumBits == 64;
5560 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5561 unsigned &RequiredAligment) const {
5562 if (!LoadedType.isSimple() ||
5563 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5565 // Cyclone supports unaligned accesses.
5566 RequiredAligment = 0;
5567 unsigned NumBits = LoadedType.getSizeInBits();
5568 return NumBits == 32 || NumBits == 64;
5571 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5572 unsigned AlignCheck) {
5573 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5574 (DstAlign == 0 || DstAlign % AlignCheck == 0));
5577 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5578 unsigned SrcAlign, bool IsMemset,
5579 bool ZeroMemset, bool MemcpyStrSrc,
5580 MachineFunction &MF) const {
5581 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5582 // instruction to materialize the v2i64 zero and one store (with restrictive
5583 // addressing mode). Just do two i64 store of zero-registers.
5585 const Function *F = MF.getFunction();
5586 if (!IsMemset && Size >= 16 &&
5587 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5588 Attribute::NoImplicitFloat) &&
5589 (memOpAlign(SrcAlign, DstAlign, 16) ||
5590 (allowsUnalignedMemoryAccesses(MVT::v2i64, 0, &Fast) && Fast)))
5593 return Size >= 8 ? MVT::i64 : MVT::i32;
5596 // 12-bit optionally shifted immediates are legal for adds.
5597 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5598 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5603 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5604 // immediates is the same as for an add or a sub.
5605 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5608 return isLegalAddImmediate(Immed);
5611 /// isLegalAddressingMode - Return true if the addressing mode represented
5612 /// by AM is legal for this target, for a load/store of the specified type.
5613 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5615 // ARM64 has five basic addressing modes:
5617 // reg + 9-bit signed offset
5618 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
5620 // reg + SIZE_IN_BYTES * reg
5622 // No global is ever allowed as a base.
5626 // No reg+reg+imm addressing.
5627 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5630 // check reg + imm case:
5631 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5632 uint64_t NumBytes = 0;
5633 if (Ty->isSized()) {
5634 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5635 NumBytes = NumBits / 8;
5636 if (!isPowerOf2_64(NumBits))
5641 int64_t Offset = AM.BaseOffs;
5643 // 9-bit signed offset
5644 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5647 // 12-bit unsigned offset
5648 unsigned shift = Log2_64(NumBytes);
5649 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5650 // Must be a multiple of NumBytes (NumBytes is a power of 2)
5651 (Offset >> shift) << shift == Offset)
5656 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5658 if (!AM.Scale || AM.Scale == 1 ||
5659 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5664 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5666 // Scaling factors are not free at all.
5667 // Operands | Rt Latency
5668 // -------------------------------------------
5670 // -------------------------------------------
5671 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
5672 // Rt, [Xn, Wm, <extend> #imm] |
5673 if (isLegalAddressingMode(AM, Ty))
5674 // Scale represents reg2 * scale, thus account for 1 if
5675 // it is not equal to 0 or 1.
5676 return AM.Scale != 0 && AM.Scale != 1;
5680 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
5681 VT = VT.getScalarType();
5686 switch (VT.getSimpleVT().SimpleTy) {
5698 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
5699 // LR is a callee-save register, but we must treat it as clobbered by any call
5700 // site. Hence we include LR in the scratch registers, which are in turn added
5701 // as implicit-defs for stackmaps and patchpoints.
5702 static const MCPhysReg ScratchRegs[] = {
5703 ARM64::X16, ARM64::X17, ARM64::LR, 0
5708 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5710 assert(Ty->isIntegerTy());
5712 unsigned BitSize = Ty->getPrimitiveSizeInBits();
5716 int64_t Val = Imm.getSExtValue();
5717 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
5720 if ((int64_t)Val < 0)
5723 Val &= (1LL << 32) - 1;
5725 unsigned LZ = countLeadingZeros((uint64_t)Val);
5726 unsigned Shift = (63 - LZ) / 16;
5727 // MOVZ is free so return true for one or fewer MOVK.
5728 return (Shift < 3) ? true : false;
5731 // Generate SUBS and CSEL for integer abs.
5732 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
5733 EVT VT = N->getValueType(0);
5735 SDValue N0 = N->getOperand(0);
5736 SDValue N1 = N->getOperand(1);
5739 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
5740 // and change it to SUB and CSEL.
5741 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
5742 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5743 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
5744 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
5745 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
5746 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
5748 // Generate SUBS & CSEL.
5750 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
5751 N0.getOperand(0), DAG.getConstant(0, VT));
5752 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
5753 DAG.getConstant(ARM64CC::PL, MVT::i32),
5754 SDValue(Cmp.getNode(), 1));
5759 // performXorCombine - Attempts to handle integer ABS.
5760 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
5761 TargetLowering::DAGCombinerInfo &DCI,
5762 const ARM64Subtarget *Subtarget) {
5763 if (DCI.isBeforeLegalizeOps())
5766 return performIntegerAbsCombine(N, DAG);
5769 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
5770 TargetLowering::DAGCombinerInfo &DCI,
5771 const ARM64Subtarget *Subtarget) {
5772 if (DCI.isBeforeLegalizeOps())
5775 // Multiplication of a power of two plus/minus one can be done more
5776 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
5777 // future CPUs have a cheaper MADD instruction, this may need to be
5778 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
5779 // 64-bit is 5 cycles, so this is always a win.
5780 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5781 APInt Value = C->getAPIntValue();
5782 EVT VT = N->getValueType(0);
5783 APInt VP1 = Value + 1;
5784 if (VP1.isPowerOf2()) {
5785 // Multiplying by one less than a power of two, replace with a shift
5787 SDValue ShiftedVal =
5788 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5789 DAG.getConstant(VP1.logBase2(), MVT::i64));
5790 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5792 APInt VM1 = Value - 1;
5793 if (VM1.isPowerOf2()) {
5794 // Multiplying by one more than a power of two, replace with a shift
5796 SDValue ShiftedVal =
5797 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5798 DAG.getConstant(VM1.logBase2(), MVT::i64));
5799 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5805 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
5806 EVT VT = N->getValueType(0);
5807 if (VT != MVT::f32 && VT != MVT::f64)
5809 // Only optimize when the source and destination types have the same width.
5810 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
5813 // If the result of an integer load is only used by an integer-to-float
5814 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
5815 // This eliminates an "integer-to-vector-move UOP and improve throughput.
5816 SDValue N0 = N->getOperand(0);
5817 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5818 // Do not change the width of a volatile load.
5819 !cast<LoadSDNode>(N0)->isVolatile()) {
5820 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5821 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
5822 LN0->getPointerInfo(), LN0->isVolatile(),
5823 LN0->isNonTemporal(), LN0->isInvariant(),
5824 LN0->getAlignment());
5826 // Make sure successors of the original load stay after it by updating them
5827 // to use the new Chain.
5828 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
5831 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
5832 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
5838 /// An EXTR instruction is made up of two shifts, ORed together. This helper
5839 /// searches for and classifies those shifts.
5840 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
5842 if (N.getOpcode() == ISD::SHL)
5844 else if (N.getOpcode() == ISD::SRL)
5849 if (!isa<ConstantSDNode>(N.getOperand(1)))
5852 ShiftAmount = N->getConstantOperandVal(1);
5853 Src = N->getOperand(0);
5857 /// EXTR instruction extracts a contiguous chunk of bits from two existing
5858 /// registers viewed as a high/low pair. This function looks for the pattern:
5859 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
5860 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
5862 static SDValue tryCombineToEXTR(SDNode *N,
5863 TargetLowering::DAGCombinerInfo &DCI) {
5864 SelectionDAG &DAG = DCI.DAG;
5866 EVT VT = N->getValueType(0);
5868 assert(N->getOpcode() == ISD::OR && "Unexpected root");
5870 if (VT != MVT::i32 && VT != MVT::i64)
5874 uint32_t ShiftLHS = 0;
5876 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
5880 uint32_t ShiftRHS = 0;
5882 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
5885 // If they're both trying to come from the high part of the register, they're
5886 // not really an EXTR.
5887 if (LHSFromHi == RHSFromHi)
5890 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
5894 std::swap(LHS, RHS);
5895 std::swap(ShiftLHS, ShiftRHS);
5898 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
5899 DAG.getConstant(ShiftRHS, MVT::i64));
5902 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
5903 const ARM64Subtarget *Subtarget) {
5904 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
5905 if (!EnableARM64ExtrGeneration)
5907 SelectionDAG &DAG = DCI.DAG;
5908 EVT VT = N->getValueType(0);
5910 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5913 SDValue Res = tryCombineToEXTR(N, DCI);
5920 static SDValue performBitcastCombine(SDNode *N,
5921 TargetLowering::DAGCombinerInfo &DCI,
5922 SelectionDAG &DAG) {
5923 // Wait 'til after everything is legalized to try this. That way we have
5924 // legal vector types and such.
5925 if (DCI.isBeforeLegalizeOps())
5928 // Remove extraneous bitcasts around an extract_subvector.
5930 // (v4i16 (bitconvert
5931 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
5933 // (extract_subvector ((v8i16 ...), (i64 4)))
5935 // Only interested in 64-bit vectors as the ultimate result.
5936 EVT VT = N->getValueType(0);
5939 if (VT.getSimpleVT().getSizeInBits() != 64)
5941 // Is the operand an extract_subvector starting at the beginning or halfway
5942 // point of the vector? A low half may also come through as an
5943 // EXTRACT_SUBREG, so look for that, too.
5944 SDValue Op0 = N->getOperand(0);
5945 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
5946 !(Op0->isMachineOpcode() &&
5947 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
5949 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
5950 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5951 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
5953 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
5954 if (idx != ARM64::dsub)
5956 // The dsub reference is equivalent to a lane zero subvector reference.
5959 // Look through the bitcast of the input to the extract.
5960 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
5962 SDValue Source = Op0->getOperand(0)->getOperand(0);
5963 // If the source type has twice the number of elements as our destination
5964 // type, we know this is an extract of the high or low half of the vector.
5965 EVT SVT = Source->getValueType(0);
5966 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
5969 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
5971 // Create the simplified form to just extract the low or high half of the
5972 // vector directly rather than bothering with the bitcasts.
5974 unsigned NumElements = VT.getVectorNumElements();
5976 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
5977 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
5979 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
5980 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
5986 static SDValue performConcatVectorsCombine(SDNode *N,
5987 TargetLowering::DAGCombinerInfo &DCI,
5988 SelectionDAG &DAG) {
5989 // Wait 'til after everything is legalized to try this. That way we have
5990 // legal vector types and such.
5991 if (DCI.isBeforeLegalizeOps())
5995 EVT VT = N->getValueType(0);
5997 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
5998 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
5999 // canonicalise to that.
6000 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6001 assert(VT.getVectorElementType().getSizeInBits() == 64);
6002 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6003 WidenVector(N->getOperand(0), DAG),
6004 DAG.getConstant(0, MVT::i64));
6007 // Canonicalise concat_vectors so that the right-hand vector has as few
6008 // bit-casts as possible before its real operation. The primary matching
6009 // destination for these operations will be the narrowing "2" instructions,
6010 // which depend on the operation being performed on this right-hand vector.
6012 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6014 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6016 SDValue Op1 = N->getOperand(1);
6017 if (Op1->getOpcode() != ISD::BITCAST)
6019 SDValue RHS = Op1->getOperand(0);
6020 MVT RHSTy = RHS.getValueType().getSimpleVT();
6021 // If the RHS is not a vector, this is not the pattern we're looking for.
6022 if (!RHSTy.isVector())
6025 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6027 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6028 RHSTy.getVectorNumElements() * 2);
6030 ISD::BITCAST, dl, VT,
6031 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6032 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6035 static SDValue tryCombineFixedPointConvert(SDNode *N,
6036 TargetLowering::DAGCombinerInfo &DCI,
6037 SelectionDAG &DAG) {
6038 // Wait 'til after everything is legalized to try this. That way we have
6039 // legal vector types and such.
6040 if (DCI.isBeforeLegalizeOps())
6042 // Transform a scalar conversion of a value from a lane extract into a
6043 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6044 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6045 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6047 // The second form interacts better with instruction selection and the
6048 // register allocator to avoid cross-class register copies that aren't
6049 // coalescable due to a lane reference.
6051 // Check the operand and see if it originates from a lane extract.
6052 SDValue Op1 = N->getOperand(1);
6053 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6054 // Yep, no additional predication needed. Perform the transform.
6055 SDValue IID = N->getOperand(0);
6056 SDValue Shift = N->getOperand(2);
6057 SDValue Vec = Op1.getOperand(0);
6058 SDValue Lane = Op1.getOperand(1);
6059 EVT ResTy = N->getValueType(0);
6063 // The vector width should be 128 bits by the time we get here, even
6064 // if it started as 64 bits (the extract_vector handling will have
6066 assert(Vec.getValueType().getSizeInBits() == 128 &&
6067 "unexpected vector size on extract_vector_elt!");
6068 if (Vec.getValueType() == MVT::v4i32)
6069 VecResTy = MVT::v4f32;
6070 else if (Vec.getValueType() == MVT::v2i64)
6071 VecResTy = MVT::v2f64;
6073 assert(0 && "unexpected vector type!");
6076 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6077 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6082 // AArch64 high-vector "long" operations are formed by performing the non-high
6083 // version on an extract_subvector of each operand which gets the high half:
6085 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6087 // However, there are cases which don't have an extract_high explicitly, but
6088 // have another operation that can be made compatible with one for free. For
6091 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6093 // This routine does the actual conversion of such DUPs, once outer routines
6094 // have determined that everything else is in order.
6095 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6096 // We can handle most types of duplicate, but the lane ones have an extra
6097 // operand saying *which* lane, so we need to know.
6099 switch (N.getOpcode()) {
6103 case ARM64ISD::DUPLANE8:
6104 case ARM64ISD::DUPLANE16:
6105 case ARM64ISD::DUPLANE32:
6106 case ARM64ISD::DUPLANE64:
6113 MVT NarrowTy = N.getSimpleValueType();
6114 if (!NarrowTy.is64BitVector())
6117 MVT ElementTy = NarrowTy.getVectorElementType();
6118 unsigned NumElems = NarrowTy.getVectorNumElements();
6119 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6123 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6126 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6128 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6129 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6132 static bool isEssentiallyExtractSubvector(SDValue N) {
6133 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6136 return N.getOpcode() == ISD::BITCAST &&
6137 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6140 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6141 struct GenericSetCCInfo {
6142 const SDValue *Opnd0;
6143 const SDValue *Opnd1;
6147 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6148 struct ARM64SetCCInfo {
6150 ARM64CC::CondCode CC;
6153 /// \brief Helper structure to keep track of SetCC information.
6155 GenericSetCCInfo Generic;
6156 ARM64SetCCInfo ARM64;
6159 /// \brief Helper structure to be able to read SetCC information.
6160 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6161 /// a GenericSetCCInfo.
6162 struct SetCCInfoAndKind {
6167 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6169 /// ARM64 lowered one.
6170 /// \p SetCCInfo is filled accordingly.
6171 /// \post SetCCInfo is meanginfull only when this function returns true.
6172 /// \return True when Op is a kind of SET_CC operation.
6173 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6174 // If this is a setcc, this is straight forward.
6175 if (Op.getOpcode() == ISD::SETCC) {
6176 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6177 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6178 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6179 SetCCInfo.IsARM64 = false;
6182 // Otherwise, check if this is a matching csel instruction.
6186 if (Op.getOpcode() != ARM64ISD::CSEL)
6188 // Set the information about the operands.
6189 // TODO: we want the operands of the Cmp not the csel
6190 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6191 SetCCInfo.IsARM64 = true;
6192 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6193 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6195 // Check that the operands matches the constraints:
6196 // (1) Both operands must be constants.
6197 // (2) One must be 1 and the other must be 0.
6198 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6199 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6202 if (!TValue || !FValue)
6206 if (!TValue->isOne()) {
6207 // Update the comparison when we are interested in !cc.
6208 std::swap(TValue, FValue);
6209 SetCCInfo.Info.ARM64.CC =
6210 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6212 return TValue->isOne() && FValue->isNullValue();
6215 // The folding we want to perform is:
6216 // (add x, (setcc cc ...) )
6218 // (csel x, (add x, 1), !cc ...)
6220 // The latter will get matched to a CSINC instruction.
6221 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6222 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6223 SDValue LHS = Op->getOperand(0);
6224 SDValue RHS = Op->getOperand(1);
6225 SetCCInfoAndKind InfoAndKind;
6227 // If neither operand is a SET_CC, give up.
6228 if (!isSetCC(LHS, InfoAndKind)) {
6229 std::swap(LHS, RHS);
6230 if (!isSetCC(LHS, InfoAndKind))
6234 // FIXME: This could be generatized to work for FP comparisons.
6235 EVT CmpVT = InfoAndKind.IsARM64
6236 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6237 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6238 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6244 if (InfoAndKind.IsARM64) {
6245 CCVal = DAG.getConstant(
6246 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6247 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6249 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6250 *InfoAndKind.Info.Generic.Opnd1,
6251 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6254 EVT VT = Op->getValueType(0);
6255 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6256 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6259 // The basic add/sub long vector instructions have variants with "2" on the end
6260 // which act on the high-half of their inputs. They are normally matched by
6263 // (add (zeroext (extract_high LHS)),
6264 // (zeroext (extract_high RHS)))
6265 // -> uaddl2 vD, vN, vM
6267 // However, if one of the extracts is something like a duplicate, this
6268 // instruction can still be used profitably. This function puts the DAG into a
6269 // more appropriate form for those patterns to trigger.
6270 static SDValue performAddSubLongCombine(SDNode *N,
6271 TargetLowering::DAGCombinerInfo &DCI,
6272 SelectionDAG &DAG) {
6273 if (DCI.isBeforeLegalizeOps())
6276 MVT VT = N->getSimpleValueType(0);
6277 if (!VT.is128BitVector()) {
6278 if (N->getOpcode() == ISD::ADD)
6279 return performSetccAddFolding(N, DAG);
6283 // Make sure both branches are extended in the same way.
6284 SDValue LHS = N->getOperand(0);
6285 SDValue RHS = N->getOperand(1);
6286 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6287 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6288 LHS.getOpcode() != RHS.getOpcode())
6291 unsigned ExtType = LHS.getOpcode();
6293 // It's not worth doing if at least one of the inputs isn't already an
6294 // extract, but we don't know which it'll be so we have to try both.
6295 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6296 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6300 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6301 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6302 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6306 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6309 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6312 // Massage DAGs which we can use the high-half "long" operations on into
6313 // something isel will recognize better. E.g.
6315 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6316 // (arm64_neon_umull (extract_high (v2i64 vec)))
6317 // (extract_high (v2i64 (dup128 scalar)))))
6319 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6320 TargetLowering::DAGCombinerInfo &DCI,
6321 SelectionDAG &DAG) {
6322 if (DCI.isBeforeLegalizeOps())
6325 SDValue LHS = N->getOperand(1);
6326 SDValue RHS = N->getOperand(2);
6327 assert(LHS.getValueType().is64BitVector() &&
6328 RHS.getValueType().is64BitVector() &&
6329 "unexpected shape for long operation");
6331 // Either node could be a DUP, but it's not worth doing both of them (you'd
6332 // just as well use the non-high version) so look for a corresponding extract
6333 // operation on the other "wing".
6334 if (isEssentiallyExtractSubvector(LHS)) {
6335 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6338 } else if (isEssentiallyExtractSubvector(RHS)) {
6339 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6344 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6345 N->getOperand(0), LHS, RHS);
6348 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6349 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6350 unsigned ElemBits = ElemTy.getSizeInBits();
6352 int64_t ShiftAmount;
6353 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6354 APInt SplatValue, SplatUndef;
6355 unsigned SplatBitSize;
6357 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6358 HasAnyUndefs, ElemBits) ||
6359 SplatBitSize != ElemBits)
6362 ShiftAmount = SplatValue.getSExtValue();
6363 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6364 ShiftAmount = CVN->getSExtValue();
6372 llvm_unreachable("Unknown shift intrinsic");
6373 case Intrinsic::arm64_neon_sqshl:
6374 Opcode = ARM64ISD::SQSHL_I;
6375 IsRightShift = false;
6377 case Intrinsic::arm64_neon_uqshl:
6378 Opcode = ARM64ISD::UQSHL_I;
6379 IsRightShift = false;
6381 case Intrinsic::arm64_neon_srshl:
6382 Opcode = ARM64ISD::SRSHR_I;
6383 IsRightShift = true;
6385 case Intrinsic::arm64_neon_urshl:
6386 Opcode = ARM64ISD::URSHR_I;
6387 IsRightShift = true;
6389 case Intrinsic::arm64_neon_sqshlu:
6390 Opcode = ARM64ISD::SQSHLU_I;
6391 IsRightShift = false;
6395 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6396 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6397 DAG.getConstant(-ShiftAmount, MVT::i32));
6398 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6399 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6400 DAG.getConstant(ShiftAmount, MVT::i32));
6405 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6406 // the intrinsics must be legal and take an i32, this means there's almost
6407 // certainly going to be a zext in the DAG which we can eliminate.
6408 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6409 SDValue AndN = N->getOperand(2);
6410 if (AndN.getOpcode() != ISD::AND)
6413 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6414 if (!CMask || CMask->getZExtValue() != Mask)
6417 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6418 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6421 static SDValue performIntrinsicCombine(SDNode *N,
6422 TargetLowering::DAGCombinerInfo &DCI,
6423 const ARM64Subtarget *Subtarget) {
6424 SelectionDAG &DAG = DCI.DAG;
6425 unsigned IID = getIntrinsicID(N);
6429 case Intrinsic::arm64_neon_vcvtfxs2fp:
6430 case Intrinsic::arm64_neon_vcvtfxu2fp:
6431 return tryCombineFixedPointConvert(N, DCI, DAG);
6433 case Intrinsic::arm64_neon_fmax:
6434 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6435 N->getOperand(1), N->getOperand(2));
6436 case Intrinsic::arm64_neon_fmin:
6437 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6438 N->getOperand(1), N->getOperand(2));
6439 case Intrinsic::arm64_neon_smull:
6440 case Intrinsic::arm64_neon_umull:
6441 case Intrinsic::arm64_neon_pmull:
6442 case Intrinsic::arm64_neon_sqdmull:
6443 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6444 case Intrinsic::arm64_neon_sqshl:
6445 case Intrinsic::arm64_neon_uqshl:
6446 case Intrinsic::arm64_neon_sqshlu:
6447 case Intrinsic::arm64_neon_srshl:
6448 case Intrinsic::arm64_neon_urshl:
6449 return tryCombineShiftImm(IID, N, DAG);
6450 case Intrinsic::arm64_crc32b:
6451 case Intrinsic::arm64_crc32cb:
6452 return tryCombineCRC32(0xff, N, DAG);
6453 case Intrinsic::arm64_crc32h:
6454 case Intrinsic::arm64_crc32ch:
6455 return tryCombineCRC32(0xffff, N, DAG);
6460 static SDValue performExtendCombine(SDNode *N,
6461 TargetLowering::DAGCombinerInfo &DCI,
6462 SelectionDAG &DAG) {
6463 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6464 // we can convert that DUP into another extract_high (of a bigger DUP), which
6465 // helps the backend to decide that an sabdl2 would be useful, saving a real
6466 // extract_high operation.
6467 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6468 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6469 SDNode *ABDNode = N->getOperand(0).getNode();
6470 unsigned IID = getIntrinsicID(ABDNode);
6471 if (IID == Intrinsic::arm64_neon_sabd ||
6472 IID == Intrinsic::arm64_neon_uabd) {
6473 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6474 if (!NewABD.getNode())
6477 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6482 // This is effectively a custom type legalization for ARM64.
6484 // Type legalization will split an extend of a small, legal, type to a larger
6485 // illegal type by first splitting the destination type, often creating
6486 // illegal source types, which then get legalized in isel-confusing ways,
6487 // leading to really terrible codegen. E.g.,
6488 // %result = v8i32 sext v8i8 %value
6490 // %losrc = extract_subreg %value, ...
6491 // %hisrc = extract_subreg %value, ...
6492 // %lo = v4i32 sext v4i8 %losrc
6493 // %hi = v4i32 sext v4i8 %hisrc
6494 // Things go rapidly downhill from there.
6496 // For ARM64, the [sz]ext vector instructions can only go up one element
6497 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6498 // take two instructions.
6500 // This implies that the most efficient way to do the extend from v8i8
6501 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6502 // the normal splitting to happen for the v8i16->v8i32.
6504 // This is pre-legalization to catch some cases where the default
6505 // type legalization will create ill-tempered code.
6506 if (!DCI.isBeforeLegalizeOps())
6509 // We're only interested in cleaning things up for non-legal vector types
6510 // here. If both the source and destination are legal, things will just
6511 // work naturally without any fiddling.
6512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6513 EVT ResVT = N->getValueType(0);
6514 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6516 // If the vector type isn't a simple VT, it's beyond the scope of what
6517 // we're worried about here. Let legalization do its thing and hope for
6519 if (!ResVT.isSimple())
6522 SDValue Src = N->getOperand(0);
6523 MVT SrcVT = Src->getValueType(0).getSimpleVT();
6524 // If the source VT is a 64-bit vector, we can play games and get the
6525 // better results we want.
6526 if (SrcVT.getSizeInBits() != 64)
6529 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6530 unsigned ElementCount = SrcVT.getVectorNumElements();
6531 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6533 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6535 // Now split the rest of the operation into two halves, each with a 64
6539 unsigned NumElements = ResVT.getVectorNumElements();
6540 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6541 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6542 ResVT.getVectorElementType(), NumElements / 2);
6544 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6545 LoVT.getVectorNumElements());
6546 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6547 DAG.getIntPtrConstant(0));
6548 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6549 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6550 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6551 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6553 // Now combine the parts back together so we still have a single result
6554 // like the combiner expects.
6555 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6558 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6559 /// value. The load store optimizer pass will merge them to store pair stores.
6560 /// This has better performance than a splat of the scalar followed by a split
6561 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6562 /// followed by an ext.b and two stores.
6563 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6564 SDValue StVal = St->getValue();
6565 EVT VT = StVal.getValueType();
6567 // Don't replace floating point stores, they possibly won't be transformed to
6568 // stp because of the store pair suppress pass.
6569 if (VT.isFloatingPoint())
6572 // Check for insert vector elements.
6573 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6576 // We can express a splat as store pair(s) for 2 or 4 elements.
6577 unsigned NumVecElts = VT.getVectorNumElements();
6578 if (NumVecElts != 4 && NumVecElts != 2)
6580 SDValue SplatVal = StVal.getOperand(1);
6581 unsigned RemainInsertElts = NumVecElts - 1;
6583 // Check that this is a splat.
6584 while (--RemainInsertElts) {
6585 SDValue NextInsertElt = StVal.getOperand(0);
6586 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6588 if (NextInsertElt.getOperand(1) != SplatVal)
6590 StVal = NextInsertElt;
6592 unsigned OrigAlignment = St->getAlignment();
6593 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6594 unsigned Alignment = std::min(OrigAlignment, EltOffset);
6596 // Create scalar stores. This is at least as good as the code sequence for a
6597 // split unaligned store wich is a dup.s, ext.b, and two stores.
6598 // Most of the time the three stores should be replaced by store pair
6599 // instructions (stp).
6601 SDValue BasePtr = St->getBasePtr();
6603 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6604 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6606 unsigned Offset = EltOffset;
6607 while (--NumVecElts) {
6608 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6609 DAG.getConstant(Offset, MVT::i64));
6610 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6611 St->getPointerInfo(), St->isVolatile(),
6612 St->isNonTemporal(), Alignment);
6613 Offset += EltOffset;
6618 static SDValue performSTORECombine(SDNode *N,
6619 TargetLowering::DAGCombinerInfo &DCI,
6621 const ARM64Subtarget *Subtarget) {
6622 if (!DCI.isBeforeLegalize())
6625 StoreSDNode *S = cast<StoreSDNode>(N);
6626 if (S->isVolatile())
6629 // Cyclone has bad performance on unaligned 16B stores when crossing line and
6630 // page boundries. We want to split such stores.
6631 if (!Subtarget->isCyclone())
6634 // Don't split at Oz.
6635 MachineFunction &MF = DAG.getMachineFunction();
6636 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
6637 AttributeSet::FunctionIndex, Attribute::MinSize);
6641 SDValue StVal = S->getValue();
6642 EVT VT = StVal.getValueType();
6644 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
6645 // those up regresses performance on micro-benchmarks and olden/bh.
6646 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
6649 // Split unaligned 16B stores. They are terrible for performance.
6650 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
6651 // extensions can use this to mark that it does not want splitting to happen
6652 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
6653 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
6654 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
6655 S->getAlignment() <= 2)
6658 // If we get a splat of a scalar convert this vector store to a store of
6659 // scalars. They will be merged into store pairs thereby removing two
6661 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
6662 if (ReplacedSplat != SDValue())
6663 return ReplacedSplat;
6666 unsigned NumElts = VT.getVectorNumElements() / 2;
6667 // Split VT into two.
6669 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
6670 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6671 DAG.getIntPtrConstant(0));
6672 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6673 DAG.getIntPtrConstant(NumElts));
6674 SDValue BasePtr = S->getBasePtr();
6676 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
6677 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
6678 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6679 DAG.getConstant(8, MVT::i64));
6680 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
6681 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
6685 // Optimize compare with zero and branch.
6686 static SDValue performBRCONDCombine(SDNode *N,
6687 TargetLowering::DAGCombinerInfo &DCI,
6688 SelectionDAG &DAG) {
6689 SDValue Chain = N->getOperand(0);
6690 SDValue Dest = N->getOperand(1);
6691 SDValue CCVal = N->getOperand(2);
6692 SDValue Cmp = N->getOperand(3);
6694 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
6695 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
6696 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
6699 unsigned CmpOpc = Cmp.getOpcode();
6700 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
6703 // Only attempt folding if there is only one use of the flag and no use of the
6705 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
6708 SDValue LHS = Cmp.getOperand(0);
6709 SDValue RHS = Cmp.getOperand(1);
6711 assert(LHS.getValueType() == RHS.getValueType() &&
6712 "Expected the value type to be the same for both operands!");
6713 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
6716 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
6717 std::swap(LHS, RHS);
6719 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
6722 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
6723 LHS.getOpcode() == ISD::SRL)
6726 // Fold the compare into the branch instruction.
6728 if (CC == ARM64CC::EQ)
6729 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6731 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6733 // Do not add new nodes to DAG combiner worklist.
6734 DCI.CombineTo(N, BR, false);
6739 // vselect (v1i1 setcc) ->
6740 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
6741 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
6742 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
6744 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
6745 SDValue N0 = N->getOperand(0);
6746 EVT CCVT = N0.getValueType();
6748 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
6749 CCVT.getVectorElementType() != MVT::i1)
6752 EVT ResVT = N->getValueType(0);
6753 EVT CmpVT = N0.getOperand(0).getValueType();
6754 // Only combine when the result type is of the same size as the compared
6756 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
6759 SDValue IfTrue = N->getOperand(1);
6760 SDValue IfFalse = N->getOperand(2);
6762 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
6763 N0.getOperand(0), N0.getOperand(1),
6764 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6765 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
6769 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
6770 DAGCombinerInfo &DCI) const {
6771 SelectionDAG &DAG = DCI.DAG;
6772 switch (N->getOpcode()) {
6777 return performAddSubLongCombine(N, DCI, DAG);
6779 return performXorCombine(N, DAG, DCI, Subtarget);
6781 return performMulCombine(N, DAG, DCI, Subtarget);
6782 case ISD::SINT_TO_FP:
6783 case ISD::UINT_TO_FP:
6784 return performIntToFpCombine(N, DAG);
6786 return performORCombine(N, DCI, Subtarget);
6787 case ISD::INTRINSIC_WO_CHAIN:
6788 return performIntrinsicCombine(N, DCI, Subtarget);
6789 case ISD::ANY_EXTEND:
6790 case ISD::ZERO_EXTEND:
6791 case ISD::SIGN_EXTEND:
6792 return performExtendCombine(N, DCI, DAG);
6794 return performBitcastCombine(N, DCI, DAG);
6795 case ISD::CONCAT_VECTORS:
6796 return performConcatVectorsCombine(N, DCI, DAG);
6798 return performVSelectCombine(N, DCI.DAG);
6800 return performSTORECombine(N, DCI, DAG, Subtarget);
6801 case ARM64ISD::BRCOND:
6802 return performBRCONDCombine(N, DCI, DAG);
6807 // Check if the return value is used as only a return value, as otherwise
6808 // we can't perform a tail-call. In particular, we need to check for
6809 // target ISD nodes that are returns and any other "odd" constructs
6810 // that the generic analysis code won't necessarily catch.
6811 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
6812 if (N->getNumValues() != 1)
6814 if (!N->hasNUsesOfValue(1, 0))
6817 SDValue TCChain = Chain;
6818 SDNode *Copy = *N->use_begin();
6819 if (Copy->getOpcode() == ISD::CopyToReg) {
6820 // If the copy has a glue operand, we conservatively assume it isn't safe to
6821 // perform a tail call.
6822 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
6825 TCChain = Copy->getOperand(0);
6826 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
6829 bool HasRet = false;
6830 for (SDNode *Node : Copy->uses()) {
6831 if (Node->getOpcode() != ARM64ISD::RET_FLAG)
6843 // Return whether the an instruction can potentially be optimized to a tail
6844 // call. This will cause the optimizers to attempt to move, or duplicate,
6845 // return instructions to help enable tail call optimizations for this
6847 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
6848 if (!EnableARM64TailCalls)
6851 if (!CI->isTailCall())
6857 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
6859 ISD::MemIndexedMode &AM,
6861 SelectionDAG &DAG) const {
6862 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
6865 Base = Op->getOperand(0);
6866 // All of the indexed addressing mode instructions take a signed
6867 // 9 bit immediate offset.
6868 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
6869 int64_t RHSC = (int64_t)RHS->getZExtValue();
6870 if (RHSC >= 256 || RHSC <= -256)
6872 IsInc = (Op->getOpcode() == ISD::ADD);
6873 Offset = Op->getOperand(1);
6879 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
6881 ISD::MemIndexedMode &AM,
6882 SelectionDAG &DAG) const {
6885 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6886 VT = LD->getMemoryVT();
6887 Ptr = LD->getBasePtr();
6888 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6889 VT = ST->getMemoryVT();
6890 Ptr = ST->getBasePtr();
6895 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
6897 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
6901 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
6904 ISD::MemIndexedMode &AM,
6905 SelectionDAG &DAG) const {
6908 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6909 VT = LD->getMemoryVT();
6910 Ptr = LD->getBasePtr();
6911 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6912 VT = ST->getMemoryVT();
6913 Ptr = ST->getBasePtr();
6918 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
6920 // Post-indexing updates the base, so it's not a valid transform
6921 // if that's not the same as the load's pointer.
6924 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
6928 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
6929 SmallVectorImpl<SDValue> &Results,
6930 SelectionDAG &DAG) const {
6931 switch (N->getOpcode()) {
6933 llvm_unreachable("Don't know how to custom expand this");
6934 case ISD::FP_TO_UINT:
6935 case ISD::FP_TO_SINT:
6936 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
6937 // Let normal code take care of it by not adding anything to Results.
6942 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
6943 // Loads and stores less than 128-bits are already atomic; ones above that
6944 // are doomed anyway, so defer to the default libcall and blame the OS when
6946 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
6947 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
6948 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
6949 return LI->getType()->getPrimitiveSizeInBits() == 128;
6951 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
6952 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
6955 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
6956 AtomicOrdering Ord) const {
6957 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6958 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
6960 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
6962 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
6963 // intrinsic must return {i64, i64} and we have to recombine them into a
6964 // single i128 here.
6965 if (ValTy->getPrimitiveSizeInBits() == 128) {
6967 IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
6968 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
6970 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
6971 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
6973 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
6974 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
6975 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
6976 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
6977 return Builder.CreateOr(
6978 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
6981 Type *Tys[] = { Addr->getType() };
6983 IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
6984 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
6986 return Builder.CreateTruncOrBitCast(
6987 Builder.CreateCall(Ldxr, Addr),
6988 cast<PointerType>(Addr->getType())->getElementType());
6991 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
6992 Value *Val, Value *Addr,
6993 AtomicOrdering Ord) const {
6994 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6996 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
6998 // Since the intrinsics must have legal type, the i128 intrinsics take two
6999 // parameters: "i64, i64". We must marshal Val into the appropriate form
7001 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7003 IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7004 Function *Stxr = Intrinsic::getDeclaration(M, Int);
7005 Type *Int64Ty = Type::getInt64Ty(M->getContext());
7007 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7008 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7009 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7010 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7014 IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7015 Type *Tys[] = { Addr->getType() };
7016 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7018 return Builder.CreateCall2(
7019 Stxr, Builder.CreateZExtOrBitCast(
7020 Val, Stxr->getFunctionType()->getParamType(0)),