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::BSL: return "ARM64ISD::BSL";
639 case ARM64ISD::NEG: return "ARM64ISD::NEG";
640 case ARM64ISD::EXTR: return "ARM64ISD::EXTR";
641 case ARM64ISD::ZIP1: return "ARM64ISD::ZIP1";
642 case ARM64ISD::ZIP2: return "ARM64ISD::ZIP2";
643 case ARM64ISD::UZP1: return "ARM64ISD::UZP1";
644 case ARM64ISD::UZP2: return "ARM64ISD::UZP2";
645 case ARM64ISD::TRN1: return "ARM64ISD::TRN1";
646 case ARM64ISD::TRN2: return "ARM64ISD::TRN2";
647 case ARM64ISD::REV16: return "ARM64ISD::REV16";
648 case ARM64ISD::REV32: return "ARM64ISD::REV32";
649 case ARM64ISD::REV64: return "ARM64ISD::REV64";
650 case ARM64ISD::EXT: return "ARM64ISD::EXT";
651 case ARM64ISD::VSHL: return "ARM64ISD::VSHL";
652 case ARM64ISD::VLSHR: return "ARM64ISD::VLSHR";
653 case ARM64ISD::VASHR: return "ARM64ISD::VASHR";
654 case ARM64ISD::CMEQ: return "ARM64ISD::CMEQ";
655 case ARM64ISD::CMGE: return "ARM64ISD::CMGE";
656 case ARM64ISD::CMGT: return "ARM64ISD::CMGT";
657 case ARM64ISD::CMHI: return "ARM64ISD::CMHI";
658 case ARM64ISD::CMHS: return "ARM64ISD::CMHS";
659 case ARM64ISD::FCMEQ: return "ARM64ISD::FCMEQ";
660 case ARM64ISD::FCMGE: return "ARM64ISD::FCMGE";
661 case ARM64ISD::FCMGT: return "ARM64ISD::FCMGT";
662 case ARM64ISD::CMEQz: return "ARM64ISD::CMEQz";
663 case ARM64ISD::CMGEz: return "ARM64ISD::CMGEz";
664 case ARM64ISD::CMGTz: return "ARM64ISD::CMGTz";
665 case ARM64ISD::CMLEz: return "ARM64ISD::CMLEz";
666 case ARM64ISD::CMLTz: return "ARM64ISD::CMLTz";
667 case ARM64ISD::FCMEQz: return "ARM64ISD::FCMEQz";
668 case ARM64ISD::FCMGEz: return "ARM64ISD::FCMGEz";
669 case ARM64ISD::FCMGTz: return "ARM64ISD::FCMGTz";
670 case ARM64ISD::FCMLEz: return "ARM64ISD::FCMLEz";
671 case ARM64ISD::FCMLTz: return "ARM64ISD::FCMLTz";
672 case ARM64ISD::NOT: return "ARM64ISD::NOT";
673 case ARM64ISD::BIT: return "ARM64ISD::BIT";
674 case ARM64ISD::CBZ: return "ARM64ISD::CBZ";
675 case ARM64ISD::CBNZ: return "ARM64ISD::CBNZ";
676 case ARM64ISD::TBZ: return "ARM64ISD::TBZ";
677 case ARM64ISD::TBNZ: return "ARM64ISD::TBNZ";
678 case ARM64ISD::TC_RETURN: return "ARM64ISD::TC_RETURN";
679 case ARM64ISD::SITOF: return "ARM64ISD::SITOF";
680 case ARM64ISD::UITOF: return "ARM64ISD::UITOF";
681 case ARM64ISD::SQSHL_I: return "ARM64ISD::SQSHL_I";
682 case ARM64ISD::UQSHL_I: return "ARM64ISD::UQSHL_I";
683 case ARM64ISD::SRSHR_I: return "ARM64ISD::SRSHR_I";
684 case ARM64ISD::URSHR_I: return "ARM64ISD::URSHR_I";
685 case ARM64ISD::SQSHLU_I: return "ARM64ISD::SQSHLU_I";
686 case ARM64ISD::WrapperLarge: return "ARM64ISD::WrapperLarge";
691 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
692 MachineBasicBlock *MBB) const {
693 // We materialise the F128CSEL pseudo-instruction as some control flow and a
697 // [... previous instrs leading to comparison ...]
703 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
705 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
706 MachineFunction *MF = MBB->getParent();
707 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
708 DebugLoc DL = MI->getDebugLoc();
709 MachineFunction::iterator It = MBB;
712 unsigned DestReg = MI->getOperand(0).getReg();
713 unsigned IfTrueReg = MI->getOperand(1).getReg();
714 unsigned IfFalseReg = MI->getOperand(2).getReg();
715 unsigned CondCode = MI->getOperand(3).getImm();
716 bool CPSRKilled = MI->getOperand(4).isKill();
718 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
719 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
720 MF->insert(It, TrueBB);
721 MF->insert(It, EndBB);
723 // Transfer rest of current basic-block to EndBB
724 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
726 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
728 BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
729 BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
730 MBB->addSuccessor(TrueBB);
731 MBB->addSuccessor(EndBB);
733 // TrueBB falls through to the end.
734 TrueBB->addSuccessor(EndBB);
737 TrueBB->addLiveIn(ARM64::CPSR);
738 EndBB->addLiveIn(ARM64::CPSR);
741 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
747 MI->eraseFromParent();
752 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
753 MachineBasicBlock *BB) const {
754 switch (MI->getOpcode()) {
759 assert(0 && "Unexpected instruction for custom inserter!");
762 case ARM64::F128CSEL:
763 return EmitF128CSEL(MI, BB);
765 case TargetOpcode::STACKMAP:
766 case TargetOpcode::PATCHPOINT:
767 return emitPatchPoint(MI, BB);
769 llvm_unreachable("Unexpected instruction for custom inserter!");
772 //===----------------------------------------------------------------------===//
773 // ARM64 Lowering private implementation.
774 //===----------------------------------------------------------------------===//
776 //===----------------------------------------------------------------------===//
778 //===----------------------------------------------------------------------===//
780 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
781 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
784 llvm_unreachable("Unknown condition code!");
808 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
809 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
810 ARM64CC::CondCode &CondCode2) {
811 CondCode2 = ARM64CC::AL;
814 llvm_unreachable("Unknown FP condition!");
817 CondCode = ARM64CC::EQ;
821 CondCode = ARM64CC::GT;
825 CondCode = ARM64CC::GE;
828 CondCode = ARM64CC::MI;
831 CondCode = ARM64CC::LS;
834 CondCode = ARM64CC::MI;
835 CondCode2 = ARM64CC::GT;
838 CondCode = ARM64CC::VC;
841 CondCode = ARM64CC::VS;
844 CondCode = ARM64CC::EQ;
845 CondCode2 = ARM64CC::VS;
848 CondCode = ARM64CC::HI;
851 CondCode = ARM64CC::PL;
855 CondCode = ARM64CC::LT;
859 CondCode = ARM64CC::LE;
863 CondCode = ARM64CC::NE;
868 /// changeVectorFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC
869 /// usable with the vector instructions. Fewer operations are available without
870 /// a real NZCV register, so we have to use less efficient combinations to get
872 static void changeVectorFPCCToARM64CC(ISD::CondCode CC,
873 ARM64CC::CondCode &CondCode,
874 ARM64CC::CondCode &CondCode2,
879 // Mostly the scalar mappings work fine.
880 changeFPCCToARM64CC(CC, CondCode, CondCode2);
883 Invert = true; // Fallthrough
885 CondCode = ARM64CC::MI;
886 CondCode2 = ARM64CC::GE;
893 // All of the compare-mask comparisons are ordered, but we can switch
894 // between the two by a double inversion. E.g. ULE == !OGT.
896 changeFPCCToARM64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
901 static bool isLegalArithImmed(uint64_t C) {
902 // Matches ARM64DAGToDAGISel::SelectArithImmed().
903 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
906 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
907 SDLoc dl, SelectionDAG &DAG) {
908 EVT VT = LHS.getValueType();
910 if (VT.isFloatingPoint())
911 return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
913 // The CMP instruction is just an alias for SUBS, and representing it as
914 // SUBS means that it's possible to get CSE with subtract operations.
915 // A later phase can perform the optimization of setting the destination
916 // register to WZR/XZR if it ends up being unused.
918 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on the
919 // grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags can be
920 // set differently by this operation. It comes down to whether "SInt(~op2)+1
921 // == SInt(~op2+1)" (and the same for UInt). If they are then everything is
922 // fine. If not then the optimization is wrong. Thus general comparisons are
923 // only valid if op2 != 0.
925 // So, finally, the only LLVM-native comparisons that don't mention C and V
926 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in the
927 // absence of information about op2.
928 unsigned Opcode = ARM64ISD::SUBS;
929 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
930 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
931 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
932 Opcode = ARM64ISD::ADDS;
933 RHS = RHS.getOperand(1);
936 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
940 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
941 SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
942 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
943 EVT VT = RHS.getValueType();
944 uint64_t C = RHSC->getZExtValue();
945 if (!isLegalArithImmed(C)) {
946 // Constant does not fit, try adjusting it by one?
952 if ((VT == MVT::i32 && C != 0x80000000 &&
953 isLegalArithImmed((uint32_t)(C - 1))) ||
954 (VT == MVT::i64 && C != 0x80000000ULL &&
955 isLegalArithImmed(C - 1ULL))) {
956 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
957 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
958 RHS = DAG.getConstant(C, VT);
963 if ((VT == MVT::i32 && C != 0 &&
964 isLegalArithImmed((uint32_t)(C - 1))) ||
965 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
966 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
967 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
968 RHS = DAG.getConstant(C, VT);
973 if ((VT == MVT::i32 && C != 0x7fffffff &&
974 isLegalArithImmed((uint32_t)(C + 1))) ||
975 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
976 isLegalArithImmed(C + 1ULL))) {
977 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
978 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
979 RHS = DAG.getConstant(C, VT);
984 if ((VT == MVT::i32 && C != 0xffffffff &&
985 isLegalArithImmed((uint32_t)(C + 1))) ||
986 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
987 isLegalArithImmed(C + 1ULL))) {
988 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
989 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
990 RHS = DAG.getConstant(C, VT);
997 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
998 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
999 ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1003 static std::pair<SDValue, SDValue>
1004 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1005 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1006 "Unsupported value type");
1007 SDValue Value, Overflow;
1009 SDValue LHS = Op.getOperand(0);
1010 SDValue RHS = Op.getOperand(1);
1012 switch (Op.getOpcode()) {
1014 llvm_unreachable("Unknown overflow instruction!");
1016 Opc = ARM64ISD::ADDS;
1020 Opc = ARM64ISD::ADDS;
1024 Opc = ARM64ISD::SUBS;
1028 Opc = ARM64ISD::SUBS;
1031 // Multiply needs a little bit extra work.
1035 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1036 if (Op.getValueType() == MVT::i32) {
1037 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1038 // For a 32 bit multiply with overflow check we want the instruction
1039 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1040 // need to generate the following pattern:
1041 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1042 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1043 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1044 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1045 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1046 DAG.getConstant(0, MVT::i64));
1047 // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1048 // operation. We need to clear out the upper 32 bits, because we used a
1049 // widening multiply that wrote all 64 bits. In the end this should be a
1051 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1053 // The signed overflow check requires more than just a simple check for
1054 // any bit set in the upper 32 bits of the result. These bits could be
1055 // just the sign bits of a negative number. To perform the overflow
1056 // check we have to arithmetic shift right the 32nd bit of the result by
1057 // 31 bits. Then we compare the result to the upper 32 bits.
1058 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1059 DAG.getConstant(32, MVT::i64));
1060 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1061 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1062 DAG.getConstant(31, MVT::i64));
1063 // It is important that LowerBits is last, otherwise the arithmetic
1064 // shift will not be folded into the compare (SUBS).
1065 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1066 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1069 // The overflow check for unsigned multiply is easy. We only need to
1070 // check if any of the upper 32 bits are set. This can be done with a
1071 // CMP (shifted register). For that we need to generate the following
1073 // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1074 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1075 DAG.getConstant(32, MVT::i64));
1076 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1078 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1079 UpperBits).getValue(1);
1083 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1084 // For the 64 bit multiply
1085 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1087 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1088 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1089 DAG.getConstant(63, MVT::i64));
1090 // It is important that LowerBits is last, otherwise the arithmetic
1091 // shift will not be folded into the compare (SUBS).
1092 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1093 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1096 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1097 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1099 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1100 UpperBits).getValue(1);
1107 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1109 // Emit the ARM64 operation with overflow check.
1110 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1111 Overflow = Value.getValue(1);
1113 return std::make_pair(Value, Overflow);
1116 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1117 RTLIB::Libcall Call) const {
1118 SmallVector<SDValue, 2> Ops;
1119 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1120 Ops.push_back(Op.getOperand(i));
1122 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1126 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1127 SDValue Sel = Op.getOperand(0);
1128 SDValue Other = Op.getOperand(1);
1130 // If neither operand is a SELECT_CC, give up.
1131 if (Sel.getOpcode() != ISD::SELECT_CC)
1132 std::swap(Sel, Other);
1133 if (Sel.getOpcode() != ISD::SELECT_CC)
1136 // The folding we want to perform is:
1137 // (xor x, (select_cc a, b, cc, 0, -1) )
1139 // (csel x, (xor x, -1), cc ...)
1141 // The latter will get matched to a CSINV instruction.
1143 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1144 SDValue LHS = Sel.getOperand(0);
1145 SDValue RHS = Sel.getOperand(1);
1146 SDValue TVal = Sel.getOperand(2);
1147 SDValue FVal = Sel.getOperand(3);
1150 // FIXME: This could be generalized to non-integer comparisons.
1151 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1154 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1155 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1157 // The the values aren't constants, this isn't the pattern we're looking for.
1158 if (!CFVal || !CTVal)
1161 // We can commute the SELECT_CC by inverting the condition. This
1162 // might be needed to make this fit into a CSINV pattern.
1163 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1164 std::swap(TVal, FVal);
1165 std::swap(CTVal, CFVal);
1166 CC = ISD::getSetCCInverse(CC, true);
1169 // If the constants line up, perform the transform!
1170 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1172 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1175 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1176 DAG.getConstant(-1ULL, Other.getValueType()));
1178 return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1185 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1186 EVT VT = Op.getValueType();
1188 // Let legalize expand this if it isn't a legal type yet.
1189 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1192 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1195 bool ExtraOp = false;
1196 switch (Op.getOpcode()) {
1198 assert(0 && "Invalid code");
1200 Opc = ARM64ISD::ADDS;
1203 Opc = ARM64ISD::SUBS;
1206 Opc = ARM64ISD::ADCS;
1210 Opc = ARM64ISD::SBCS;
1216 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1217 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1221 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1222 // Let legalize expand this if it isn't a legal type yet.
1223 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1226 ARM64CC::CondCode CC;
1227 // The actual operation that sets the overflow or carry flag.
1228 SDValue Value, Overflow;
1229 std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1231 // We use 0 and 1 as false and true values.
1232 SDValue TVal = DAG.getConstant(1, MVT::i32);
1233 SDValue FVal = DAG.getConstant(0, MVT::i32);
1235 // We use an inverted condition, because the conditional select is inverted
1236 // too. This will allow it to be selected to a single instruction:
1237 // CSINC Wd, WZR, WZR, invert(cond).
1238 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1239 Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1242 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1243 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1246 // Prefetch operands are:
1247 // 1: Address to prefetch
1249 // 3: int locality (0 = no locality ... 3 = extreme locality)
1250 // 4: bool isDataCache
1251 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1253 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1254 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1255 // The data thing is not used.
1256 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1258 bool IsStream = !Locality;
1259 // When the locality number is set
1261 // The front-end should have filtered out the out-of-range values
1262 assert(Locality <= 3 && "Prefetch locality out-of-range");
1263 // The locality degree is the opposite of the cache speed.
1264 // Put the number the other way around.
1265 // The encoding starts at 0 for level 1
1266 Locality = 3 - Locality;
1269 // built the mask value encoding the expected behavior.
1270 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1271 (Locality << 1) | // Cache level bits
1272 (unsigned)IsStream; // Stream bit
1273 return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1274 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1277 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1278 SelectionDAG &DAG) const {
1279 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1282 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1284 return LowerF128Call(Op, DAG, LC);
1287 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1288 SelectionDAG &DAG) const {
1289 if (Op.getOperand(0).getValueType() != MVT::f128) {
1290 // It's legal except when f128 is involved
1295 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1297 // FP_ROUND node has a second operand indicating whether it is known to be
1298 // precise. That doesn't take part in the LibCall so we can't directly use
1300 SDValue SrcVal = Op.getOperand(0);
1301 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1302 /*isSigned*/ false, SDLoc(Op)).first;
1305 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1306 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1307 // Any additional optimization in this function should be recorded
1308 // in the cost tables.
1309 EVT InVT = Op.getOperand(0).getValueType();
1310 EVT VT = Op.getValueType();
1312 // FP_TO_XINT conversion from the same type are legal.
1313 if (VT.getSizeInBits() == InVT.getSizeInBits())
1316 if (InVT == MVT::v2f64 || InVT == MVT::v4f32) {
1319 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1321 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1322 } else if (InVT == MVT::v2f32) {
1324 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Op.getOperand(0));
1325 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1328 // Type changing conversions are illegal.
1332 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1333 SelectionDAG &DAG) const {
1334 if (Op.getOperand(0).getValueType().isVector())
1335 return LowerVectorFP_TO_INT(Op, DAG);
1337 if (Op.getOperand(0).getValueType() != MVT::f128) {
1338 // It's legal except when f128 is involved
1343 if (Op.getOpcode() == ISD::FP_TO_SINT)
1344 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1346 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1348 SmallVector<SDValue, 2> Ops;
1349 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1350 Ops.push_back(Op.getOperand(i));
1352 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1356 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1357 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1358 // Any additional optimization in this function should be recorded
1359 // in the cost tables.
1360 EVT VT = Op.getValueType();
1362 SDValue In = Op.getOperand(0);
1363 EVT InVT = In.getValueType();
1365 // v2i32 to v2f32 is legal.
1366 if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1369 // This function only handles v2f64 outputs.
1370 if (VT == MVT::v2f64) {
1371 // Extend the input argument to a v2i64 that we can feed into the
1372 // floating point conversion. Zero or sign extend based on whether
1373 // we're doing a signed or unsigned float conversion.
1375 Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1376 assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1377 SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1378 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1381 // Scalarize v2i64 to v2f32 conversions.
1382 std::vector<SDValue> BuildVectorOps;
1383 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1384 SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1385 DAG.getConstant(i, MVT::i64));
1386 Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1387 BuildVectorOps.push_back(Sclr);
1390 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &BuildVectorOps[0],
1391 BuildVectorOps.size());
1394 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1395 SelectionDAG &DAG) const {
1396 if (Op.getValueType().isVector())
1397 return LowerVectorINT_TO_FP(Op, DAG);
1399 // i128 conversions are libcalls.
1400 if (Op.getOperand(0).getValueType() == MVT::i128)
1403 // Other conversions are legal, unless it's to the completely software-based
1405 if (Op.getValueType() != MVT::f128)
1409 if (Op.getOpcode() == ISD::SINT_TO_FP)
1410 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1412 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1414 return LowerF128Call(Op, DAG, LC);
1417 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1418 // For iOS, we want to call an alternative entry point: __sincos_stret,
1419 // which returns the values in two S / D registers.
1421 SDValue Arg = Op.getOperand(0);
1422 EVT ArgVT = Arg.getValueType();
1423 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1430 Entry.isSExt = false;
1431 Entry.isZExt = false;
1432 Args.push_back(Entry);
1434 const char *LibcallName =
1435 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1436 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1438 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1439 TargetLowering::CallLoweringInfo CLI(
1440 DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1441 CallingConv::Fast, /*isTaillCall=*/false,
1442 /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1443 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1444 return CallResult.first;
1447 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1448 SelectionDAG &DAG) const {
1449 switch (Op.getOpcode()) {
1451 llvm_unreachable("unimplemented operand");
1453 case ISD::GlobalAddress:
1454 return LowerGlobalAddress(Op, DAG);
1455 case ISD::GlobalTLSAddress:
1456 return LowerGlobalTLSAddress(Op, DAG);
1458 return LowerSETCC(Op, DAG);
1460 return LowerBR_CC(Op, DAG);
1462 return LowerSELECT(Op, DAG);
1463 case ISD::SELECT_CC:
1464 return LowerSELECT_CC(Op, DAG);
1465 case ISD::JumpTable:
1466 return LowerJumpTable(Op, DAG);
1467 case ISD::ConstantPool:
1468 return LowerConstantPool(Op, DAG);
1469 case ISD::BlockAddress:
1470 return LowerBlockAddress(Op, DAG);
1472 return LowerVASTART(Op, DAG);
1474 return LowerVACOPY(Op, DAG);
1476 return LowerVAARG(Op, DAG);
1481 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1488 return LowerXALUO(Op, DAG);
1490 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1492 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1494 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1496 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1498 return LowerFP_ROUND(Op, DAG);
1499 case ISD::FP_EXTEND:
1500 return LowerFP_EXTEND(Op, DAG);
1501 case ISD::FRAMEADDR:
1502 return LowerFRAMEADDR(Op, DAG);
1503 case ISD::RETURNADDR:
1504 return LowerRETURNADDR(Op, DAG);
1505 case ISD::INSERT_VECTOR_ELT:
1506 return LowerINSERT_VECTOR_ELT(Op, DAG);
1507 case ISD::EXTRACT_VECTOR_ELT:
1508 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1509 case ISD::BUILD_VECTOR:
1510 return LowerBUILD_VECTOR(Op, DAG);
1511 case ISD::VECTOR_SHUFFLE:
1512 return LowerVECTOR_SHUFFLE(Op, DAG);
1513 case ISD::EXTRACT_SUBVECTOR:
1514 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1518 return LowerVectorSRA_SRL_SHL(Op, DAG);
1519 case ISD::SHL_PARTS:
1520 return LowerShiftLeftParts(Op, DAG);
1521 case ISD::SRL_PARTS:
1522 case ISD::SRA_PARTS:
1523 return LowerShiftRightParts(Op, DAG);
1525 return LowerCTPOP(Op, DAG);
1526 case ISD::FCOPYSIGN:
1527 return LowerFCOPYSIGN(Op, DAG);
1529 return LowerVectorAND(Op, DAG);
1531 return LowerVectorOR(Op, DAG);
1533 return LowerXOR(Op, DAG);
1535 return LowerPREFETCH(Op, DAG);
1536 case ISD::SINT_TO_FP:
1537 case ISD::UINT_TO_FP:
1538 return LowerINT_TO_FP(Op, DAG);
1539 case ISD::FP_TO_SINT:
1540 case ISD::FP_TO_UINT:
1541 return LowerFP_TO_INT(Op, DAG);
1543 return LowerFSINCOS(Op, DAG);
1547 /// getFunctionAlignment - Return the Log2 alignment of this function.
1548 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
1552 //===----------------------------------------------------------------------===//
1553 // Calling Convention Implementation
1554 //===----------------------------------------------------------------------===//
1556 #include "ARM64GenCallingConv.inc"
1558 /// Selects the correct CCAssignFn for a the given CallingConvention
1560 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1561 bool IsVarArg) const {
1564 llvm_unreachable("Unsupported calling convention.");
1565 case CallingConv::WebKit_JS:
1566 return CC_ARM64_WebKit_JS;
1567 case CallingConv::C:
1568 case CallingConv::Fast:
1569 if (!Subtarget->isTargetDarwin())
1570 return CC_ARM64_AAPCS;
1571 return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
1575 SDValue ARM64TargetLowering::LowerFormalArguments(
1576 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1577 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1578 SmallVectorImpl<SDValue> &InVals) const {
1579 MachineFunction &MF = DAG.getMachineFunction();
1580 MachineFrameInfo *MFI = MF.getFrameInfo();
1582 // Assign locations to all of the incoming arguments.
1583 SmallVector<CCValAssign, 16> ArgLocs;
1584 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1585 getTargetMachine(), ArgLocs, *DAG.getContext());
1587 // At this point, Ins[].VT may already be promoted to i32. To correctly
1588 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1589 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1590 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1591 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1593 unsigned NumArgs = Ins.size();
1594 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1595 unsigned CurArgIdx = 0;
1596 for (unsigned i = 0; i != NumArgs; ++i) {
1597 MVT ValVT = Ins[i].VT;
1598 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1599 CurArgIdx = Ins[i].OrigArgIndex;
1601 // Get type of the original argument.
1602 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1603 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1604 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1606 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1608 else if (ActualMVT == MVT::i16)
1611 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1613 AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1614 assert(!Res && "Call operand has unhandled type");
1617 assert(ArgLocs.size() == Ins.size());
1618 SmallVector<SDValue, 16> ArgValues;
1619 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1620 CCValAssign &VA = ArgLocs[i];
1622 if (Ins[i].Flags.isByVal()) {
1623 // Byval is used for HFAs in the PCS, but the system should work in a
1624 // non-compliant manner for larger structs.
1625 EVT PtrTy = getPointerTy();
1626 int Size = Ins[i].Flags.getByValSize();
1627 unsigned NumRegs = (Size + 7) / 8;
1630 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1631 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1632 InVals.push_back(FrameIdxN);
1635 } if (VA.isRegLoc()) {
1636 // Arguments stored in registers.
1637 EVT RegVT = VA.getLocVT();
1640 const TargetRegisterClass *RC;
1642 if (RegVT == MVT::i32)
1643 RC = &ARM64::GPR32RegClass;
1644 else if (RegVT == MVT::i64)
1645 RC = &ARM64::GPR64RegClass;
1646 else if (RegVT == MVT::f32)
1647 RC = &ARM64::FPR32RegClass;
1648 else if (RegVT == MVT::f64 || RegVT == MVT::v1i64 ||
1649 RegVT == MVT::v1f64 || RegVT == MVT::v2i32 ||
1650 RegVT == MVT::v4i16 || RegVT == MVT::v8i8)
1651 RC = &ARM64::FPR64RegClass;
1652 else if (RegVT == MVT::v2i64 || RegVT == MVT::v4i32 ||
1653 RegVT == MVT::v8i16 || RegVT == MVT::v16i8)
1654 RC = &ARM64::FPR128RegClass;
1656 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1658 // Transform the arguments in physical registers into virtual ones.
1659 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1660 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1662 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1663 // to 64 bits. Insert an assert[sz]ext to capture this, then
1664 // truncate to the right size.
1665 switch (VA.getLocInfo()) {
1667 llvm_unreachable("Unknown loc info!");
1668 case CCValAssign::Full:
1670 case CCValAssign::BCvt:
1671 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1673 case CCValAssign::SExt:
1674 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
1675 DAG.getValueType(VA.getValVT()));
1676 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1678 case CCValAssign::ZExt:
1679 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
1680 DAG.getValueType(VA.getValVT()));
1681 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1685 InVals.push_back(ArgValue);
1687 } else { // VA.isRegLoc()
1688 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1689 unsigned ArgOffset = VA.getLocMemOffset();
1690 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1691 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
1693 // Create load nodes to retrieve arguments from the stack.
1694 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1695 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
1696 MachinePointerInfo::getFixedStack(FI), false,
1703 if (!Subtarget->isTargetDarwin()) {
1704 // The AAPCS variadic function ABI is identical to the non-variadic
1705 // one. As a result there may be more arguments in registers and we should
1706 // save them for future reference.
1707 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1710 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
1711 // This will point to the next argument passed via stack.
1712 unsigned StackOffset = CCInfo.getNextStackOffset();
1713 // We currently pass all varargs at 8-byte alignment.
1714 StackOffset = ((StackOffset + 7) & ~7);
1715 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1721 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1722 SelectionDAG &DAG, SDLoc DL,
1723 SDValue &Chain) const {
1724 MachineFunction &MF = DAG.getMachineFunction();
1725 MachineFrameInfo *MFI = MF.getFrameInfo();
1726 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
1728 SmallVector<SDValue, 8> MemOps;
1730 static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
1731 ARM64::X3, ARM64::X4, ARM64::X5,
1732 ARM64::X6, ARM64::X7 };
1733 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1734 unsigned FirstVariadicGPR =
1735 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1737 static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
1738 ARM64::Q3, ARM64::Q4, ARM64::Q5,
1739 ARM64::Q6, ARM64::Q7 };
1740 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1741 unsigned FirstVariadicFPR =
1742 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1744 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1746 if (GPRSaveSize != 0) {
1747 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1749 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1751 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1752 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
1753 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1755 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1756 MachinePointerInfo::getStack(i * 8), false, false, 0);
1757 MemOps.push_back(Store);
1758 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1759 DAG.getConstant(8, getPointerTy()));
1763 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1765 if (FPRSaveSize != 0) {
1766 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1768 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1770 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1771 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
1772 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
1774 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1775 MachinePointerInfo::getStack(i * 16), false, false, 0);
1776 MemOps.push_back(Store);
1777 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1778 DAG.getConstant(16, getPointerTy()));
1782 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1783 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1784 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1785 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1787 if (!MemOps.empty()) {
1788 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
1793 /// LowerCallResult - Lower the result values of a call into the
1794 /// appropriate copies out of appropriate physical registers.
1795 SDValue ARM64TargetLowering::LowerCallResult(
1796 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1797 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1798 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1799 SDValue ThisVal) const {
1800 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1801 : RetCC_ARM64_AAPCS;
1802 // Assign locations to each value returned by this call.
1803 SmallVector<CCValAssign, 16> RVLocs;
1804 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1805 getTargetMachine(), RVLocs, *DAG.getContext());
1806 CCInfo.AnalyzeCallResult(Ins, RetCC);
1808 // Copy all of the result registers out of their specified physreg.
1809 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1810 CCValAssign VA = RVLocs[i];
1812 // Pass 'this' value directly from the argument to return value, to avoid
1813 // reg unit interference
1814 if (i == 0 && isThisReturn) {
1815 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1816 "unexpected return calling convention register assignment");
1817 InVals.push_back(ThisVal);
1822 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1823 Chain = Val.getValue(1);
1824 InFlag = Val.getValue(2);
1826 switch (VA.getLocInfo()) {
1828 llvm_unreachable("Unknown loc info!");
1829 case CCValAssign::Full:
1831 case CCValAssign::BCvt:
1832 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1836 InVals.push_back(Val);
1842 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
1843 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1844 bool isCalleeStructRet, bool isCallerStructRet,
1845 const SmallVectorImpl<ISD::OutputArg> &Outs,
1846 const SmallVectorImpl<SDValue> &OutVals,
1847 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1848 // Look for obvious safe cases to perform tail call optimization that do not
1849 // require ABI changes. This is what gcc calls sibcall.
1851 // Do not sibcall optimize vararg calls unless the call site is not passing
1853 if (isVarArg && !Outs.empty())
1856 // Also avoid sibcall optimization if either caller or callee uses struct
1857 // return semantics.
1858 if (isCalleeStructRet || isCallerStructRet)
1861 // Note that currently ARM64 "C" calling convention and "Fast" calling
1862 // convention are compatible. If/when that ever changes, we'll need to
1863 // add checks here to make sure any interactions are OK.
1865 // If the callee takes no arguments then go on to check the results of the
1867 if (!Outs.empty()) {
1868 // Check if stack adjustment is needed. For now, do not do this if any
1869 // argument is passed on the stack.
1870 SmallVector<CCValAssign, 16> ArgLocs;
1871 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1872 getTargetMachine(), ArgLocs, *DAG.getContext());
1873 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
1874 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
1875 if (CCInfo.getNextStackOffset()) {
1876 // Check if the arguments are already laid out in the right way as
1877 // the caller's fixed stack objects.
1878 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1879 ++i, ++realArgIdx) {
1880 CCValAssign &VA = ArgLocs[i];
1881 if (VA.getLocInfo() == CCValAssign::Indirect)
1883 if (VA.needsCustom()) {
1884 // Just don't handle anything that needs custom adjustments for now.
1885 // If need be, we can revisit later, but we shouldn't ever end up
1888 } else if (!VA.isRegLoc()) {
1889 // Likewise, don't try to handle stack based arguments for the
1899 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
1900 /// and add input and output parameter nodes.
1901 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1902 SmallVectorImpl<SDValue> &InVals) const {
1903 SelectionDAG &DAG = CLI.DAG;
1905 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1906 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1907 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1908 SDValue Chain = CLI.Chain;
1909 SDValue Callee = CLI.Callee;
1910 bool &IsTailCall = CLI.IsTailCall;
1911 CallingConv::ID CallConv = CLI.CallConv;
1912 bool IsVarArg = CLI.IsVarArg;
1914 MachineFunction &MF = DAG.getMachineFunction();
1915 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1916 bool IsThisReturn = false;
1918 // If tail calls are explicitly disabled, make sure not to use them.
1919 if (!EnableARM64TailCalls)
1923 // Check if it's really possible to do a tail call.
1924 IsTailCall = isEligibleForTailCallOptimization(
1925 Callee, CallConv, IsVarArg, IsStructRet,
1926 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
1927 // We don't support GuaranteedTailCallOpt, only automatically
1928 // detected sibcalls.
1929 // FIXME: Re-evaluate. Is this true? Should it be true?
1934 // Analyze operands of the call, assigning locations to each operand.
1935 SmallVector<CCValAssign, 16> ArgLocs;
1936 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1937 getTargetMachine(), ArgLocs, *DAG.getContext());
1940 // Handle fixed and variable vector arguments differently.
1941 // Variable vector arguments always go into memory.
1942 unsigned NumArgs = Outs.size();
1944 for (unsigned i = 0; i != NumArgs; ++i) {
1945 MVT ArgVT = Outs[i].VT;
1946 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1947 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
1948 /*IsVarArg=*/ !Outs[i].IsFixed);
1949 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1950 assert(!Res && "Call operand has unhandled type");
1954 // At this point, Outs[].VT may already be promoted to i32. To correctly
1955 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1956 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1957 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
1958 // we use a special version of AnalyzeCallOperands to pass in ValVT and
1960 unsigned NumArgs = Outs.size();
1961 for (unsigned i = 0; i != NumArgs; ++i) {
1962 MVT ValVT = Outs[i].VT;
1963 // Get type of the original argument.
1964 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
1965 /*AllowUnknown*/ true);
1966 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
1967 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1968 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1970 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1972 else if (ActualMVT == MVT::i16)
1975 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1976 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
1977 assert(!Res && "Call operand has unhandled type");
1982 // Get a count of how many bytes are to be pushed on the stack.
1983 unsigned NumBytes = CCInfo.getNextStackOffset();
1985 // Adjust the stack pointer for the new arguments...
1986 // These operations are automatically eliminated by the prolog/epilog pass
1989 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
1991 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
1993 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1994 SmallVector<SDValue, 8> MemOpChains;
1996 // Walk the register/memloc assignments, inserting copies/loads.
1997 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1998 ++i, ++realArgIdx) {
1999 CCValAssign &VA = ArgLocs[i];
2000 SDValue Arg = OutVals[realArgIdx];
2001 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2003 // Promote the value if needed.
2004 switch (VA.getLocInfo()) {
2006 llvm_unreachable("Unknown loc info!");
2007 case CCValAssign::Full:
2009 case CCValAssign::SExt:
2010 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2012 case CCValAssign::ZExt:
2013 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2015 case CCValAssign::AExt:
2016 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2018 case CCValAssign::BCvt:
2019 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2021 case CCValAssign::FPExt:
2022 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2026 if (VA.isRegLoc()) {
2027 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2028 assert(VA.getLocVT() == MVT::i64 &&
2029 "unexpected calling convention register assignment");
2030 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2031 "unexpected use of 'returned'");
2032 IsThisReturn = true;
2034 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2036 assert(VA.isMemLoc());
2037 // There's no reason we can't support stack args w/ tailcall, but
2038 // we currently don't, so assert if we see one.
2039 assert(!IsTailCall && "stack argument with tail call!?");
2040 unsigned LocMemOffset = VA.getLocMemOffset();
2041 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2042 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2044 if (Outs[i].Flags.isByVal()) {
2046 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2047 SDValue Cpy = DAG.getMemcpy(
2048 Chain, DL, PtrOff, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2049 /*isVolatile = */ false,
2050 /*alwaysInline = */ false,
2051 MachinePointerInfo::getStack(LocMemOffset), MachinePointerInfo());
2053 MemOpChains.push_back(Cpy);
2055 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2056 // promoted to a legal register type i32, we should truncate Arg back to
2058 if (Arg.getValueType().isSimple() &&
2059 Arg.getValueType().getSimpleVT() == MVT::i32 &&
2060 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2061 VA.getLocVT() == MVT::i16))
2062 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2064 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2065 MachinePointerInfo::getStack(LocMemOffset),
2067 MemOpChains.push_back(Store);
2072 if (!MemOpChains.empty())
2073 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOpChains[0],
2074 MemOpChains.size());
2076 // Build a sequence of copy-to-reg nodes chained together with token chain
2077 // and flag operands which copy the outgoing args into the appropriate regs.
2079 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2080 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2081 RegsToPass[i].second, InFlag);
2082 InFlag = Chain.getValue(1);
2085 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2086 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2087 // node so that legalize doesn't hack it.
2088 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2089 Subtarget->isTargetMachO()) {
2090 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2091 const GlobalValue *GV = G->getGlobal();
2092 bool InternalLinkage = GV->hasInternalLinkage();
2093 if (InternalLinkage)
2094 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2096 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2098 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2100 } else if (ExternalSymbolSDNode *S =
2101 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2102 const char *Sym = S->getSymbol();
2104 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2105 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2107 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2108 const GlobalValue *GV = G->getGlobal();
2109 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2110 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2111 const char *Sym = S->getSymbol();
2112 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2115 std::vector<SDValue> Ops;
2116 Ops.push_back(Chain);
2117 Ops.push_back(Callee);
2119 // Add argument registers to the end of the list so that they are known live
2121 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2122 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2123 RegsToPass[i].second.getValueType()));
2125 // Add a register mask operand representing the call-preserved registers.
2126 const uint32_t *Mask;
2127 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2128 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2130 // For 'this' returns, use the X0-preserving mask if applicable
2131 Mask = ARI->getThisReturnPreservedMask(CallConv);
2133 IsThisReturn = false;
2134 Mask = ARI->getCallPreservedMask(CallConv);
2137 Mask = ARI->getCallPreservedMask(CallConv);
2139 assert(Mask && "Missing call preserved mask for calling convention");
2140 Ops.push_back(DAG.getRegisterMask(Mask));
2142 if (InFlag.getNode())
2143 Ops.push_back(InFlag);
2145 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2147 // If we're doing a tall call, use a TC_RETURN here rather than an
2148 // actual call instruction.
2150 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, &Ops[0], Ops.size());
2152 // Returns a chain and a flag for retval copy to use.
2153 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
2154 InFlag = Chain.getValue(1);
2156 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2157 DAG.getIntPtrConstant(0, true), InFlag, DL);
2159 InFlag = Chain.getValue(1);
2161 // Handle result values, copying them out of physregs into vregs that we
2163 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2164 InVals, IsThisReturn,
2165 IsThisReturn ? OutVals[0] : SDValue());
2168 bool ARM64TargetLowering::CanLowerReturn(
2169 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2170 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2171 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2172 : RetCC_ARM64_AAPCS;
2173 SmallVector<CCValAssign, 16> RVLocs;
2174 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2175 return CCInfo.CheckReturn(Outs, RetCC);
2179 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2181 const SmallVectorImpl<ISD::OutputArg> &Outs,
2182 const SmallVectorImpl<SDValue> &OutVals,
2183 SDLoc DL, SelectionDAG &DAG) const {
2184 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2185 : RetCC_ARM64_AAPCS;
2186 SmallVector<CCValAssign, 16> RVLocs;
2187 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2188 getTargetMachine(), RVLocs, *DAG.getContext());
2189 CCInfo.AnalyzeReturn(Outs, RetCC);
2191 // Copy the result values into the output registers.
2193 SmallVector<SDValue, 4> RetOps(1, Chain);
2194 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2195 ++i, ++realRVLocIdx) {
2196 CCValAssign &VA = RVLocs[i];
2197 assert(VA.isRegLoc() && "Can only return in registers!");
2198 SDValue Arg = OutVals[realRVLocIdx];
2200 switch (VA.getLocInfo()) {
2202 llvm_unreachable("Unknown loc info!");
2203 case CCValAssign::Full:
2205 case CCValAssign::BCvt:
2206 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2210 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2211 Flag = Chain.getValue(1);
2212 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2215 RetOps[0] = Chain; // Update chain.
2217 // Add the flag if we have it.
2219 RetOps.push_back(Flag);
2221 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, &RetOps[0],
2225 //===----------------------------------------------------------------------===//
2226 // Other Lowering Code
2227 //===----------------------------------------------------------------------===//
2229 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2230 SelectionDAG &DAG) const {
2231 EVT PtrVT = getPointerTy();
2233 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2234 unsigned char OpFlags =
2235 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2237 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2238 "unexpected offset in global node");
2240 // This also catched the large code model case for Darwin.
2241 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2242 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2243 // FIXME: Once remat is capable of dealing with instructions with register
2244 // operands, expand this into two nodes instead of using a wrapper node.
2245 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2248 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2249 const unsigned char MO_NC = ARM64II::MO_NC;
2251 ARM64ISD::WrapperLarge, DL, PtrVT,
2252 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2253 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2254 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2255 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2257 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2258 // the only correct model on Darwin.
2259 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2260 OpFlags | ARM64II::MO_PAGE);
2261 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2262 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2264 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2265 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2269 /// \brief Convert a TLS address reference into the correct sequence of loads
2270 /// and calls to compute the variable's address (for Darwin, currently) and
2271 /// return an SDValue containing the final node.
2273 /// Darwin only has one TLS scheme which must be capable of dealing with the
2274 /// fully general situation, in the worst case. This means:
2275 /// + "extern __thread" declaration.
2276 /// + Defined in a possibly unknown dynamic library.
2278 /// The general system is that each __thread variable has a [3 x i64] descriptor
2279 /// which contains information used by the runtime to calculate the address. The
2280 /// only part of this the compiler needs to know about is the first xword, which
2281 /// contains a function pointer that must be called with the address of the
2282 /// entire descriptor in "x0".
2284 /// Since this descriptor may be in a different unit, in general even the
2285 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2287 /// adrp x0, _var@TLVPPAGE
2288 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2289 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2290 /// ; the function pointer
2291 /// blr x1 ; Uses descriptor address in x0
2292 /// ; Address of _var is now in x0.
2294 /// If the address of _var's descriptor *is* known to the linker, then it can
2295 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2296 /// a slight efficiency gain.
2298 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2299 SelectionDAG &DAG) const {
2300 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2303 MVT PtrVT = getPointerTy();
2304 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2307 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2308 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2310 // The first entry in the descriptor is a function pointer that we must call
2311 // to obtain the address of the variable.
2312 SDValue Chain = DAG.getEntryNode();
2313 SDValue FuncTLVGet =
2314 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2315 false, true, true, 8);
2316 Chain = FuncTLVGet.getValue(1);
2318 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2319 MFI->setAdjustsStack(true);
2321 // TLS calls preserve all registers except those that absolutely must be
2322 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2324 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2325 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2326 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2328 // Finally, we can make the call. This is just a degenerate version of a
2329 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2330 // the address of the variable in this thread.
2331 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2332 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2333 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2334 DAG.getRegisterMask(Mask), Chain.getValue(1));
2335 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2338 /// When accessing thread-local variables under either the general-dynamic or
2339 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2340 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2341 /// is a function pointer to carry out the resolution. This function takes the
2342 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2343 /// other registers (except LR, CPSR) are preserved.
2345 /// Thus, the ideal call sequence on AArch64 is:
2347 /// adrp x0, :tlsdesc:thread_var
2348 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2349 /// add x0, x0, :tlsdesc_lo12:thread_var
2350 /// .tlsdesccall thread_var
2352 /// (TPIDR_EL0 offset now in x0).
2354 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2355 /// relocation to help the linker relax this sequence if it turns out to be too
2358 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2360 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2361 SDValue DescAddr, SDLoc DL,
2362 SelectionDAG &DAG) const {
2363 EVT PtrVT = getPointerTy();
2365 // The function we need to call is simply the first entry in the GOT for this
2366 // descriptor, load it in preparation.
2367 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2369 // TLS calls preserve all registers except those that absolutely must be
2370 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2372 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2373 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2374 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2376 // The function takes only one argument: the address of the descriptor itself
2378 SDValue Glue, Chain;
2379 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2380 Glue = Chain.getValue(1);
2382 // We're now ready to populate the argument list, as with a normal call:
2383 SmallVector<SDValue, 6> Ops;
2384 Ops.push_back(Chain);
2385 Ops.push_back(Func);
2386 Ops.push_back(SymAddr);
2387 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2388 Ops.push_back(DAG.getRegisterMask(Mask));
2389 Ops.push_back(Glue);
2391 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2392 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, &Ops[0], Ops.size());
2393 Glue = Chain.getValue(1);
2395 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2398 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2399 SelectionDAG &DAG) const {
2400 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2401 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2402 "ELF TLS only supported in small memory model");
2403 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2405 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2408 EVT PtrVT = getPointerTy();
2410 const GlobalValue *GV = GA->getGlobal();
2412 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2414 if (Model == TLSModel::LocalExec) {
2415 SDValue HiVar = DAG.getTargetGlobalAddress(
2416 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2417 SDValue LoVar = DAG.getTargetGlobalAddress(
2418 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2420 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2421 DAG.getTargetConstant(16, MVT::i32)),
2423 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2424 DAG.getTargetConstant(0, MVT::i32)),
2426 } else if (Model == TLSModel::InitialExec) {
2427 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2428 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2429 } else if (Model == TLSModel::LocalDynamic) {
2430 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2431 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2432 // the beginning of the module's TLS region, followed by a DTPREL offset
2435 // These accesses will need deduplicating if there's more than one.
2436 ARM64FunctionInfo *MFI =
2437 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2438 MFI->incNumLocalDynamicTLSAccesses();
2440 // Accesses used in this sequence go via the TLS descriptor which lives in
2441 // the GOT. Prepare an address we can use to handle this.
2442 SDValue HiDesc = DAG.getTargetExternalSymbol(
2443 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2444 SDValue LoDesc = DAG.getTargetExternalSymbol(
2445 "_TLS_MODULE_BASE_", PtrVT,
2446 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2448 // First argument to the descriptor call is the address of the descriptor
2450 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2451 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2453 // The call needs a relocation too for linker relaxation. It doesn't make
2454 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2456 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2459 // Now we can calculate the offset from TPIDR_EL0 to this module's
2460 // thread-local area.
2461 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2463 // Now use :dtprel_whatever: operations to calculate this variable's offset
2464 // in its thread-storage area.
2465 SDValue HiVar = DAG.getTargetGlobalAddress(
2466 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2467 SDValue LoVar = DAG.getTargetGlobalAddress(
2468 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2471 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2472 DAG.getTargetConstant(16, MVT::i32)),
2474 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2475 DAG.getTargetConstant(0, MVT::i32)),
2478 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2479 } else if (Model == TLSModel::GeneralDynamic) {
2480 // Accesses used in this sequence go via the TLS descriptor which lives in
2481 // the GOT. Prepare an address we can use to handle this.
2482 SDValue HiDesc = DAG.getTargetGlobalAddress(
2483 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2484 SDValue LoDesc = DAG.getTargetGlobalAddress(
2486 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2488 // First argument to the descriptor call is the address of the descriptor
2490 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2491 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2493 // The call needs a relocation too for linker relaxation. It doesn't make
2494 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2497 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2499 // Finally we can make a call to calculate the offset from tpidr_el0.
2500 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2502 llvm_unreachable("Unsupported ELF TLS access model");
2504 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2507 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2508 SelectionDAG &DAG) const {
2509 if (Subtarget->isTargetDarwin())
2510 return LowerDarwinGlobalTLSAddress(Op, DAG);
2511 else if (Subtarget->isTargetELF())
2512 return LowerELFGlobalTLSAddress(Op, DAG);
2514 llvm_unreachable("Unexpected platform trying to use TLS");
2516 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2517 SDValue Chain = Op.getOperand(0);
2518 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2519 SDValue LHS = Op.getOperand(2);
2520 SDValue RHS = Op.getOperand(3);
2521 SDValue Dest = Op.getOperand(4);
2524 // Handle f128 first, since lowering it will result in comparing the return
2525 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2526 // is expecting to deal with.
2527 if (LHS.getValueType() == MVT::f128) {
2528 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2530 // If softenSetCCOperands returned a scalar, we need to compare the result
2531 // against zero to select between true and false values.
2532 if (RHS.getNode() == 0) {
2533 RHS = DAG.getConstant(0, LHS.getValueType());
2538 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2540 unsigned Opc = LHS.getOpcode();
2541 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2542 cast<ConstantSDNode>(RHS)->isOne() &&
2543 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2544 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2545 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2546 "Unexpected condition code.");
2547 // Only lower legal XALUO ops.
2548 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2551 // The actual operation with overflow check.
2552 ARM64CC::CondCode OFCC;
2553 SDValue Value, Overflow;
2554 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2556 if (CC == ISD::SETNE)
2557 OFCC = getInvertedCondCode(OFCC);
2558 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2560 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2564 if (LHS.getValueType().isInteger()) {
2565 assert((LHS.getValueType() == RHS.getValueType()) &&
2566 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2568 // If the RHS of the comparison is zero, we can potentially fold this
2569 // to a specialized branch.
2570 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2571 if (RHSC && RHSC->getZExtValue() == 0) {
2572 if (CC == ISD::SETEQ) {
2573 // See if we can use a TBZ to fold in an AND as well.
2574 // TBZ has a smaller branch displacement than CBZ. If the offset is
2575 // out of bounds, a late MI-layer pass rewrites branches.
2576 // 403.gcc is an example that hits this case.
2577 if (LHS.getOpcode() == ISD::AND &&
2578 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2579 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2580 SDValue Test = LHS.getOperand(0);
2581 uint64_t Mask = LHS.getConstantOperandVal(1);
2583 // TBZ only operates on i64's, but the ext should be free.
2584 if (Test.getValueType() == MVT::i32)
2585 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2587 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
2588 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2591 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2592 } else if (CC == ISD::SETNE) {
2593 // See if we can use a TBZ to fold in an AND as well.
2594 // TBZ has a smaller branch displacement than CBZ. If the offset is
2595 // out of bounds, a late MI-layer pass rewrites branches.
2596 // 403.gcc is an example that hits this case.
2597 if (LHS.getOpcode() == ISD::AND &&
2598 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2599 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2600 SDValue Test = LHS.getOperand(0);
2601 uint64_t Mask = LHS.getConstantOperandVal(1);
2603 // TBNZ only operates on i64's, but the ext should be free.
2604 if (Test.getValueType() == MVT::i32)
2605 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2607 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2608 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2611 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2616 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2617 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2621 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2623 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2624 // clean. Some of them require two branches to implement.
2625 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2626 ARM64CC::CondCode CC1, CC2;
2627 changeFPCCToARM64CC(CC, CC1, CC2);
2628 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2630 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2631 if (CC2 != ARM64CC::AL) {
2632 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2633 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2640 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2641 SelectionDAG &DAG) const {
2642 EVT VT = Op.getValueType();
2645 SDValue In1 = Op.getOperand(0);
2646 SDValue In2 = Op.getOperand(1);
2647 EVT SrcVT = In2.getValueType();
2649 if (SrcVT == MVT::f32 && VT == MVT::f64)
2650 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2651 else if (SrcVT == MVT::f64 && VT == MVT::f32)
2652 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
2654 // FIXME: Src type is different, bail out for now. Can VT really be a
2661 SDValue EltMask, VecVal1, VecVal2;
2662 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
2665 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
2667 if (!VT.isVector()) {
2668 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2669 DAG.getUNDEF(VecVT), In1);
2670 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2671 DAG.getUNDEF(VecVT), In2);
2673 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2674 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2676 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
2680 // We want to materialize a mask with the the high bit set, but the AdvSIMD
2681 // immediate moves cannot materialize that in a single instruction for
2682 // 64-bit elements. Instead, materialize zero and then negate it.
2683 EltMask = DAG.getConstant(0, EltVT);
2685 if (!VT.isVector()) {
2686 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2687 DAG.getUNDEF(VecVT), In1);
2688 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2689 DAG.getUNDEF(VecVT), In2);
2691 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2692 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2695 llvm_unreachable("Invalid type for copysign!");
2698 std::vector<SDValue> BuildVectorOps;
2699 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
2700 BuildVectorOps.push_back(EltMask);
2702 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT,
2703 &BuildVectorOps[0], BuildVectorOps.size());
2705 // If we couldn't materialize the mask above, then the mask vector will be
2706 // the zero vector, and we need to negate it here.
2707 if (VT == MVT::f64 || VT == MVT::v2f64) {
2708 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
2709 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
2710 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
2714 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
2717 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
2718 else if (VT == MVT::f64)
2719 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
2721 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
2724 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
2725 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
2726 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
2729 // While there is no integer popcount instruction, it can
2730 // be more efficiently lowered to the following sequence that uses
2731 // AdvSIMD registers/instructions as long as the copies to/from
2732 // the AdvSIMD registers are cheap.
2733 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
2734 // CNT V0.8B, V0.8B // 8xbyte pop-counts
2735 // ADDV B0, V0.8B // sum 8xbyte pop-counts
2736 // UMOV X0, V0.B[0] // copy byte result back to integer reg
2737 SDValue Val = Op.getOperand(0);
2739 EVT VT = Op.getValueType();
2740 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
2743 if (VT == MVT::i32) {
2744 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
2746 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
2748 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
2751 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
2752 SDValue UaddLV = DAG.getNode(
2753 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2754 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
2757 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
2761 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2763 if (Op.getValueType().isVector())
2764 return LowerVSETCC(Op, DAG);
2766 SDValue LHS = Op.getOperand(0);
2767 SDValue RHS = Op.getOperand(1);
2768 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2771 // We chose ZeroOrOneBooleanContents, so use zero and one.
2772 EVT VT = Op.getValueType();
2773 SDValue TVal = DAG.getConstant(1, VT);
2774 SDValue FVal = DAG.getConstant(0, VT);
2776 // Handle f128 first, since one possible outcome is a normal integer
2777 // comparison which gets picked up by the next if statement.
2778 if (LHS.getValueType() == MVT::f128) {
2779 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2781 // If softenSetCCOperands returned a scalar, use it.
2782 if (RHS.getNode() == 0) {
2783 assert(LHS.getValueType() == Op.getValueType() &&
2784 "Unexpected setcc expansion!");
2789 if (LHS.getValueType().isInteger()) {
2792 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
2794 // Note that we inverted the condition above, so we reverse the order of
2795 // the true and false operands here. This will allow the setcc to be
2796 // matched to a single CSINC instruction.
2797 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
2800 // Now we know we're dealing with FP values.
2801 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2803 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
2804 // and do the comparison.
2805 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2807 ARM64CC::CondCode CC1, CC2;
2808 changeFPCCToARM64CC(CC, CC1, CC2);
2809 if (CC2 == ARM64CC::AL) {
2810 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
2811 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2813 // Note that we inverted the condition above, so we reverse the order of
2814 // the true and false operands here. This will allow the setcc to be
2815 // matched to a single CSINC instruction.
2816 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
2818 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2819 // clean. Some of them require two CSELs to implement. As is in this case,
2820 // we emit the first CSEL and then emit a second using the output of the
2821 // first as the RHS. We're effectively OR'ing the two CC's together.
2823 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
2824 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2825 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2827 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2828 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
2832 /// A SELECT_CC operation is really some kind of max or min if both values being
2833 /// compared are, in some sense, equal to the results in either case. However,
2834 /// it is permissible to compare f32 values and produce directly extended f64
2837 /// Extending the comparison operands would also be allowed, but is less likely
2838 /// to happen in practice since their use is right here. Note that truncate
2839 /// operations would *not* be semantically equivalent.
2840 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
2844 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
2845 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
2846 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
2847 Result.getValueType() == MVT::f64) {
2849 APFloat CmpVal = CCmp->getValueAPF();
2850 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
2851 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
2854 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
2857 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2858 SDValue CC = Op->getOperand(0);
2859 SDValue TVal = Op->getOperand(1);
2860 SDValue FVal = Op->getOperand(2);
2863 unsigned Opc = CC.getOpcode();
2864 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
2866 if (CC.getResNo() == 1 &&
2867 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2868 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2869 // Only lower legal XALUO ops.
2870 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
2873 ARM64CC::CondCode OFCC;
2874 SDValue Value, Overflow;
2875 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
2876 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2878 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
2882 if (CC.getOpcode() == ISD::SETCC)
2883 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
2884 cast<CondCodeSDNode>(CC.getOperand(2))->get());
2886 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
2890 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
2891 SelectionDAG &DAG) const {
2892 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2893 SDValue LHS = Op.getOperand(0);
2894 SDValue RHS = Op.getOperand(1);
2895 SDValue TVal = Op.getOperand(2);
2896 SDValue FVal = Op.getOperand(3);
2899 // Handle f128 first, because it will result in a comparison of some RTLIB
2900 // call result against zero.
2901 if (LHS.getValueType() == MVT::f128) {
2902 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2904 // If softenSetCCOperands returned a scalar, we need to compare the result
2905 // against zero to select between true and false values.
2906 if (RHS.getNode() == 0) {
2907 RHS = DAG.getConstant(0, LHS.getValueType());
2912 // Handle integers first.
2913 if (LHS.getValueType().isInteger()) {
2914 assert((LHS.getValueType() == RHS.getValueType()) &&
2915 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2917 unsigned Opcode = ARM64ISD::CSEL;
2919 // If both the TVal and the FVal are constants, see if we can swap them in
2920 // order to for a CSINV or CSINC out of them.
2921 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2922 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2924 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2925 std::swap(TVal, FVal);
2926 std::swap(CTVal, CFVal);
2927 CC = ISD::getSetCCInverse(CC, true);
2928 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
2929 std::swap(TVal, FVal);
2930 std::swap(CTVal, CFVal);
2931 CC = ISD::getSetCCInverse(CC, true);
2932 } else if (TVal.getOpcode() == ISD::XOR) {
2933 // If TVal is a NOT we want to swap TVal and FVal so that we can match
2934 // with a CSINV rather than a CSEL.
2935 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
2937 if (CVal && CVal->isAllOnesValue()) {
2938 std::swap(TVal, FVal);
2939 std::swap(CTVal, CFVal);
2940 CC = ISD::getSetCCInverse(CC, true);
2942 } else if (TVal.getOpcode() == ISD::SUB) {
2943 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
2944 // that we can match with a CSNEG rather than a CSEL.
2945 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
2947 if (CVal && CVal->isNullValue()) {
2948 std::swap(TVal, FVal);
2949 std::swap(CTVal, CFVal);
2950 CC = ISD::getSetCCInverse(CC, true);
2952 } else if (CTVal && CFVal) {
2953 const int64_t TrueVal = CTVal->getSExtValue();
2954 const int64_t FalseVal = CFVal->getSExtValue();
2957 // If both TVal and FVal are constants, see if FVal is the
2958 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
2959 // instead of a CSEL in that case.
2960 if (TrueVal == ~FalseVal) {
2961 Opcode = ARM64ISD::CSINV;
2962 } else if (TrueVal == -FalseVal) {
2963 Opcode = ARM64ISD::CSNEG;
2964 } else if (TVal.getValueType() == MVT::i32) {
2965 // If our operands are only 32-bit wide, make sure we use 32-bit
2966 // arithmetic for the check whether we can use CSINC. This ensures that
2967 // the addition in the check will wrap around properly in case there is
2968 // an overflow (which would not be the case if we do the check with
2969 // 64-bit arithmetic).
2970 const uint32_t TrueVal32 = CTVal->getZExtValue();
2971 const uint32_t FalseVal32 = CFVal->getZExtValue();
2973 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
2974 Opcode = ARM64ISD::CSINC;
2976 if (TrueVal32 > FalseVal32) {
2980 // 64-bit check whether we can use CSINC.
2981 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
2982 Opcode = ARM64ISD::CSINC;
2984 if (TrueVal > FalseVal) {
2989 // Swap TVal and FVal if necessary.
2991 std::swap(TVal, FVal);
2992 std::swap(CTVal, CFVal);
2993 CC = ISD::getSetCCInverse(CC, true);
2996 if (Opcode != ARM64ISD::CSEL) {
2997 // Drop FVal since we can get its value by simply inverting/negating
3004 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3006 EVT VT = Op.getValueType();
3007 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3010 // Now we know we're dealing with FP values.
3011 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3012 assert(LHS.getValueType() == RHS.getValueType());
3013 EVT VT = Op.getValueType();
3015 // Try to match this select into a max/min operation, which have dedicated
3016 // opcode in the instruction set.
3017 // NOTE: This is not correct in the presence of NaNs, so we only enable this
3019 if (getTargetMachine().Options.NoNaNsFPMath) {
3020 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3021 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3022 CC = ISD::getSetCCSwappedOperands(CC);
3023 std::swap(TVal, FVal);
3026 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3027 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3037 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3045 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3051 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3052 // and do the comparison.
3053 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3055 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3056 // clean. Some of them require two CSELs to implement.
3057 ARM64CC::CondCode CC1, CC2;
3058 changeFPCCToARM64CC(CC, CC1, CC2);
3059 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3060 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3062 // If we need a second CSEL, emit it, using the output of the first as the
3063 // RHS. We're effectively OR'ing the two CC's together.
3064 if (CC2 != ARM64CC::AL) {
3065 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3066 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3069 // Otherwise, return the output of the first CSEL.
3073 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3074 SelectionDAG &DAG) const {
3075 // Jump table entries as PC relative offsets. No additional tweaking
3076 // is necessary here. Just get the address of the jump table.
3077 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3078 EVT PtrVT = getPointerTy();
3081 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3082 !Subtarget->isTargetMachO()) {
3083 const unsigned char MO_NC = ARM64II::MO_NC;
3085 ARM64ISD::WrapperLarge, DL, PtrVT,
3086 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G3),
3087 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G2 | MO_NC),
3088 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G1 | MO_NC),
3089 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G0 | MO_NC));
3092 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3093 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3094 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3095 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3096 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3099 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3100 SelectionDAG &DAG) const {
3101 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3102 EVT PtrVT = getPointerTy();
3105 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3106 // Use the GOT for the large code model on iOS.
3107 if (Subtarget->isTargetMachO()) {
3108 SDValue GotAddr = DAG.getTargetConstantPool(
3109 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3111 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3114 const unsigned char MO_NC = ARM64II::MO_NC;
3116 ARM64ISD::WrapperLarge, DL, PtrVT,
3117 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3118 CP->getOffset(), ARM64II::MO_G3),
3119 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3120 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3121 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3122 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3123 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3124 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3126 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3127 // ELF, the only valid one on Darwin.
3129 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3130 CP->getOffset(), ARM64II::MO_PAGE);
3131 SDValue Lo = DAG.getTargetConstantPool(
3132 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3133 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3135 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3136 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3140 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3141 SelectionDAG &DAG) const {
3142 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3143 EVT PtrVT = getPointerTy();
3145 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3146 !Subtarget->isTargetMachO()) {
3147 const unsigned char MO_NC = ARM64II::MO_NC;
3149 ARM64ISD::WrapperLarge, DL, PtrVT,
3150 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3151 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3152 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3153 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3155 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3156 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3158 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3159 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3163 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3164 SelectionDAG &DAG) const {
3165 ARM64FunctionInfo *FuncInfo =
3166 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3170 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3171 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3172 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3173 MachinePointerInfo(SV), false, false, 0);
3176 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3177 SelectionDAG &DAG) const {
3178 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3179 // Standard, section B.3.
3180 MachineFunction &MF = DAG.getMachineFunction();
3181 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3184 SDValue Chain = Op.getOperand(0);
3185 SDValue VAList = Op.getOperand(1);
3186 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3187 SmallVector<SDValue, 4> MemOps;
3189 // void *__stack at offset 0
3191 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3192 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3193 MachinePointerInfo(SV), false, false, 8));
3195 // void *__gr_top at offset 8
3196 int GPRSize = FuncInfo->getVarArgsGPRSize();
3198 SDValue GRTop, GRTopAddr;
3200 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3201 DAG.getConstant(8, getPointerTy()));
3203 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3204 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3205 DAG.getConstant(GPRSize, getPointerTy()));
3207 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3208 MachinePointerInfo(SV, 8), false, false, 8));
3211 // void *__vr_top at offset 16
3212 int FPRSize = FuncInfo->getVarArgsFPRSize();
3214 SDValue VRTop, VRTopAddr;
3215 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3216 DAG.getConstant(16, getPointerTy()));
3218 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3219 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3220 DAG.getConstant(FPRSize, getPointerTy()));
3222 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3223 MachinePointerInfo(SV, 16), false, false, 8));
3226 // int __gr_offs at offset 24
3227 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3228 DAG.getConstant(24, getPointerTy()));
3229 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3230 GROffsAddr, MachinePointerInfo(SV, 24), false,
3233 // int __vr_offs at offset 28
3234 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3235 DAG.getConstant(28, getPointerTy()));
3236 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3237 VROffsAddr, MachinePointerInfo(SV, 28), false,
3240 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
3244 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3245 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3246 : LowerAAPCS_VASTART(Op, DAG);
3249 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3250 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3252 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3253 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3254 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3256 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3257 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3258 8, false, false, MachinePointerInfo(DestSV),
3259 MachinePointerInfo(SrcSV));
3262 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3263 assert(Subtarget->isTargetDarwin() &&
3264 "automatic va_arg instruction only works on Darwin");
3266 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3267 EVT VT = Op.getValueType();
3269 SDValue Chain = Op.getOperand(0);
3270 SDValue Addr = Op.getOperand(1);
3271 unsigned Align = Op.getConstantOperandVal(3);
3273 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3274 MachinePointerInfo(V), false, false, false, 0);
3275 Chain = VAList.getValue(1);
3278 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3279 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3280 DAG.getConstant(Align - 1, getPointerTy()));
3281 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3282 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3285 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3286 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3288 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3289 // up to 64 bits. At the very least, we have to increase the striding of the
3290 // vaargs list to match this, and for FP values we need to introduce
3291 // FP_ROUND nodes as well.
3292 if (VT.isInteger() && !VT.isVector())
3294 bool NeedFPTrunc = false;
3295 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3300 // Increment the pointer, VAList, to the next vaarg
3301 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3302 DAG.getConstant(ArgSize, getPointerTy()));
3303 // Store the incremented VAList to the legalized pointer
3304 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3307 // Load the actual argument out of the pointer VAList
3309 // Load the value as an f64.
3310 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3311 MachinePointerInfo(), false, false, false, 0);
3312 // Round the value down to an f32.
3313 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3314 DAG.getIntPtrConstant(1));
3315 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3316 // Merge the rounded value with the chain output of the load.
3317 return DAG.getMergeValues(Ops, 2, DL);
3320 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3324 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3325 SelectionDAG &DAG) const {
3326 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3327 MFI->setFrameAddressIsTaken(true);
3329 EVT VT = Op.getValueType();
3331 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3332 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3334 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3335 MachinePointerInfo(), false, false, false, 0);
3339 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3340 SelectionDAG &DAG) const {
3341 MachineFunction &MF = DAG.getMachineFunction();
3342 MachineFrameInfo *MFI = MF.getFrameInfo();
3343 MFI->setReturnAddressIsTaken(true);
3345 EVT VT = Op.getValueType();
3347 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3349 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3350 SDValue Offset = DAG.getConstant(8, getPointerTy());
3351 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3352 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3353 MachinePointerInfo(), false, false, false, 0);
3356 // Return LR, which contains the return address. Mark it an implicit live-in.
3357 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3358 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3361 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3362 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3363 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3364 SelectionDAG &DAG) const {
3365 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3366 EVT VT = Op.getValueType();
3367 unsigned VTBits = VT.getSizeInBits();
3369 SDValue ShOpLo = Op.getOperand(0);
3370 SDValue ShOpHi = Op.getOperand(1);
3371 SDValue ShAmt = Op.getOperand(2);
3373 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3375 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3377 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3378 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3379 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3380 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3381 DAG.getConstant(VTBits, MVT::i64));
3382 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3384 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3385 ISD::SETGE, dl, DAG);
3386 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3388 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3389 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3391 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3393 // ARM64 shifts larger than the register width are wrapped rather than
3394 // clamped, so we can't just emit "hi >> x".
3395 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3396 SDValue TrueValHi = Opc == ISD::SRA
3397 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3398 DAG.getConstant(VTBits - 1, MVT::i64))
3399 : DAG.getConstant(0, VT);
3401 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3403 SDValue Ops[2] = { Lo, Hi };
3404 return DAG.getMergeValues(Ops, 2, dl);
3407 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3408 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3409 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3410 SelectionDAG &DAG) const {
3411 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3412 EVT VT = Op.getValueType();
3413 unsigned VTBits = VT.getSizeInBits();
3415 SDValue ShOpLo = Op.getOperand(0);
3416 SDValue ShOpHi = Op.getOperand(1);
3417 SDValue ShAmt = Op.getOperand(2);
3420 assert(Op.getOpcode() == ISD::SHL_PARTS);
3421 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3422 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3423 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3424 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3425 DAG.getConstant(VTBits, MVT::i64));
3426 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3427 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3429 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3431 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3432 ISD::SETGE, dl, DAG);
3433 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3434 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3436 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3437 // so we can't just emit "lo << a" if a is too big.
3438 SDValue TrueValLo = DAG.getConstant(0, VT);
3439 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3441 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3443 SDValue Ops[2] = { Lo, Hi };
3444 return DAG.getMergeValues(Ops, 2, dl);
3448 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3449 // The ARM64 target doesn't support folding offsets into global addresses.
3453 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3454 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3455 // FIXME: We should be able to handle f128 as well with a clever lowering.
3456 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3460 return ARM64_AM::getFP64Imm(Imm) != -1;
3461 else if (VT == MVT::f32)
3462 return ARM64_AM::getFP32Imm(Imm) != -1;
3466 //===----------------------------------------------------------------------===//
3467 // ARM64 Optimization Hooks
3468 //===----------------------------------------------------------------------===//
3470 //===----------------------------------------------------------------------===//
3471 // ARM64 Inline Assembly Support
3472 //===----------------------------------------------------------------------===//
3474 // Table of Constraints
3475 // TODO: This is the current set of constraints supported by ARM for the
3476 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3478 // r - A general register
3479 // w - An FP/SIMD register of some size in the range v0-v31
3480 // x - An FP/SIMD register of some size in the range v0-v15
3481 // I - Constant that can be used with an ADD instruction
3482 // J - Constant that can be used with a SUB instruction
3483 // K - Constant that can be used with a 32-bit logical instruction
3484 // L - Constant that can be used with a 64-bit logical instruction
3485 // M - Constant that can be used as a 32-bit MOV immediate
3486 // N - Constant that can be used as a 64-bit MOV immediate
3487 // Q - A memory reference with base register and no offset
3488 // S - A symbolic address
3489 // Y - Floating point constant zero
3490 // Z - Integer constant zero
3492 // Note that general register operands will be output using their 64-bit x
3493 // register name, whatever the size of the variable, unless the asm operand
3494 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3495 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3498 /// getConstraintType - Given a constraint letter, return the type of
3499 /// constraint it is for this target.
3500 ARM64TargetLowering::ConstraintType
3501 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3502 if (Constraint.size() == 1) {
3503 switch (Constraint[0]) {
3510 return C_RegisterClass;
3511 // An address with a single base register. Due to the way we
3512 // currently handle addresses it is the same as 'r'.
3517 return TargetLowering::getConstraintType(Constraint);
3520 /// Examine constraint type and operand type and determine a weight value.
3521 /// This object must already have been set up with the operand type
3522 /// and the current alternative constraint selected.
3523 TargetLowering::ConstraintWeight
3524 ARM64TargetLowering::getSingleConstraintMatchWeight(
3525 AsmOperandInfo &info, const char *constraint) const {
3526 ConstraintWeight weight = CW_Invalid;
3527 Value *CallOperandVal = info.CallOperandVal;
3528 // If we don't have a value, we can't do a match,
3529 // but allow it at the lowest weight.
3530 if (CallOperandVal == NULL)
3532 Type *type = CallOperandVal->getType();
3533 // Look at the constraint type.
3534 switch (*constraint) {
3536 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3540 if (type->isFloatingPointTy() || type->isVectorTy())
3541 weight = CW_Register;
3544 weight = CW_Constant;
3550 std::pair<unsigned, const TargetRegisterClass *>
3551 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3553 if (Constraint.size() == 1) {
3554 switch (Constraint[0]) {
3556 if (VT.getSizeInBits() == 64)
3557 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3558 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3561 return std::make_pair(0U, &ARM64::FPR32RegClass);
3562 if (VT.getSizeInBits() == 64)
3563 return std::make_pair(0U, &ARM64::FPR64RegClass);
3564 if (VT.getSizeInBits() == 128)
3565 return std::make_pair(0U, &ARM64::FPR128RegClass);
3567 // The instructions that this constraint is designed for can
3568 // only take 128-bit registers so just use that regclass.
3570 if (VT.getSizeInBits() == 128)
3571 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
3575 if (StringRef("{cc}").equals_lower(Constraint))
3576 return std::make_pair(unsigned(ARM64::CPSR), &ARM64::CCRRegClass);
3578 // Use the default implementation in TargetLowering to convert the register
3579 // constraint into a member of a register class.
3580 std::pair<unsigned, const TargetRegisterClass *> Res;
3581 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3583 // Not found as a standard register?
3584 if (Res.second == 0) {
3585 unsigned Size = Constraint.size();
3586 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3587 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3588 const std::string Reg =
3589 std::string(&Constraint[2], &Constraint[Size - 1]);
3590 int RegNo = atoi(Reg.c_str());
3591 if (RegNo >= 0 && RegNo <= 31) {
3592 // v0 - v31 are aliases of q0 - q31.
3593 // By default we'll emit v0-v31 for this unless there's a modifier where
3594 // we'll emit the correct register as well.
3595 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
3596 Res.second = &ARM64::FPR128RegClass;
3604 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3605 /// vector. If it is invalid, don't add anything to Ops.
3606 void ARM64TargetLowering::LowerAsmOperandForConstraint(
3607 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3608 SelectionDAG &DAG) const {
3609 SDValue Result(0, 0);
3611 // Currently only support length 1 constraints.
3612 if (Constraint.length() != 1)
3615 char ConstraintLetter = Constraint[0];
3616 switch (ConstraintLetter) {
3620 // This set of constraints deal with valid constants for various instructions.
3621 // Validate and return a target constant for them if we can.
3623 // 'z' maps to xzr or wzr so it needs an input of 0.
3624 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3625 if (!C || C->getZExtValue() != 0)
3628 if (Op.getValueType() == MVT::i64)
3629 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
3631 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
3641 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3645 // Grab the value and do some validation.
3646 uint64_t CVal = C->getZExtValue();
3647 switch (ConstraintLetter) {
3648 // The I constraint applies only to simple ADD or SUB immediate operands:
3649 // i.e. 0 to 4095 with optional shift by 12
3650 // The J constraint applies only to ADD or SUB immediates that would be
3651 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
3652 // instruction [or vice versa], in other words -1 to -4095 with optional
3653 // left shift by 12.
3655 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
3659 uint64_t NVal = -C->getSExtValue();
3660 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
3664 // The K and L constraints apply *only* to logical immediates, including
3665 // what used to be the MOVI alias for ORR (though the MOVI alias has now
3666 // been removed and MOV should be used). So these constraints have to
3667 // distinguish between bit patterns that are valid 32-bit or 64-bit
3668 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
3669 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
3672 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3676 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3679 // The M and N constraints are a superset of K and L respectively, for use
3680 // with the MOV (immediate) alias. As well as the logical immediates they
3681 // also match 32 or 64-bit immediates that can be loaded either using a
3682 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
3683 // (M) or 64-bit 0x1234000000000000 (N) etc.
3684 // As a note some of this code is liberally stolen from the asm parser.
3686 if (!isUInt<32>(CVal))
3688 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3690 if ((CVal & 0xFFFF) == CVal)
3692 if ((CVal & 0xFFFF0000ULL) == CVal)
3694 uint64_t NCVal = ~(uint32_t)CVal;
3695 if ((NCVal & 0xFFFFULL) == NCVal)
3697 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3702 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3704 if ((CVal & 0xFFFFULL) == CVal)
3706 if ((CVal & 0xFFFF0000ULL) == CVal)
3708 if ((CVal & 0xFFFF00000000ULL) == CVal)
3710 if ((CVal & 0xFFFF000000000000ULL) == CVal)
3712 uint64_t NCVal = ~CVal;
3713 if ((NCVal & 0xFFFFULL) == NCVal)
3715 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3717 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
3719 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
3727 // All assembler immediates are 64-bit integers.
3728 Result = DAG.getTargetConstant(CVal, MVT::i64);
3732 if (Result.getNode()) {
3733 Ops.push_back(Result);
3737 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3740 //===----------------------------------------------------------------------===//
3741 // ARM64 Advanced SIMD Support
3742 //===----------------------------------------------------------------------===//
3744 /// WidenVector - Given a value in the V64 register class, produce the
3745 /// equivalent value in the V128 register class.
3746 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
3747 EVT VT = V64Reg.getValueType();
3748 unsigned NarrowSize = VT.getVectorNumElements();
3749 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3750 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
3753 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
3754 V64Reg, DAG.getConstant(0, MVT::i32));
3757 /// getExtFactor - Determine the adjustment factor for the position when
3758 /// generating an "extract from vector registers" instruction.
3759 static unsigned getExtFactor(SDValue &V) {
3760 EVT EltType = V.getValueType().getVectorElementType();
3761 return EltType.getSizeInBits() / 8;
3764 /// NarrowVector - Given a value in the V128 register class, produce the
3765 /// equivalent value in the V64 register class.
3766 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
3767 EVT VT = V128Reg.getValueType();
3768 unsigned WideSize = VT.getVectorNumElements();
3769 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3770 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
3773 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
3776 // Gather data to see if the operation can be modelled as a
3777 // shuffle in combination with VEXTs.
3778 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
3779 SelectionDAG &DAG) const {
3781 EVT VT = Op.getValueType();
3782 unsigned NumElts = VT.getVectorNumElements();
3784 SmallVector<SDValue, 2> SourceVecs;
3785 SmallVector<unsigned, 2> MinElts;
3786 SmallVector<unsigned, 2> MaxElts;
3788 for (unsigned i = 0; i < NumElts; ++i) {
3789 SDValue V = Op.getOperand(i);
3790 if (V.getOpcode() == ISD::UNDEF)
3792 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3793 // A shuffle can only come from building a vector from various
3794 // elements of other vectors.
3798 // Record this extraction against the appropriate vector if possible...
3799 SDValue SourceVec = V.getOperand(0);
3800 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3801 bool FoundSource = false;
3802 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3803 if (SourceVecs[j] == SourceVec) {
3804 if (MinElts[j] > EltNo)
3806 if (MaxElts[j] < EltNo)
3813 // Or record a new source if not...
3815 SourceVecs.push_back(SourceVec);
3816 MinElts.push_back(EltNo);
3817 MaxElts.push_back(EltNo);
3821 // Currently only do something sane when at most two source vectors
3823 if (SourceVecs.size() > 2)
3826 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3827 int VEXTOffsets[2] = { 0, 0 };
3829 // This loop extracts the usage patterns of the source vectors
3830 // and prepares appropriate SDValues for a shuffle if possible.
3831 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3832 if (SourceVecs[i].getValueType() == VT) {
3833 // No VEXT necessary
3834 ShuffleSrcs[i] = SourceVecs[i];
3837 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3838 // We can pad out the smaller vector for free, so if it's part of a
3840 ShuffleSrcs[i] = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, SourceVecs[i],
3841 DAG.getUNDEF(SourceVecs[i].getValueType()));
3845 // Don't attempt to extract subvectors from BUILD_VECTOR sources
3846 // that expand or trunc the original value.
3847 // TODO: We can try to bitcast and ANY_EXTEND the result but
3848 // we need to consider the cost of vector ANY_EXTEND, and the
3849 // legality of all the types.
3850 if (SourceVecs[i].getValueType().getVectorElementType() !=
3851 VT.getVectorElementType())
3854 // Since only 64-bit and 128-bit vectors are legal on ARM and
3855 // we've eliminated the other cases...
3856 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3857 "unexpected vector sizes in ReconstructShuffle");
3859 if (MaxElts[i] - MinElts[i] >= NumElts) {
3860 // Span too large for a VEXT to cope
3864 if (MinElts[i] >= NumElts) {
3865 // The extraction can just take the second half
3866 VEXTOffsets[i] = NumElts;
3868 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3869 DAG.getIntPtrConstant(NumElts));
3870 } else if (MaxElts[i] < NumElts) {
3871 // The extraction can just take the first half
3873 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3874 SourceVecs[i], DAG.getIntPtrConstant(0));
3876 // An actual VEXT is needed
3877 VEXTOffsets[i] = MinElts[i];
3878 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3879 SourceVecs[i], DAG.getIntPtrConstant(0));
3881 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3882 DAG.getIntPtrConstant(NumElts));
3883 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
3884 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
3885 DAG.getConstant(Imm, MVT::i32));
3889 SmallVector<int, 8> Mask;
3891 for (unsigned i = 0; i < NumElts; ++i) {
3892 SDValue Entry = Op.getOperand(i);
3893 if (Entry.getOpcode() == ISD::UNDEF) {
3898 SDValue ExtractVec = Entry.getOperand(0);
3900 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
3901 if (ExtractVec == SourceVecs[0]) {
3902 Mask.push_back(ExtractElt - VEXTOffsets[0]);
3904 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
3908 // Final check before we try to produce nonsense...
3909 if (isShuffleMaskLegal(Mask, VT))
3910 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
3916 // check if an EXT instruction can handle the shuffle mask when the
3917 // vector sources of the shuffle are the same.
3918 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3919 unsigned NumElts = VT.getVectorNumElements();
3921 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3927 // If this is a VEXT shuffle, the immediate value is the index of the first
3928 // element. The other shuffle indices must be the successive elements after
3930 unsigned ExpectedElt = Imm;
3931 for (unsigned i = 1; i < NumElts; ++i) {
3932 // Increment the expected index. If it wraps around, just follow it
3933 // back to index zero and keep going.
3935 if (ExpectedElt == NumElts)
3939 continue; // ignore UNDEF indices
3940 if (ExpectedElt != static_cast<unsigned>(M[i]))
3947 // check if an EXT instruction can handle the shuffle mask when the
3948 // vector sources of the shuffle are different.
3949 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
3951 unsigned NumElts = VT.getVectorNumElements();
3954 // Look for the first non-undef choice and count backwards from
3955 // that. E.g. <-1, -1, 3, ...> means that an EXT must start at 3 - 2 = 1. This
3956 // guarantees that at least one index is correct.
3957 const int *FirstRealElt =
3958 std::find_if(M.begin(), M.end(), [](int Elt) { return Elt >= 0; });
3959 assert(FirstRealElt != M.end() && "Completely UNDEF shuffle? Why bother?");
3960 Imm = *FirstRealElt - (FirstRealElt - M.begin());
3962 // If this is a VEXT shuffle, the immediate value is the index of the first
3963 // element. The other shuffle indices must be the successive elements after
3965 unsigned ExpectedElt = Imm;
3966 for (unsigned i = 1; i < NumElts; ++i) {
3967 // Increment the expected index. If it wraps around, it may still be
3968 // a VEXT but the source vectors must be swapped.
3970 if (ExpectedElt == NumElts * 2) {
3976 continue; // ignore UNDEF indices
3977 if (ExpectedElt != static_cast<unsigned>(M[i]))
3981 // Adjust the index value if the source operands will be swapped.
3988 /// isREVMask - Check if a vector shuffle corresponds to a REV
3989 /// instruction with the specified blocksize. (The order of the elements
3990 /// within each block of the vector is reversed.)
3991 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3992 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
3993 "Only possible block sizes for REV are: 16, 32, 64");
3995 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3999 unsigned NumElts = VT.getVectorNumElements();
4000 unsigned BlockElts = M[0] + 1;
4001 // If the first shuffle index is UNDEF, be optimistic.
4003 BlockElts = BlockSize / EltSz;
4005 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4008 for (unsigned i = 0; i < NumElts; ++i) {
4010 continue; // ignore UNDEF indices
4011 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4018 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4019 unsigned NumElts = VT.getVectorNumElements();
4020 WhichResult = (M[0] == 0 ? 0 : 1);
4021 unsigned Idx = WhichResult * NumElts / 2;
4022 for (unsigned i = 0; i != NumElts; i += 2) {
4023 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4024 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4032 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4033 unsigned NumElts = VT.getVectorNumElements();
4034 WhichResult = (M[0] == 0 ? 0 : 1);
4035 for (unsigned i = 0; i != NumElts; ++i) {
4037 continue; // ignore UNDEF indices
4038 if ((unsigned)M[i] != 2 * i + WhichResult)
4045 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4046 unsigned NumElts = VT.getVectorNumElements();
4047 WhichResult = (M[0] == 0 ? 0 : 1);
4048 for (unsigned i = 0; i < NumElts; i += 2) {
4049 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4050 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4056 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4057 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4058 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4059 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4060 unsigned NumElts = VT.getVectorNumElements();
4061 WhichResult = (M[0] == 0 ? 0 : 1);
4062 unsigned Idx = WhichResult * NumElts / 2;
4063 for (unsigned i = 0; i != NumElts; i += 2) {
4064 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4065 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4073 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4074 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4075 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4076 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4077 unsigned Half = VT.getVectorNumElements() / 2;
4078 WhichResult = (M[0] == 0 ? 0 : 1);
4079 for (unsigned j = 0; j != 2; ++j) {
4080 unsigned Idx = WhichResult;
4081 for (unsigned i = 0; i != Half; ++i) {
4082 int MIdx = M[i + j * Half];
4083 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4092 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4093 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4094 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4095 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4096 unsigned NumElts = VT.getVectorNumElements();
4097 WhichResult = (M[0] == 0 ? 0 : 1);
4098 for (unsigned i = 0; i < NumElts; i += 2) {
4099 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4100 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4106 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4107 bool &DstIsLeft, int &Anomaly) {
4108 if (M.size() != static_cast<size_t>(NumInputElements))
4111 int NumLHSMatch = 0, NumRHSMatch = 0;
4112 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4114 for (int i = 0; i < NumInputElements; ++i) {
4124 LastLHSMismatch = i;
4126 if (M[i] == i + NumInputElements)
4129 LastRHSMismatch = i;
4132 if (NumLHSMatch == NumInputElements - 1) {
4134 Anomaly = LastLHSMismatch;
4136 } else if (NumRHSMatch == NumInputElements - 1) {
4138 Anomaly = LastRHSMismatch;
4145 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4146 if (VT.getSizeInBits() != 128)
4149 unsigned NumElts = VT.getVectorNumElements();
4151 for (int I = 0, E = NumElts / 2; I != E; I++) {
4156 int Offset = NumElts / 2;
4157 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4158 if (Mask[I] != I + SplitLHS * Offset)
4165 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4167 EVT VT = Op.getValueType();
4168 SDValue V0 = Op.getOperand(0);
4169 SDValue V1 = Op.getOperand(1);
4170 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4172 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4173 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4176 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4178 if (!isConcatMask(Mask, VT, SplitV0))
4181 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4182 VT.getVectorNumElements() / 2);
4184 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4185 DAG.getConstant(0, MVT::i64));
4187 if (V1.getValueType().getSizeInBits() == 128) {
4188 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4189 DAG.getConstant(0, MVT::i64));
4191 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4194 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4195 /// the specified operations to build the shuffle.
4196 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4197 SDValue RHS, SelectionDAG &DAG,
4199 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4200 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4201 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4204 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4213 OP_VUZPL, // VUZP, left result
4214 OP_VUZPR, // VUZP, right result
4215 OP_VZIPL, // VZIP, left result
4216 OP_VZIPR, // VZIP, right result
4217 OP_VTRNL, // VTRN, left result
4218 OP_VTRNR // VTRN, right result
4221 if (OpNum == OP_COPY) {
4222 if (LHSID == (1 * 9 + 2) * 9 + 3)
4224 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4228 SDValue OpLHS, OpRHS;
4229 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4230 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4231 EVT VT = OpLHS.getValueType();
4235 llvm_unreachable("Unknown shuffle opcode!");
4237 // VREV divides the vector in half and swaps within the half.
4238 if (VT.getVectorElementType() == MVT::i32 ||
4239 VT.getVectorElementType() == MVT::f32)
4240 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4241 // vrev <4 x i16> -> REV32
4242 if (VT.getVectorElementType() == MVT::i16)
4243 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4244 // vrev <4 x i8> -> REV16
4245 assert(VT.getVectorElementType() == MVT::i8);
4246 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4251 EVT EltTy = VT.getVectorElementType();
4253 if (EltTy == MVT::i8)
4254 Opcode = ARM64ISD::DUPLANE8;
4255 else if (EltTy == MVT::i16)
4256 Opcode = ARM64ISD::DUPLANE16;
4257 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4258 Opcode = ARM64ISD::DUPLANE32;
4259 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4260 Opcode = ARM64ISD::DUPLANE64;
4262 llvm_unreachable("Invalid vector element type?");
4264 if (VT.getSizeInBits() == 64)
4265 OpLHS = WidenVector(OpLHS, DAG);
4266 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4267 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4272 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4273 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4274 DAG.getConstant(Imm, MVT::i32));
4277 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4279 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4281 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4283 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4285 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4287 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4291 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4292 SelectionDAG &DAG) {
4293 // Check to see if we can use the TBL instruction.
4294 SDValue V1 = Op.getOperand(0);
4295 SDValue V2 = Op.getOperand(1);
4298 EVT EltVT = Op.getValueType().getVectorElementType();
4299 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4301 SmallVector<SDValue, 8> TBLMask;
4302 for (int Val : ShuffleMask) {
4303 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4304 unsigned Offset = Byte + Val * BytesPerElt;
4305 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4309 MVT IndexVT = MVT::v8i8;
4310 unsigned IndexLen = 8;
4311 if (Op.getValueType().getSizeInBits() == 128) {
4312 IndexVT = MVT::v16i8;
4316 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4317 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4320 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4322 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4323 Shuffle = DAG.getNode(
4324 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4325 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4326 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4328 if (IndexLen == 8) {
4329 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4330 Shuffle = DAG.getNode(
4331 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4332 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4333 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4335 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4336 // cannot currently represent the register constraints on the input
4338 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4339 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4340 // &TBLMask[0], IndexLen));
4341 Shuffle = DAG.getNode(
4342 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4343 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4344 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4347 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4350 static unsigned getDUPLANEOp(EVT EltType) {
4351 if (EltType == MVT::i8)
4352 return ARM64ISD::DUPLANE8;
4353 if (EltType == MVT::i16)
4354 return ARM64ISD::DUPLANE16;
4355 if (EltType == MVT::i32 || EltType == MVT::f32)
4356 return ARM64ISD::DUPLANE32;
4357 if (EltType == MVT::i64 || EltType == MVT::f64)
4358 return ARM64ISD::DUPLANE64;
4360 llvm_unreachable("Invalid vector element type?");
4363 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4364 SelectionDAG &DAG) const {
4366 EVT VT = Op.getValueType();
4368 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4370 // Convert shuffles that are directly supported on NEON to target-specific
4371 // DAG nodes, instead of keeping them as shuffles and matching them again
4372 // during code selection. This is more efficient and avoids the possibility
4373 // of inconsistencies between legalization and selection.
4374 ArrayRef<int> ShuffleMask = SVN->getMask();
4376 SDValue V1 = Op.getOperand(0);
4377 SDValue V2 = Op.getOperand(1);
4379 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4380 V1.getValueType().getSimpleVT())) {
4381 int Lane = SVN->getSplatIndex();
4382 // If this is undef splat, generate it via "just" vdup, if possible.
4386 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4387 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4389 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4390 // constant. If so, we can just reference the lane's definition directly.
4391 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4392 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4393 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4395 // Otherwise, duplicate from the lane of the input vector.
4396 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4398 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4399 // to make a vector of the same size as this SHUFFLE. We can ignore the
4400 // extract entirely, and canonicalise the concat using WidenVector.
4401 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4402 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4403 V1 = V1.getOperand(0);
4404 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4405 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4406 Lane -= Idx * VT.getVectorNumElements() / 2;
4407 V1 = WidenVector(V1.getOperand(Idx), DAG);
4408 } else if (VT.getSizeInBits() == 64)
4409 V1 = WidenVector(V1, DAG);
4411 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4414 if (isREVMask(ShuffleMask, VT, 64))
4415 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4416 if (isREVMask(ShuffleMask, VT, 32))
4417 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4418 if (isREVMask(ShuffleMask, VT, 16))
4419 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4421 bool ReverseEXT = false;
4423 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4426 Imm *= getExtFactor(V1);
4427 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4428 DAG.getConstant(Imm, MVT::i32));
4429 } else if (V2->getOpcode() == ISD::UNDEF &&
4430 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4431 Imm *= getExtFactor(V1);
4432 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4433 DAG.getConstant(Imm, MVT::i32));
4436 unsigned WhichResult;
4437 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4438 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4439 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4441 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4442 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4443 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4445 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4446 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4447 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4450 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4451 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4452 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4454 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4455 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4456 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4458 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4459 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4460 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4463 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4464 if (Concat.getNode())
4469 int NumInputElements = V1.getValueType().getVectorNumElements();
4470 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4471 SDValue DstVec = DstIsLeft ? V1 : V2;
4472 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4474 SDValue SrcVec = V1;
4475 int SrcLane = ShuffleMask[Anomaly];
4476 if (SrcLane >= NumInputElements) {
4478 SrcLane -= VT.getVectorNumElements();
4480 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4482 EVT ScalarVT = VT.getVectorElementType();
4483 if (ScalarVT.getSizeInBits() < 32)
4484 ScalarVT = MVT::i32;
4487 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4488 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4492 // If the shuffle is not directly supported and it has 4 elements, use
4493 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4494 unsigned NumElts = VT.getVectorNumElements();
4496 unsigned PFIndexes[4];
4497 for (unsigned i = 0; i != 4; ++i) {
4498 if (ShuffleMask[i] < 0)
4501 PFIndexes[i] = ShuffleMask[i];
4504 // Compute the index in the perfect shuffle table.
4505 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4506 PFIndexes[2] * 9 + PFIndexes[3];
4507 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4508 unsigned Cost = (PFEntry >> 30);
4511 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4514 return GenerateTBL(Op, ShuffleMask, DAG);
4517 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4519 EVT VT = BVN->getValueType(0);
4520 APInt SplatBits, SplatUndef;
4521 unsigned SplatBitSize;
4523 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4524 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4526 for (unsigned i = 0; i < NumSplats; ++i) {
4527 CnstBits <<= SplatBitSize;
4528 UndefBits <<= SplatBitSize;
4529 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4530 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4539 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4540 SelectionDAG &DAG) const {
4541 BuildVectorSDNode *BVN =
4542 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4543 SDValue LHS = Op.getOperand(0);
4545 EVT VT = Op.getValueType();
4550 APInt CnstBits(VT.getSizeInBits(), 0);
4551 APInt UndefBits(VT.getSizeInBits(), 0);
4552 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4553 // We only have BIC vector immediate instruction, which is and-not.
4554 CnstBits = ~CnstBits;
4556 // We make use of a little bit of goto ickiness in order to avoid having to
4557 // duplicate the immediate matching logic for the undef toggled case.
4558 bool SecondTry = false;
4561 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4562 CnstBits = CnstBits.zextOrTrunc(64);
4563 uint64_t CnstVal = CnstBits.getZExtValue();
4565 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4566 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4567 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4568 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4569 DAG.getConstant(CnstVal, MVT::i32),
4570 DAG.getConstant(0, MVT::i32));
4571 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4574 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4575 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4576 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4577 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4578 DAG.getConstant(CnstVal, MVT::i32),
4579 DAG.getConstant(8, MVT::i32));
4580 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4583 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4584 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4585 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4586 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4587 DAG.getConstant(CnstVal, MVT::i32),
4588 DAG.getConstant(16, MVT::i32));
4589 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4592 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4593 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4594 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4595 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4596 DAG.getConstant(CnstVal, MVT::i32),
4597 DAG.getConstant(24, MVT::i32));
4598 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4601 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4602 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4603 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4604 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4605 DAG.getConstant(CnstVal, MVT::i32),
4606 DAG.getConstant(0, MVT::i32));
4607 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4610 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4611 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4612 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4613 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4614 DAG.getConstant(CnstVal, MVT::i32),
4615 DAG.getConstant(8, MVT::i32));
4616 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4623 CnstBits = ~UndefBits;
4627 // We can always fall back to a non-immediate AND.
4632 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4633 // consists of only the same constant int value, returned in reference arg
4635 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4636 uint64_t &ConstVal) {
4637 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4640 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4643 EVT VT = Bvec->getValueType(0);
4644 unsigned NumElts = VT.getVectorNumElements();
4645 for (unsigned i = 1; i < NumElts; ++i)
4646 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4648 ConstVal = FirstElt->getZExtValue();
4652 static unsigned getIntrinsicID(const SDNode *N) {
4653 unsigned Opcode = N->getOpcode();
4656 return Intrinsic::not_intrinsic;
4657 case ISD::INTRINSIC_WO_CHAIN: {
4658 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4659 if (IID < Intrinsic::num_intrinsics)
4661 return Intrinsic::not_intrinsic;
4666 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4667 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4668 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4669 // Also, logical shift right -> sri, with the same structure.
4670 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4671 EVT VT = N->getValueType(0);
4678 // Is the first op an AND?
4679 const SDValue And = N->getOperand(0);
4680 if (And.getOpcode() != ISD::AND)
4683 // Is the second op an shl or lshr?
4684 SDValue Shift = N->getOperand(1);
4685 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4686 // or ARM64ISD::VLSHR vector, #shift
4687 unsigned ShiftOpc = Shift.getOpcode();
4688 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4690 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4692 // Is the shift amount constant?
4693 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4697 // Is the and mask vector all constant?
4699 if (!isAllConstantBuildVector(And.getOperand(1), C1))
4702 // Is C1 == ~C2, taking into account how much one can shift elements of a
4704 uint64_t C2 = C2node->getZExtValue();
4705 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4706 if (C2 > ElemSizeInBits)
4708 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4709 if ((C1 & ElemMask) != (~C2 & ElemMask))
4712 SDValue X = And.getOperand(0);
4713 SDValue Y = Shift.getOperand(0);
4716 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4718 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4719 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4721 DEBUG(dbgs() << "arm64-lower: transformed: \n");
4722 DEBUG(N->dump(&DAG));
4723 DEBUG(dbgs() << "into: \n");
4724 DEBUG(ResultSLI->dump(&DAG));
4730 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4731 SelectionDAG &DAG) const {
4732 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4733 if (EnableARM64SlrGeneration) {
4734 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4739 BuildVectorSDNode *BVN =
4740 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4741 SDValue LHS = Op.getOperand(1);
4743 EVT VT = Op.getValueType();
4745 // OR commutes, so try swapping the operands.
4747 LHS = Op.getOperand(0);
4748 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4753 APInt CnstBits(VT.getSizeInBits(), 0);
4754 APInt UndefBits(VT.getSizeInBits(), 0);
4755 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4756 // We make use of a little bit of goto ickiness in order to avoid having to
4757 // duplicate the immediate matching logic for the undef toggled case.
4758 bool SecondTry = false;
4761 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4762 CnstBits = CnstBits.zextOrTrunc(64);
4763 uint64_t CnstVal = CnstBits.getZExtValue();
4765 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4766 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4767 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4768 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4769 DAG.getConstant(CnstVal, MVT::i32),
4770 DAG.getConstant(0, MVT::i32));
4771 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4774 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4775 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4776 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4777 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4778 DAG.getConstant(CnstVal, MVT::i32),
4779 DAG.getConstant(8, MVT::i32));
4780 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4783 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4784 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4785 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4786 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4787 DAG.getConstant(CnstVal, MVT::i32),
4788 DAG.getConstant(16, MVT::i32));
4789 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4792 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4793 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4794 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4795 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4796 DAG.getConstant(CnstVal, MVT::i32),
4797 DAG.getConstant(24, MVT::i32));
4798 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4801 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4802 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4803 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4804 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4805 DAG.getConstant(CnstVal, MVT::i32),
4806 DAG.getConstant(0, MVT::i32));
4807 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4810 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4811 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4812 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4813 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4814 DAG.getConstant(CnstVal, MVT::i32),
4815 DAG.getConstant(8, MVT::i32));
4816 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4823 CnstBits = UndefBits;
4827 // We can always fall back to a non-immediate OR.
4832 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4833 SelectionDAG &DAG) const {
4834 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4836 EVT VT = Op.getValueType();
4838 APInt CnstBits(VT.getSizeInBits(), 0);
4839 APInt UndefBits(VT.getSizeInBits(), 0);
4840 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4841 // We make use of a little bit of goto ickiness in order to avoid having to
4842 // duplicate the immediate matching logic for the undef toggled case.
4843 bool SecondTry = false;
4846 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4847 CnstBits = CnstBits.zextOrTrunc(64);
4848 uint64_t CnstVal = CnstBits.getZExtValue();
4850 // Certain magic vector constants (used to express things like NOT
4851 // and NEG) are passed through unmodified. This allows codegen patterns
4852 // for these operations to match. Special-purpose patterns will lower
4853 // these immediates to MOVIs if it proves necessary.
4854 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4857 // The many faces of MOVI...
4858 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4859 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4860 if (VT.getSizeInBits() == 128) {
4861 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4862 DAG.getConstant(CnstVal, MVT::i32));
4863 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4866 // Support the V64 version via subregister insertion.
4867 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4868 DAG.getConstant(CnstVal, MVT::i32));
4869 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4872 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4873 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4874 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4875 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4876 DAG.getConstant(CnstVal, MVT::i32),
4877 DAG.getConstant(0, MVT::i32));
4878 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4881 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4882 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4883 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4884 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4885 DAG.getConstant(CnstVal, MVT::i32),
4886 DAG.getConstant(8, MVT::i32));
4887 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4890 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4891 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4892 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4893 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4894 DAG.getConstant(CnstVal, MVT::i32),
4895 DAG.getConstant(16, MVT::i32));
4896 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4899 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4900 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4901 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4902 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4903 DAG.getConstant(CnstVal, MVT::i32),
4904 DAG.getConstant(24, MVT::i32));
4905 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4908 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4909 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4910 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4911 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4912 DAG.getConstant(CnstVal, MVT::i32),
4913 DAG.getConstant(0, MVT::i32));
4914 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4917 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4918 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4919 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4920 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4921 DAG.getConstant(CnstVal, MVT::i32),
4922 DAG.getConstant(8, MVT::i32));
4923 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4926 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4927 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4928 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4929 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4930 DAG.getConstant(CnstVal, MVT::i32),
4931 DAG.getConstant(264, MVT::i32));
4932 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4935 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4936 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
4937 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4938 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4939 DAG.getConstant(CnstVal, MVT::i32),
4940 DAG.getConstant(272, MVT::i32));
4941 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4944 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
4945 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
4946 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
4947 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
4948 DAG.getConstant(CnstVal, MVT::i32));
4949 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4952 // The few faces of FMOV...
4953 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
4954 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
4955 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
4956 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
4957 DAG.getConstant(CnstVal, MVT::i32));
4958 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4961 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
4962 VT.getSizeInBits() == 128) {
4963 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
4964 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
4965 DAG.getConstant(CnstVal, MVT::i32));
4966 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4969 // The many faces of MVNI...
4971 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4972 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4973 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4974 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4975 DAG.getConstant(CnstVal, MVT::i32),
4976 DAG.getConstant(0, MVT::i32));
4977 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4980 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4981 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4982 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4983 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4984 DAG.getConstant(CnstVal, MVT::i32),
4985 DAG.getConstant(8, MVT::i32));
4986 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4989 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4990 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4991 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4992 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4993 DAG.getConstant(CnstVal, MVT::i32),
4994 DAG.getConstant(16, MVT::i32));
4995 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4998 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4999 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5000 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5001 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5002 DAG.getConstant(CnstVal, MVT::i32),
5003 DAG.getConstant(24, MVT::i32));
5004 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5007 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5008 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5009 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5010 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5011 DAG.getConstant(CnstVal, MVT::i32),
5012 DAG.getConstant(0, MVT::i32));
5013 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5016 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5017 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5018 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5019 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5020 DAG.getConstant(CnstVal, MVT::i32),
5021 DAG.getConstant(8, MVT::i32));
5022 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5025 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5026 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5027 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5028 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5029 DAG.getConstant(CnstVal, MVT::i32),
5030 DAG.getConstant(264, MVT::i32));
5031 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5034 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5035 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5036 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5037 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5038 DAG.getConstant(CnstVal, MVT::i32),
5039 DAG.getConstant(272, MVT::i32));
5040 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5047 CnstBits = UndefBits;
5052 // Scan through the operands to find some interesting properties we can
5054 // 1) If only one value is used, we can use a DUP, or
5055 // 2) if only the low element is not undef, we can just insert that, or
5056 // 3) if only one constant value is used (w/ some non-constant lanes),
5057 // we can splat the constant value into the whole vector then fill
5058 // in the non-constant lanes.
5059 // 4) FIXME: If different constant values are used, but we can intelligently
5060 // select the values we'll be overwriting for the non-constant
5061 // lanes such that we can directly materialize the vector
5062 // some other way (MOVI, e.g.), we can be sneaky.
5063 unsigned NumElts = VT.getVectorNumElements();
5064 bool isOnlyLowElement = true;
5065 bool usesOnlyOneValue = true;
5066 bool usesOnlyOneConstantValue = true;
5067 bool isConstant = true;
5068 unsigned NumConstantLanes = 0;
5070 SDValue ConstantValue;
5071 for (unsigned i = 0; i < NumElts; ++i) {
5072 SDValue V = Op.getOperand(i);
5073 if (V.getOpcode() == ISD::UNDEF)
5076 isOnlyLowElement = false;
5077 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5080 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5082 if (!ConstantValue.getNode())
5084 else if (ConstantValue != V)
5085 usesOnlyOneConstantValue = false;
5088 if (!Value.getNode())
5090 else if (V != Value)
5091 usesOnlyOneValue = false;
5094 if (!Value.getNode())
5095 return DAG.getUNDEF(VT);
5097 if (isOnlyLowElement)
5098 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5100 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5101 // i32 and try again.
5102 if (usesOnlyOneValue) {
5104 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5105 Value.getValueType() != VT)
5106 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5108 // This is actually a DUPLANExx operation, which keeps everything vectory.
5110 // DUPLANE works on 128-bit vectors, widen it if necessary.
5111 SDValue Lane = Value.getOperand(1);
5112 Value = Value.getOperand(0);
5113 if (Value.getValueType().getSizeInBits() == 64)
5114 Value = WidenVector(Value, DAG);
5116 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5117 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5120 if (VT.getVectorElementType().isFloatingPoint()) {
5121 SmallVector<SDValue, 8> Ops;
5123 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5124 for (unsigned i = 0; i < NumElts; ++i)
5125 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5126 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5127 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
5128 Val = LowerBUILD_VECTOR(Val, DAG);
5130 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5134 // If there was only one constant value used and for more than one lane,
5135 // start by splatting that value, then replace the non-constant lanes. This
5136 // is better than the default, which will perform a separate initialization
5138 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5139 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5140 // Now insert the non-constant lanes.
5141 for (unsigned i = 0; i < NumElts; ++i) {
5142 SDValue V = Op.getOperand(i);
5143 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5144 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5145 // Note that type legalization likely mucked about with the VT of the
5146 // source operand, so we may have to convert it here before inserting.
5147 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5153 // If all elements are constants and the case above didn't get hit, fall back
5154 // to the default expansion, which will generate a load from the constant
5159 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5161 SDValue shuffle = ReconstructShuffle(Op, DAG);
5162 if (shuffle != SDValue())
5166 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5167 // know the default expansion would otherwise fall back on something even
5168 // worse. For a vector with one or two non-undef values, that's
5169 // scalar_to_vector for the elements followed by a shuffle (provided the
5170 // shuffle is valid for the target) and materialization element by element
5171 // on the stack followed by a load for everything else.
5172 if (!isConstant && !usesOnlyOneValue) {
5173 SDValue Vec = DAG.getUNDEF(VT);
5174 SDValue Op0 = Op.getOperand(0);
5175 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5177 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5178 // a) Avoid a RMW dependency on the full vector register, and
5179 // b) Allow the register coalescer to fold away the copy if the
5180 // value is already in an S or D register.
5181 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5182 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5184 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5185 DAG.getTargetConstant(SubIdx, MVT::i32));
5186 Vec = SDValue(N, 0);
5189 for (; i < NumElts; ++i) {
5190 SDValue V = Op.getOperand(i);
5191 if (V.getOpcode() == ISD::UNDEF)
5193 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5194 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5199 // Just use the default expansion. We failed to find a better alternative.
5203 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5204 SelectionDAG &DAG) const {
5205 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5207 // Check for non-constant lane.
5208 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5211 EVT VT = Op.getOperand(0).getValueType();
5213 // Insertion/extraction are legal for V128 types.
5214 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5215 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5218 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5219 VT != MVT::v1i64 && VT != MVT::v2f32)
5222 // For V64 types, we perform insertion by expanding the value
5223 // to a V128 type and perform the insertion on that.
5225 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5226 EVT WideTy = WideVec.getValueType();
5228 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5229 Op.getOperand(1), Op.getOperand(2));
5230 // Re-narrow the resultant vector.
5231 return NarrowVector(Node, DAG);
5234 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5235 SelectionDAG &DAG) const {
5236 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5238 // Check for non-constant lane.
5239 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5242 EVT VT = Op.getOperand(0).getValueType();
5244 // Insertion/extraction are legal for V128 types.
5245 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5246 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5249 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5250 VT != MVT::v1i64 && VT != MVT::v2f32)
5253 // For V64 types, we perform extraction by expanding the value
5254 // to a V128 type and perform the extraction on that.
5256 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5257 EVT WideTy = WideVec.getValueType();
5259 EVT ExtrTy = WideTy.getVectorElementType();
5260 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5263 // For extractions, we just return the result directly.
5264 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5268 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5269 SelectionDAG &DAG) const {
5270 EVT VT = Op.getOperand(0).getValueType();
5276 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5279 unsigned Val = Cst->getZExtValue();
5281 unsigned Size = Op.getValueType().getSizeInBits();
5285 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5288 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5291 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5294 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5297 llvm_unreachable("Unexpected vector type in extract_subvector!");
5300 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5302 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5308 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5310 if (VT.getVectorNumElements() == 4 &&
5311 (VT.is128BitVector() || VT.is64BitVector())) {
5312 unsigned PFIndexes[4];
5313 for (unsigned i = 0; i != 4; ++i) {
5317 PFIndexes[i] = M[i];
5320 // Compute the index in the perfect shuffle table.
5321 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5322 PFIndexes[2] * 9 + PFIndexes[3];
5323 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5324 unsigned Cost = (PFEntry >> 30);
5332 unsigned DummyUnsigned;
5334 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5335 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5336 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5337 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5338 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5339 isZIPMask(M, VT, DummyUnsigned) ||
5340 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5341 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5342 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5343 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5344 isConcatMask(M, VT, VT.getSizeInBits() == 128));
5347 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5348 /// operand of a vector shift operation, where all the elements of the
5349 /// build_vector must have the same constant integer value.
5350 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5351 // Ignore bit_converts.
5352 while (Op.getOpcode() == ISD::BITCAST)
5353 Op = Op.getOperand(0);
5354 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5355 APInt SplatBits, SplatUndef;
5356 unsigned SplatBitSize;
5358 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5359 HasAnyUndefs, ElementBits) ||
5360 SplatBitSize > ElementBits)
5362 Cnt = SplatBits.getSExtValue();
5366 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5367 /// operand of a vector shift left operation. That value must be in the range:
5368 /// 0 <= Value < ElementBits for a left shift; or
5369 /// 0 <= Value <= ElementBits for a long left shift.
5370 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5371 assert(VT.isVector() && "vector shift count is not a vector type");
5372 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5373 if (!getVShiftImm(Op, ElementBits, Cnt))
5375 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5378 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5379 /// operand of a vector shift right operation. For a shift opcode, the value
5380 /// is positive, but for an intrinsic the value count must be negative. The
5381 /// absolute value must be in the range:
5382 /// 1 <= |Value| <= ElementBits for a right shift; or
5383 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5384 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5386 assert(VT.isVector() && "vector shift count is not a vector type");
5387 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5388 if (!getVShiftImm(Op, ElementBits, Cnt))
5392 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5395 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5396 SelectionDAG &DAG) const {
5397 EVT VT = Op.getValueType();
5401 if (!Op.getOperand(1).getValueType().isVector())
5403 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5405 switch (Op.getOpcode()) {
5407 llvm_unreachable("unexpected shift opcode");
5410 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5411 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5412 DAG.getConstant(Cnt, MVT::i32));
5413 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5414 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5415 Op.getOperand(0), Op.getOperand(1));
5418 // Right shift immediate
5419 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5422 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5423 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5424 DAG.getConstant(Cnt, MVT::i32));
5427 // Right shift register. Note, there is not a shift right register
5428 // instruction, but the shift left register instruction takes a signed
5429 // value, where negative numbers specify a right shift.
5430 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5431 : Intrinsic::arm64_neon_ushl;
5432 // negate the shift amount
5433 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5434 SDValue NegShiftLeft =
5435 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5436 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5437 return NegShiftLeft;
5443 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5444 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5445 SDLoc dl, SelectionDAG &DAG) {
5446 EVT SrcVT = LHS.getValueType();
5448 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5449 APInt CnstBits(VT.getSizeInBits(), 0);
5450 APInt UndefBits(VT.getSizeInBits(), 0);
5451 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5452 bool IsZero = IsCnst && (CnstBits == 0);
5454 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5461 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5463 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5464 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5468 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5469 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5472 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5473 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5476 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5477 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5480 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5481 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5485 // If we ignore NaNs then we can use to the MI implementation.
5489 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5490 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5500 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5502 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5503 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5507 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5508 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5511 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5512 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5515 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5516 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5519 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5520 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5522 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5524 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5527 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5528 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5530 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5532 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5536 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5537 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5538 SDValue LHS = Op.getOperand(0);
5539 SDValue RHS = Op.getOperand(1);
5542 if (LHS.getValueType().getVectorElementType().isInteger()) {
5543 assert(LHS.getValueType() == RHS.getValueType());
5544 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5545 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5549 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5550 LHS.getValueType().getVectorElementType() == MVT::f64);
5552 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5553 // clean. Some of them require two branches to implement.
5554 ARM64CC::CondCode CC1, CC2;
5556 changeVectorFPCCToARM64CC(CC, CC1, CC2, ShouldInvert);
5558 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5560 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5564 if (CC2 != ARM64CC::AL) {
5566 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5567 if (!Cmp2.getNode())
5570 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
5574 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
5579 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5580 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5581 /// specified in the intrinsic calls.
5582 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5584 unsigned Intrinsic) const {
5585 switch (Intrinsic) {
5586 case Intrinsic::arm64_neon_ld2:
5587 case Intrinsic::arm64_neon_ld3:
5588 case Intrinsic::arm64_neon_ld4:
5589 case Intrinsic::arm64_neon_ld2lane:
5590 case Intrinsic::arm64_neon_ld3lane:
5591 case Intrinsic::arm64_neon_ld4lane:
5592 case Intrinsic::arm64_neon_ld2r:
5593 case Intrinsic::arm64_neon_ld3r:
5594 case Intrinsic::arm64_neon_ld4r: {
5595 Info.opc = ISD::INTRINSIC_W_CHAIN;
5596 // Conservatively set memVT to the entire set of vectors loaded.
5597 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5598 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5599 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5602 Info.vol = false; // volatile loads with NEON intrinsics not supported
5603 Info.readMem = true;
5604 Info.writeMem = false;
5607 case Intrinsic::arm64_neon_st2:
5608 case Intrinsic::arm64_neon_st3:
5609 case Intrinsic::arm64_neon_st4:
5610 case Intrinsic::arm64_neon_st2lane:
5611 case Intrinsic::arm64_neon_st3lane:
5612 case Intrinsic::arm64_neon_st4lane: {
5613 Info.opc = ISD::INTRINSIC_VOID;
5614 // Conservatively set memVT to the entire set of vectors stored.
5615 unsigned NumElts = 0;
5616 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5617 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5618 if (!ArgTy->isVectorTy())
5620 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5622 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5623 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5626 Info.vol = false; // volatile stores with NEON intrinsics not supported
5627 Info.readMem = false;
5628 Info.writeMem = true;
5631 case Intrinsic::arm64_ldaxr:
5632 case Intrinsic::arm64_ldxr: {
5633 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5634 Info.opc = ISD::INTRINSIC_W_CHAIN;
5635 Info.memVT = MVT::getVT(PtrTy->getElementType());
5636 Info.ptrVal = I.getArgOperand(0);
5638 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5640 Info.readMem = true;
5641 Info.writeMem = false;
5644 case Intrinsic::arm64_stlxr:
5645 case Intrinsic::arm64_stxr: {
5646 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5647 Info.opc = ISD::INTRINSIC_W_CHAIN;
5648 Info.memVT = MVT::getVT(PtrTy->getElementType());
5649 Info.ptrVal = I.getArgOperand(1);
5651 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5653 Info.readMem = false;
5654 Info.writeMem = true;
5657 case Intrinsic::arm64_ldaxp:
5658 case Intrinsic::arm64_ldxp: {
5659 Info.opc = ISD::INTRINSIC_W_CHAIN;
5660 Info.memVT = MVT::i128;
5661 Info.ptrVal = I.getArgOperand(0);
5665 Info.readMem = true;
5666 Info.writeMem = false;
5669 case Intrinsic::arm64_stlxp:
5670 case Intrinsic::arm64_stxp: {
5671 Info.opc = ISD::INTRINSIC_W_CHAIN;
5672 Info.memVT = MVT::i128;
5673 Info.ptrVal = I.getArgOperand(2);
5677 Info.readMem = false;
5678 Info.writeMem = true;
5688 // Truncations from 64-bit GPR to 32-bit GPR is free.
5689 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5690 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5692 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5693 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5694 if (NumBits1 <= NumBits2)
5698 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5699 if (!VT1.isInteger() || !VT2.isInteger())
5701 unsigned NumBits1 = VT1.getSizeInBits();
5702 unsigned NumBits2 = VT2.getSizeInBits();
5703 if (NumBits1 <= NumBits2)
5708 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5710 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5711 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5713 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5714 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5715 if (NumBits1 == 32 && NumBits2 == 64)
5719 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5720 if (!VT1.isInteger() || !VT2.isInteger())
5722 unsigned NumBits1 = VT1.getSizeInBits();
5723 unsigned NumBits2 = VT2.getSizeInBits();
5724 if (NumBits1 == 32 && NumBits2 == 64)
5729 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5730 EVT VT1 = Val.getValueType();
5731 if (isZExtFree(VT1, VT2)) {
5735 if (Val.getOpcode() != ISD::LOAD)
5738 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5739 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5740 VT2.isInteger() && VT1.getSizeInBits() <= 32);
5743 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5744 unsigned &RequiredAligment) const {
5745 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5747 // Cyclone supports unaligned accesses.
5748 RequiredAligment = 0;
5749 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5750 return NumBits == 32 || NumBits == 64;
5753 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5754 unsigned &RequiredAligment) const {
5755 if (!LoadedType.isSimple() ||
5756 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5758 // Cyclone supports unaligned accesses.
5759 RequiredAligment = 0;
5760 unsigned NumBits = LoadedType.getSizeInBits();
5761 return NumBits == 32 || NumBits == 64;
5764 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5765 unsigned AlignCheck) {
5766 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5767 (DstAlign == 0 || DstAlign % AlignCheck == 0));
5770 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5771 unsigned SrcAlign, bool IsMemset,
5772 bool ZeroMemset, bool MemcpyStrSrc,
5773 MachineFunction &MF) const {
5774 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5775 // instruction to materialize the v2i64 zero and one store (with restrictive
5776 // addressing mode). Just do two i64 store of zero-registers.
5778 const Function *F = MF.getFunction();
5779 if (!IsMemset && Size >= 16 &&
5780 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5781 Attribute::NoImplicitFloat) &&
5782 (memOpAlign(SrcAlign, DstAlign, 16) ||
5783 (allowsUnalignedMemoryAccesses(MVT::v2i64, 0, &Fast) && Fast)))
5786 return Size >= 8 ? MVT::i64 : MVT::i32;
5789 // 12-bit optionally shifted immediates are legal for adds.
5790 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5791 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5796 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5797 // immediates is the same as for an add or a sub.
5798 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5801 return isLegalAddImmediate(Immed);
5804 /// isLegalAddressingMode - Return true if the addressing mode represented
5805 /// by AM is legal for this target, for a load/store of the specified type.
5806 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5808 // ARM64 has five basic addressing modes:
5810 // reg + 9-bit signed offset
5811 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
5813 // reg + SIZE_IN_BYTES * reg
5815 // No global is ever allowed as a base.
5819 // No reg+reg+imm addressing.
5820 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5823 // check reg + imm case:
5824 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5825 uint64_t NumBytes = 0;
5826 if (Ty->isSized()) {
5827 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5828 NumBytes = NumBits / 8;
5829 if (!isPowerOf2_64(NumBits))
5834 int64_t Offset = AM.BaseOffs;
5836 // 9-bit signed offset
5837 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5840 // 12-bit unsigned offset
5841 unsigned shift = Log2_64(NumBytes);
5842 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5843 // Must be a multiple of NumBytes (NumBytes is a power of 2)
5844 (Offset >> shift) << shift == Offset)
5849 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5851 if (!AM.Scale || AM.Scale == 1 ||
5852 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5857 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5859 // Scaling factors are not free at all.
5860 // Operands | Rt Latency
5861 // -------------------------------------------
5863 // -------------------------------------------
5864 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
5865 // Rt, [Xn, Wm, <extend> #imm] |
5866 if (isLegalAddressingMode(AM, Ty))
5867 // Scale represents reg2 * scale, thus account for 1 if
5868 // it is not equal to 0 or 1.
5869 return AM.Scale != 0 && AM.Scale != 1;
5873 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
5874 VT = VT.getScalarType();
5879 switch (VT.getSimpleVT().SimpleTy) {
5891 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
5892 // LR is a callee-save register, but we must treat it as clobbered by any call
5893 // site. Hence we include LR in the scratch registers, which are in turn added
5894 // as implicit-defs for stackmaps and patchpoints.
5895 static const MCPhysReg ScratchRegs[] = {
5896 ARM64::X16, ARM64::X17, ARM64::LR, 0
5901 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5903 assert(Ty->isIntegerTy());
5905 unsigned BitSize = Ty->getPrimitiveSizeInBits();
5909 int64_t Val = Imm.getSExtValue();
5910 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
5913 if ((int64_t)Val < 0)
5916 Val &= (1LL << 32) - 1;
5918 unsigned LZ = countLeadingZeros((uint64_t)Val);
5919 unsigned Shift = (63 - LZ) / 16;
5920 // MOVZ is free so return true for one or fewer MOVK.
5921 return (Shift < 3) ? true : false;
5924 // Generate SUBS and CSEL for integer abs.
5925 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
5926 EVT VT = N->getValueType(0);
5928 SDValue N0 = N->getOperand(0);
5929 SDValue N1 = N->getOperand(1);
5932 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
5933 // and change it to SUB and CSEL.
5934 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
5935 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5936 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
5937 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
5938 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
5939 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
5941 // Generate SUBS & CSEL.
5943 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
5944 N0.getOperand(0), DAG.getConstant(0, VT));
5945 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
5946 DAG.getConstant(ARM64CC::PL, MVT::i32),
5947 SDValue(Cmp.getNode(), 1));
5952 // performXorCombine - Attempts to handle integer ABS.
5953 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
5954 TargetLowering::DAGCombinerInfo &DCI,
5955 const ARM64Subtarget *Subtarget) {
5956 if (DCI.isBeforeLegalizeOps())
5959 return performIntegerAbsCombine(N, DAG);
5962 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
5963 TargetLowering::DAGCombinerInfo &DCI,
5964 const ARM64Subtarget *Subtarget) {
5965 if (DCI.isBeforeLegalizeOps())
5968 // Multiplication of a power of two plus/minus one can be done more
5969 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
5970 // future CPUs have a cheaper MADD instruction, this may need to be
5971 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
5972 // 64-bit is 5 cycles, so this is always a win.
5973 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5974 APInt Value = C->getAPIntValue();
5975 EVT VT = N->getValueType(0);
5976 APInt VP1 = Value + 1;
5977 if (VP1.isPowerOf2()) {
5978 // Multiplying by one less than a power of two, replace with a shift
5980 SDValue ShiftedVal =
5981 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5982 DAG.getConstant(VP1.logBase2(), MVT::i64));
5983 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5985 APInt VM1 = Value - 1;
5986 if (VM1.isPowerOf2()) {
5987 // Multiplying by one more than a power of two, replace with a shift
5989 SDValue ShiftedVal =
5990 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5991 DAG.getConstant(VM1.logBase2(), MVT::i64));
5992 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5998 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
5999 EVT VT = N->getValueType(0);
6000 if (VT != MVT::f32 && VT != MVT::f64)
6002 // Only optimize when the source and destination types have the same width.
6003 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6006 // If the result of an integer load is only used by an integer-to-float
6007 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6008 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6009 SDValue N0 = N->getOperand(0);
6010 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6011 // Do not change the width of a volatile load.
6012 !cast<LoadSDNode>(N0)->isVolatile()) {
6013 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6014 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6015 LN0->getPointerInfo(), LN0->isVolatile(),
6016 LN0->isNonTemporal(), LN0->isInvariant(),
6017 LN0->getAlignment());
6019 // Make sure successors of the original load stay after it by updating them
6020 // to use the new Chain.
6021 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6024 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6025 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6031 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6032 /// searches for and classifies those shifts.
6033 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6035 if (N.getOpcode() == ISD::SHL)
6037 else if (N.getOpcode() == ISD::SRL)
6042 if (!isa<ConstantSDNode>(N.getOperand(1)))
6045 ShiftAmount = N->getConstantOperandVal(1);
6046 Src = N->getOperand(0);
6050 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6051 /// registers viewed as a high/low pair. This function looks for the pattern:
6052 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6053 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6055 static SDValue tryCombineToEXTR(SDNode *N,
6056 TargetLowering::DAGCombinerInfo &DCI) {
6057 SelectionDAG &DAG = DCI.DAG;
6059 EVT VT = N->getValueType(0);
6061 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6063 if (VT != MVT::i32 && VT != MVT::i64)
6067 uint32_t ShiftLHS = 0;
6069 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6073 uint32_t ShiftRHS = 0;
6075 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6078 // If they're both trying to come from the high part of the register, they're
6079 // not really an EXTR.
6080 if (LHSFromHi == RHSFromHi)
6083 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6087 std::swap(LHS, RHS);
6088 std::swap(ShiftLHS, ShiftRHS);
6091 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6092 DAG.getConstant(ShiftRHS, MVT::i64));
6095 static SDValue tryCombineToBSL(SDNode *N,
6096 TargetLowering::DAGCombinerInfo &DCI) {
6097 EVT VT = N->getValueType(0);
6098 SelectionDAG &DAG = DCI.DAG;
6104 SDValue N0 = N->getOperand(0);
6105 if (N0.getOpcode() != ISD::AND)
6108 SDValue N1 = N->getOperand(1);
6109 if (N1.getOpcode() != ISD::AND)
6112 // We only have to look for constant vectors here since the general, variable
6113 // case can be handled in TableGen.
6114 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6115 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6116 for (int i = 1; i >= 0; --i)
6117 for (int j = 1; j >= 0; --j) {
6118 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6119 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6123 bool FoundMatch = true;
6124 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6125 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6126 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6128 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6135 return DAG.getNode(ARM64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6136 N0->getOperand(1 - i), N1->getOperand(1 - j));
6142 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6143 const ARM64Subtarget *Subtarget) {
6144 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6145 if (!EnableARM64ExtrGeneration)
6147 SelectionDAG &DAG = DCI.DAG;
6148 EVT VT = N->getValueType(0);
6150 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6153 SDValue Res = tryCombineToEXTR(N, DCI);
6157 Res = tryCombineToBSL(N, DCI);
6164 static SDValue performBitcastCombine(SDNode *N,
6165 TargetLowering::DAGCombinerInfo &DCI,
6166 SelectionDAG &DAG) {
6167 // Wait 'til after everything is legalized to try this. That way we have
6168 // legal vector types and such.
6169 if (DCI.isBeforeLegalizeOps())
6172 // Remove extraneous bitcasts around an extract_subvector.
6174 // (v4i16 (bitconvert
6175 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6177 // (extract_subvector ((v8i16 ...), (i64 4)))
6179 // Only interested in 64-bit vectors as the ultimate result.
6180 EVT VT = N->getValueType(0);
6183 if (VT.getSimpleVT().getSizeInBits() != 64)
6185 // Is the operand an extract_subvector starting at the beginning or halfway
6186 // point of the vector? A low half may also come through as an
6187 // EXTRACT_SUBREG, so look for that, too.
6188 SDValue Op0 = N->getOperand(0);
6189 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6190 !(Op0->isMachineOpcode() &&
6191 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6193 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6194 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6195 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6197 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6198 if (idx != ARM64::dsub)
6200 // The dsub reference is equivalent to a lane zero subvector reference.
6203 // Look through the bitcast of the input to the extract.
6204 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6206 SDValue Source = Op0->getOperand(0)->getOperand(0);
6207 // If the source type has twice the number of elements as our destination
6208 // type, we know this is an extract of the high or low half of the vector.
6209 EVT SVT = Source->getValueType(0);
6210 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6213 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6215 // Create the simplified form to just extract the low or high half of the
6216 // vector directly rather than bothering with the bitcasts.
6218 unsigned NumElements = VT.getVectorNumElements();
6220 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6221 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6223 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6224 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6230 static SDValue performConcatVectorsCombine(SDNode *N,
6231 TargetLowering::DAGCombinerInfo &DCI,
6232 SelectionDAG &DAG) {
6233 // Wait 'til after everything is legalized to try this. That way we have
6234 // legal vector types and such.
6235 if (DCI.isBeforeLegalizeOps())
6239 EVT VT = N->getValueType(0);
6241 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6242 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6243 // canonicalise to that.
6244 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6245 assert(VT.getVectorElementType().getSizeInBits() == 64);
6246 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6247 WidenVector(N->getOperand(0), DAG),
6248 DAG.getConstant(0, MVT::i64));
6251 // Canonicalise concat_vectors so that the right-hand vector has as few
6252 // bit-casts as possible before its real operation. The primary matching
6253 // destination for these operations will be the narrowing "2" instructions,
6254 // which depend on the operation being performed on this right-hand vector.
6256 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6258 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6260 SDValue Op1 = N->getOperand(1);
6261 if (Op1->getOpcode() != ISD::BITCAST)
6263 SDValue RHS = Op1->getOperand(0);
6264 MVT RHSTy = RHS.getValueType().getSimpleVT();
6265 // If the RHS is not a vector, this is not the pattern we're looking for.
6266 if (!RHSTy.isVector())
6269 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6271 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6272 RHSTy.getVectorNumElements() * 2);
6274 ISD::BITCAST, dl, VT,
6275 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6276 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6279 static SDValue tryCombineFixedPointConvert(SDNode *N,
6280 TargetLowering::DAGCombinerInfo &DCI,
6281 SelectionDAG &DAG) {
6282 // Wait 'til after everything is legalized to try this. That way we have
6283 // legal vector types and such.
6284 if (DCI.isBeforeLegalizeOps())
6286 // Transform a scalar conversion of a value from a lane extract into a
6287 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6288 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6289 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6291 // The second form interacts better with instruction selection and the
6292 // register allocator to avoid cross-class register copies that aren't
6293 // coalescable due to a lane reference.
6295 // Check the operand and see if it originates from a lane extract.
6296 SDValue Op1 = N->getOperand(1);
6297 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6298 // Yep, no additional predication needed. Perform the transform.
6299 SDValue IID = N->getOperand(0);
6300 SDValue Shift = N->getOperand(2);
6301 SDValue Vec = Op1.getOperand(0);
6302 SDValue Lane = Op1.getOperand(1);
6303 EVT ResTy = N->getValueType(0);
6307 // The vector width should be 128 bits by the time we get here, even
6308 // if it started as 64 bits (the extract_vector handling will have
6310 assert(Vec.getValueType().getSizeInBits() == 128 &&
6311 "unexpected vector size on extract_vector_elt!");
6312 if (Vec.getValueType() == MVT::v4i32)
6313 VecResTy = MVT::v4f32;
6314 else if (Vec.getValueType() == MVT::v2i64)
6315 VecResTy = MVT::v2f64;
6317 assert(0 && "unexpected vector type!");
6320 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6321 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6326 // AArch64 high-vector "long" operations are formed by performing the non-high
6327 // version on an extract_subvector of each operand which gets the high half:
6329 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6331 // However, there are cases which don't have an extract_high explicitly, but
6332 // have another operation that can be made compatible with one for free. For
6335 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6337 // This routine does the actual conversion of such DUPs, once outer routines
6338 // have determined that everything else is in order.
6339 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6340 // We can handle most types of duplicate, but the lane ones have an extra
6341 // operand saying *which* lane, so we need to know.
6343 switch (N.getOpcode()) {
6347 case ARM64ISD::DUPLANE8:
6348 case ARM64ISD::DUPLANE16:
6349 case ARM64ISD::DUPLANE32:
6350 case ARM64ISD::DUPLANE64:
6357 MVT NarrowTy = N.getSimpleValueType();
6358 if (!NarrowTy.is64BitVector())
6361 MVT ElementTy = NarrowTy.getVectorElementType();
6362 unsigned NumElems = NarrowTy.getVectorNumElements();
6363 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6367 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6370 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6372 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6373 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6376 static bool isEssentiallyExtractSubvector(SDValue N) {
6377 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6380 return N.getOpcode() == ISD::BITCAST &&
6381 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6384 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6385 struct GenericSetCCInfo {
6386 const SDValue *Opnd0;
6387 const SDValue *Opnd1;
6391 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6392 struct ARM64SetCCInfo {
6394 ARM64CC::CondCode CC;
6397 /// \brief Helper structure to keep track of SetCC information.
6399 GenericSetCCInfo Generic;
6400 ARM64SetCCInfo ARM64;
6403 /// \brief Helper structure to be able to read SetCC information.
6404 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6405 /// a GenericSetCCInfo.
6406 struct SetCCInfoAndKind {
6411 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6413 /// ARM64 lowered one.
6414 /// \p SetCCInfo is filled accordingly.
6415 /// \post SetCCInfo is meanginfull only when this function returns true.
6416 /// \return True when Op is a kind of SET_CC operation.
6417 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6418 // If this is a setcc, this is straight forward.
6419 if (Op.getOpcode() == ISD::SETCC) {
6420 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6421 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6422 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6423 SetCCInfo.IsARM64 = false;
6426 // Otherwise, check if this is a matching csel instruction.
6430 if (Op.getOpcode() != ARM64ISD::CSEL)
6432 // Set the information about the operands.
6433 // TODO: we want the operands of the Cmp not the csel
6434 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6435 SetCCInfo.IsARM64 = true;
6436 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6437 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6439 // Check that the operands matches the constraints:
6440 // (1) Both operands must be constants.
6441 // (2) One must be 1 and the other must be 0.
6442 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6443 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6446 if (!TValue || !FValue)
6450 if (!TValue->isOne()) {
6451 // Update the comparison when we are interested in !cc.
6452 std::swap(TValue, FValue);
6453 SetCCInfo.Info.ARM64.CC =
6454 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6456 return TValue->isOne() && FValue->isNullValue();
6459 // The folding we want to perform is:
6460 // (add x, (setcc cc ...) )
6462 // (csel x, (add x, 1), !cc ...)
6464 // The latter will get matched to a CSINC instruction.
6465 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6466 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6467 SDValue LHS = Op->getOperand(0);
6468 SDValue RHS = Op->getOperand(1);
6469 SetCCInfoAndKind InfoAndKind;
6471 // If neither operand is a SET_CC, give up.
6472 if (!isSetCC(LHS, InfoAndKind)) {
6473 std::swap(LHS, RHS);
6474 if (!isSetCC(LHS, InfoAndKind))
6478 // FIXME: This could be generatized to work for FP comparisons.
6479 EVT CmpVT = InfoAndKind.IsARM64
6480 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6481 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6482 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6488 if (InfoAndKind.IsARM64) {
6489 CCVal = DAG.getConstant(
6490 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6491 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6493 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6494 *InfoAndKind.Info.Generic.Opnd1,
6495 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6498 EVT VT = Op->getValueType(0);
6499 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6500 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6503 // The basic add/sub long vector instructions have variants with "2" on the end
6504 // which act on the high-half of their inputs. They are normally matched by
6507 // (add (zeroext (extract_high LHS)),
6508 // (zeroext (extract_high RHS)))
6509 // -> uaddl2 vD, vN, vM
6511 // However, if one of the extracts is something like a duplicate, this
6512 // instruction can still be used profitably. This function puts the DAG into a
6513 // more appropriate form for those patterns to trigger.
6514 static SDValue performAddSubLongCombine(SDNode *N,
6515 TargetLowering::DAGCombinerInfo &DCI,
6516 SelectionDAG &DAG) {
6517 if (DCI.isBeforeLegalizeOps())
6520 MVT VT = N->getSimpleValueType(0);
6521 if (!VT.is128BitVector()) {
6522 if (N->getOpcode() == ISD::ADD)
6523 return performSetccAddFolding(N, DAG);
6527 // Make sure both branches are extended in the same way.
6528 SDValue LHS = N->getOperand(0);
6529 SDValue RHS = N->getOperand(1);
6530 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6531 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6532 LHS.getOpcode() != RHS.getOpcode())
6535 unsigned ExtType = LHS.getOpcode();
6537 // It's not worth doing if at least one of the inputs isn't already an
6538 // extract, but we don't know which it'll be so we have to try both.
6539 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6540 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6544 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6545 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6546 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6550 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6553 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6556 // Massage DAGs which we can use the high-half "long" operations on into
6557 // something isel will recognize better. E.g.
6559 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6560 // (arm64_neon_umull (extract_high (v2i64 vec)))
6561 // (extract_high (v2i64 (dup128 scalar)))))
6563 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6564 TargetLowering::DAGCombinerInfo &DCI,
6565 SelectionDAG &DAG) {
6566 if (DCI.isBeforeLegalizeOps())
6569 SDValue LHS = N->getOperand(1);
6570 SDValue RHS = N->getOperand(2);
6571 assert(LHS.getValueType().is64BitVector() &&
6572 RHS.getValueType().is64BitVector() &&
6573 "unexpected shape for long operation");
6575 // Either node could be a DUP, but it's not worth doing both of them (you'd
6576 // just as well use the non-high version) so look for a corresponding extract
6577 // operation on the other "wing".
6578 if (isEssentiallyExtractSubvector(LHS)) {
6579 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6582 } else if (isEssentiallyExtractSubvector(RHS)) {
6583 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6588 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6589 N->getOperand(0), LHS, RHS);
6592 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6593 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6594 unsigned ElemBits = ElemTy.getSizeInBits();
6596 int64_t ShiftAmount;
6597 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6598 APInt SplatValue, SplatUndef;
6599 unsigned SplatBitSize;
6601 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6602 HasAnyUndefs, ElemBits) ||
6603 SplatBitSize != ElemBits)
6606 ShiftAmount = SplatValue.getSExtValue();
6607 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6608 ShiftAmount = CVN->getSExtValue();
6616 llvm_unreachable("Unknown shift intrinsic");
6617 case Intrinsic::arm64_neon_sqshl:
6618 Opcode = ARM64ISD::SQSHL_I;
6619 IsRightShift = false;
6621 case Intrinsic::arm64_neon_uqshl:
6622 Opcode = ARM64ISD::UQSHL_I;
6623 IsRightShift = false;
6625 case Intrinsic::arm64_neon_srshl:
6626 Opcode = ARM64ISD::SRSHR_I;
6627 IsRightShift = true;
6629 case Intrinsic::arm64_neon_urshl:
6630 Opcode = ARM64ISD::URSHR_I;
6631 IsRightShift = true;
6633 case Intrinsic::arm64_neon_sqshlu:
6634 Opcode = ARM64ISD::SQSHLU_I;
6635 IsRightShift = false;
6639 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6640 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6641 DAG.getConstant(-ShiftAmount, MVT::i32));
6642 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6643 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6644 DAG.getConstant(ShiftAmount, MVT::i32));
6649 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6650 // the intrinsics must be legal and take an i32, this means there's almost
6651 // certainly going to be a zext in the DAG which we can eliminate.
6652 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6653 SDValue AndN = N->getOperand(2);
6654 if (AndN.getOpcode() != ISD::AND)
6657 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6658 if (!CMask || CMask->getZExtValue() != Mask)
6661 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6662 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6665 static SDValue performIntrinsicCombine(SDNode *N,
6666 TargetLowering::DAGCombinerInfo &DCI,
6667 const ARM64Subtarget *Subtarget) {
6668 SelectionDAG &DAG = DCI.DAG;
6669 unsigned IID = getIntrinsicID(N);
6673 case Intrinsic::arm64_neon_vcvtfxs2fp:
6674 case Intrinsic::arm64_neon_vcvtfxu2fp:
6675 return tryCombineFixedPointConvert(N, DCI, DAG);
6677 case Intrinsic::arm64_neon_fmax:
6678 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6679 N->getOperand(1), N->getOperand(2));
6680 case Intrinsic::arm64_neon_fmin:
6681 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6682 N->getOperand(1), N->getOperand(2));
6683 case Intrinsic::arm64_neon_smull:
6684 case Intrinsic::arm64_neon_umull:
6685 case Intrinsic::arm64_neon_pmull:
6686 case Intrinsic::arm64_neon_sqdmull:
6687 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6688 case Intrinsic::arm64_neon_sqshl:
6689 case Intrinsic::arm64_neon_uqshl:
6690 case Intrinsic::arm64_neon_sqshlu:
6691 case Intrinsic::arm64_neon_srshl:
6692 case Intrinsic::arm64_neon_urshl:
6693 return tryCombineShiftImm(IID, N, DAG);
6694 case Intrinsic::arm64_crc32b:
6695 case Intrinsic::arm64_crc32cb:
6696 return tryCombineCRC32(0xff, N, DAG);
6697 case Intrinsic::arm64_crc32h:
6698 case Intrinsic::arm64_crc32ch:
6699 return tryCombineCRC32(0xffff, N, DAG);
6704 static SDValue performExtendCombine(SDNode *N,
6705 TargetLowering::DAGCombinerInfo &DCI,
6706 SelectionDAG &DAG) {
6707 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6708 // we can convert that DUP into another extract_high (of a bigger DUP), which
6709 // helps the backend to decide that an sabdl2 would be useful, saving a real
6710 // extract_high operation.
6711 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6712 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6713 SDNode *ABDNode = N->getOperand(0).getNode();
6714 unsigned IID = getIntrinsicID(ABDNode);
6715 if (IID == Intrinsic::arm64_neon_sabd ||
6716 IID == Intrinsic::arm64_neon_uabd) {
6717 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6718 if (!NewABD.getNode())
6721 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6726 // This is effectively a custom type legalization for ARM64.
6728 // Type legalization will split an extend of a small, legal, type to a larger
6729 // illegal type by first splitting the destination type, often creating
6730 // illegal source types, which then get legalized in isel-confusing ways,
6731 // leading to really terrible codegen. E.g.,
6732 // %result = v8i32 sext v8i8 %value
6734 // %losrc = extract_subreg %value, ...
6735 // %hisrc = extract_subreg %value, ...
6736 // %lo = v4i32 sext v4i8 %losrc
6737 // %hi = v4i32 sext v4i8 %hisrc
6738 // Things go rapidly downhill from there.
6740 // For ARM64, the [sz]ext vector instructions can only go up one element
6741 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6742 // take two instructions.
6744 // This implies that the most efficient way to do the extend from v8i8
6745 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6746 // the normal splitting to happen for the v8i16->v8i32.
6748 // This is pre-legalization to catch some cases where the default
6749 // type legalization will create ill-tempered code.
6750 if (!DCI.isBeforeLegalizeOps())
6753 // We're only interested in cleaning things up for non-legal vector types
6754 // here. If both the source and destination are legal, things will just
6755 // work naturally without any fiddling.
6756 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6757 EVT ResVT = N->getValueType(0);
6758 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6760 // If the vector type isn't a simple VT, it's beyond the scope of what
6761 // we're worried about here. Let legalization do its thing and hope for
6763 if (!ResVT.isSimple())
6766 SDValue Src = N->getOperand(0);
6767 MVT SrcVT = Src->getValueType(0).getSimpleVT();
6768 // If the source VT is a 64-bit vector, we can play games and get the
6769 // better results we want.
6770 if (SrcVT.getSizeInBits() != 64)
6773 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6774 unsigned ElementCount = SrcVT.getVectorNumElements();
6775 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6777 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6779 // Now split the rest of the operation into two halves, each with a 64
6783 unsigned NumElements = ResVT.getVectorNumElements();
6784 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6785 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6786 ResVT.getVectorElementType(), NumElements / 2);
6788 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6789 LoVT.getVectorNumElements());
6790 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6791 DAG.getIntPtrConstant(0));
6792 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6793 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6794 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6795 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6797 // Now combine the parts back together so we still have a single result
6798 // like the combiner expects.
6799 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6802 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6803 /// value. The load store optimizer pass will merge them to store pair stores.
6804 /// This has better performance than a splat of the scalar followed by a split
6805 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6806 /// followed by an ext.b and two stores.
6807 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6808 SDValue StVal = St->getValue();
6809 EVT VT = StVal.getValueType();
6811 // Don't replace floating point stores, they possibly won't be transformed to
6812 // stp because of the store pair suppress pass.
6813 if (VT.isFloatingPoint())
6816 // Check for insert vector elements.
6817 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6820 // We can express a splat as store pair(s) for 2 or 4 elements.
6821 unsigned NumVecElts = VT.getVectorNumElements();
6822 if (NumVecElts != 4 && NumVecElts != 2)
6824 SDValue SplatVal = StVal.getOperand(1);
6825 unsigned RemainInsertElts = NumVecElts - 1;
6827 // Check that this is a splat.
6828 while (--RemainInsertElts) {
6829 SDValue NextInsertElt = StVal.getOperand(0);
6830 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6832 if (NextInsertElt.getOperand(1) != SplatVal)
6834 StVal = NextInsertElt;
6836 unsigned OrigAlignment = St->getAlignment();
6837 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6838 unsigned Alignment = std::min(OrigAlignment, EltOffset);
6840 // Create scalar stores. This is at least as good as the code sequence for a
6841 // split unaligned store wich is a dup.s, ext.b, and two stores.
6842 // Most of the time the three stores should be replaced by store pair
6843 // instructions (stp).
6845 SDValue BasePtr = St->getBasePtr();
6847 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6848 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6850 unsigned Offset = EltOffset;
6851 while (--NumVecElts) {
6852 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6853 DAG.getConstant(Offset, MVT::i64));
6854 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6855 St->getPointerInfo(), St->isVolatile(),
6856 St->isNonTemporal(), Alignment);
6857 Offset += EltOffset;
6862 static SDValue performSTORECombine(SDNode *N,
6863 TargetLowering::DAGCombinerInfo &DCI,
6865 const ARM64Subtarget *Subtarget) {
6866 if (!DCI.isBeforeLegalize())
6869 StoreSDNode *S = cast<StoreSDNode>(N);
6870 if (S->isVolatile())
6873 // Cyclone has bad performance on unaligned 16B stores when crossing line and
6874 // page boundries. We want to split such stores.
6875 if (!Subtarget->isCyclone())
6878 // Don't split at Oz.
6879 MachineFunction &MF = DAG.getMachineFunction();
6880 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
6881 AttributeSet::FunctionIndex, Attribute::MinSize);
6885 SDValue StVal = S->getValue();
6886 EVT VT = StVal.getValueType();
6888 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
6889 // those up regresses performance on micro-benchmarks and olden/bh.
6890 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
6893 // Split unaligned 16B stores. They are terrible for performance.
6894 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
6895 // extensions can use this to mark that it does not want splitting to happen
6896 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
6897 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
6898 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
6899 S->getAlignment() <= 2)
6902 // If we get a splat of a scalar convert this vector store to a store of
6903 // scalars. They will be merged into store pairs thereby removing two
6905 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
6906 if (ReplacedSplat != SDValue())
6907 return ReplacedSplat;
6910 unsigned NumElts = VT.getVectorNumElements() / 2;
6911 // Split VT into two.
6913 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
6914 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6915 DAG.getIntPtrConstant(0));
6916 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6917 DAG.getIntPtrConstant(NumElts));
6918 SDValue BasePtr = S->getBasePtr();
6920 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
6921 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
6922 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6923 DAG.getConstant(8, MVT::i64));
6924 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
6925 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
6929 // Optimize compare with zero and branch.
6930 static SDValue performBRCONDCombine(SDNode *N,
6931 TargetLowering::DAGCombinerInfo &DCI,
6932 SelectionDAG &DAG) {
6933 SDValue Chain = N->getOperand(0);
6934 SDValue Dest = N->getOperand(1);
6935 SDValue CCVal = N->getOperand(2);
6936 SDValue Cmp = N->getOperand(3);
6938 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
6939 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
6940 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
6943 unsigned CmpOpc = Cmp.getOpcode();
6944 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
6947 // Only attempt folding if there is only one use of the flag and no use of the
6949 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
6952 SDValue LHS = Cmp.getOperand(0);
6953 SDValue RHS = Cmp.getOperand(1);
6955 assert(LHS.getValueType() == RHS.getValueType() &&
6956 "Expected the value type to be the same for both operands!");
6957 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
6960 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
6961 std::swap(LHS, RHS);
6963 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
6966 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
6967 LHS.getOpcode() == ISD::SRL)
6970 // Fold the compare into the branch instruction.
6972 if (CC == ARM64CC::EQ)
6973 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6975 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6977 // Do not add new nodes to DAG combiner worklist.
6978 DCI.CombineTo(N, BR, false);
6983 // vselect (v1i1 setcc) ->
6984 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
6985 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
6986 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
6988 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
6989 SDValue N0 = N->getOperand(0);
6990 EVT CCVT = N0.getValueType();
6992 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
6993 CCVT.getVectorElementType() != MVT::i1)
6996 EVT ResVT = N->getValueType(0);
6997 EVT CmpVT = N0.getOperand(0).getValueType();
6998 // Only combine when the result type is of the same size as the compared
7000 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7003 SDValue IfTrue = N->getOperand(1);
7004 SDValue IfFalse = N->getOperand(2);
7006 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7007 N0.getOperand(0), N0.getOperand(1),
7008 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7009 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7013 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7014 DAGCombinerInfo &DCI) const {
7015 SelectionDAG &DAG = DCI.DAG;
7016 switch (N->getOpcode()) {
7021 return performAddSubLongCombine(N, DCI, DAG);
7023 return performXorCombine(N, DAG, DCI, Subtarget);
7025 return performMulCombine(N, DAG, DCI, Subtarget);
7026 case ISD::SINT_TO_FP:
7027 case ISD::UINT_TO_FP:
7028 return performIntToFpCombine(N, DAG);
7030 return performORCombine(N, DCI, Subtarget);
7031 case ISD::INTRINSIC_WO_CHAIN:
7032 return performIntrinsicCombine(N, DCI, Subtarget);
7033 case ISD::ANY_EXTEND:
7034 case ISD::ZERO_EXTEND:
7035 case ISD::SIGN_EXTEND:
7036 return performExtendCombine(N, DCI, DAG);
7038 return performBitcastCombine(N, DCI, DAG);
7039 case ISD::CONCAT_VECTORS:
7040 return performConcatVectorsCombine(N, DCI, DAG);
7042 return performVSelectCombine(N, DCI.DAG);
7044 return performSTORECombine(N, DCI, DAG, Subtarget);
7045 case ARM64ISD::BRCOND:
7046 return performBRCONDCombine(N, DCI, DAG);
7051 // Check if the return value is used as only a return value, as otherwise
7052 // we can't perform a tail-call. In particular, we need to check for
7053 // target ISD nodes that are returns and any other "odd" constructs
7054 // that the generic analysis code won't necessarily catch.
7055 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7056 if (N->getNumValues() != 1)
7058 if (!N->hasNUsesOfValue(1, 0))
7061 SDValue TCChain = Chain;
7062 SDNode *Copy = *N->use_begin();
7063 if (Copy->getOpcode() == ISD::CopyToReg) {
7064 // If the copy has a glue operand, we conservatively assume it isn't safe to
7065 // perform a tail call.
7066 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7069 TCChain = Copy->getOperand(0);
7070 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7073 bool HasRet = false;
7074 for (SDNode *Node : Copy->uses()) {
7075 if (Node->getOpcode() != ARM64ISD::RET_FLAG)
7087 // Return whether the an instruction can potentially be optimized to a tail
7088 // call. This will cause the optimizers to attempt to move, or duplicate,
7089 // return instructions to help enable tail call optimizations for this
7091 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7092 if (!EnableARM64TailCalls)
7095 if (!CI->isTailCall())
7101 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7103 ISD::MemIndexedMode &AM,
7105 SelectionDAG &DAG) const {
7106 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7109 Base = Op->getOperand(0);
7110 // All of the indexed addressing mode instructions take a signed
7111 // 9 bit immediate offset.
7112 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7113 int64_t RHSC = (int64_t)RHS->getZExtValue();
7114 if (RHSC >= 256 || RHSC <= -256)
7116 IsInc = (Op->getOpcode() == ISD::ADD);
7117 Offset = Op->getOperand(1);
7123 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7125 ISD::MemIndexedMode &AM,
7126 SelectionDAG &DAG) const {
7129 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7130 VT = LD->getMemoryVT();
7131 Ptr = LD->getBasePtr();
7132 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7133 VT = ST->getMemoryVT();
7134 Ptr = ST->getBasePtr();
7139 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7141 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7145 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7148 ISD::MemIndexedMode &AM,
7149 SelectionDAG &DAG) const {
7152 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7153 VT = LD->getMemoryVT();
7154 Ptr = LD->getBasePtr();
7155 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7156 VT = ST->getMemoryVT();
7157 Ptr = ST->getBasePtr();
7162 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7164 // Post-indexing updates the base, so it's not a valid transform
7165 // if that's not the same as the load's pointer.
7168 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7172 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7173 SmallVectorImpl<SDValue> &Results,
7174 SelectionDAG &DAG) const {
7175 switch (N->getOpcode()) {
7177 llvm_unreachable("Don't know how to custom expand this");
7178 case ISD::FP_TO_UINT:
7179 case ISD::FP_TO_SINT:
7180 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7181 // Let normal code take care of it by not adding anything to Results.
7186 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
7187 // Loads and stores less than 128-bits are already atomic; ones above that
7188 // are doomed anyway, so defer to the default libcall and blame the OS when
7190 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
7191 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
7192 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
7193 return LI->getType()->getPrimitiveSizeInBits() == 128;
7195 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
7196 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
7199 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
7200 AtomicOrdering Ord) const {
7201 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7202 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
7204 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7206 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
7207 // intrinsic must return {i64, i64} and we have to recombine them into a
7208 // single i128 here.
7209 if (ValTy->getPrimitiveSizeInBits() == 128) {
7211 IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
7212 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
7214 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7215 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
7217 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
7218 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
7219 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
7220 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
7221 return Builder.CreateOr(
7222 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
7225 Type *Tys[] = { Addr->getType() };
7227 IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
7228 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
7230 return Builder.CreateTruncOrBitCast(
7231 Builder.CreateCall(Ldxr, Addr),
7232 cast<PointerType>(Addr->getType())->getElementType());
7235 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
7236 Value *Val, Value *Addr,
7237 AtomicOrdering Ord) const {
7238 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7240 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7242 // Since the intrinsics must have legal type, the i128 intrinsics take two
7243 // parameters: "i64, i64". We must marshal Val into the appropriate form
7245 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7247 IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7248 Function *Stxr = Intrinsic::getDeclaration(M, Int);
7249 Type *Int64Ty = Type::getInt64Ty(M->getContext());
7251 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7252 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7253 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7254 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7258 IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7259 Type *Tys[] = { Addr->getType() };
7260 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7262 return Builder.CreateCall2(
7263 Stxr, Builder.CreateZExtOrBitCast(
7264 Val, Stxr->getFunctionType()->getParamType(0)),