blob: 4fcc409e071d462dc8d1f7ae756859d8b1ee81aa [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64ISelLowering.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000015#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000016#include "AArch64PerfectShuffle.h"
17#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000018#include "AArch64TargetMachine.h"
19#include "AArch64TargetObjectFile.h"
20#include "MCTargetDesc/AArch64AddressingModes.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/CodeGen/CallingConvLower.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Target/TargetOptions.h"
34using namespace llvm;
35
36#define DEBUG_TYPE "aarch64-lower"
37
38STATISTIC(NumTailCalls, "Number of tail calls");
39STATISTIC(NumShiftInserts, "Number of vector shift inserts");
40
41enum AlignMode {
42 StrictAlign,
43 NoStrictAlign
44};
45
46static cl::opt<AlignMode>
47Align(cl::desc("Load/store alignment support"),
48 cl::Hidden, cl::init(NoStrictAlign),
49 cl::values(
50 clEnumValN(StrictAlign, "aarch64-strict-align",
51 "Disallow all unaligned memory accesses"),
52 clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
53 "Allow unaligned memory accesses"),
54 clEnumValEnd));
55
56// Place holder until extr generation is tested fully.
57static cl::opt<bool>
58EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
59 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
60 cl::init(true));
61
62static cl::opt<bool>
63EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
64 cl::desc("Allow AArch64 SLI/SRI formation"),
65 cl::init(false));
66
67//===----------------------------------------------------------------------===//
68// AArch64 Lowering public interface.
69//===----------------------------------------------------------------------===//
Eric Christopher89958332014-05-31 00:07:32 +000070static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
71 if (TT.isOSBinFormatMachO())
Tim Northover3b0846e2014-05-24 12:50:23 +000072 return new AArch64_MachoTargetObjectFile();
73
74 return new AArch64_ELFTargetObjectFile();
75}
76
Eric Christopher841da852014-06-10 23:26:45 +000077AArch64TargetLowering::AArch64TargetLowering(TargetMachine &TM)
Eric Christopher89958332014-05-31 00:07:32 +000078 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
Tim Northover3b0846e2014-05-24 12:50:23 +000079 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
80
81 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
82 // we have to make something up. Arbitrarily, choose ZeroOrOne.
83 setBooleanContents(ZeroOrOneBooleanContent);
84 // When comparing vectors the result sets the different elements in the
85 // vector to all-one or all-zero.
86 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
87
88 // Set up the register classes.
89 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
90 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
91
92 if (Subtarget->hasFPARMv8()) {
93 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
94 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
95 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
96 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
97 }
98
99 if (Subtarget->hasNEON()) {
100 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
101 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
102 // Someone set us up the NEON.
103 addDRTypeForNEON(MVT::v2f32);
104 addDRTypeForNEON(MVT::v8i8);
105 addDRTypeForNEON(MVT::v4i16);
106 addDRTypeForNEON(MVT::v2i32);
107 addDRTypeForNEON(MVT::v1i64);
108 addDRTypeForNEON(MVT::v1f64);
109
110 addQRTypeForNEON(MVT::v4f32);
111 addQRTypeForNEON(MVT::v2f64);
112 addQRTypeForNEON(MVT::v16i8);
113 addQRTypeForNEON(MVT::v8i16);
114 addQRTypeForNEON(MVT::v4i32);
115 addQRTypeForNEON(MVT::v2i64);
116 }
117
118 // Compute derived properties from the register classes
119 computeRegisterProperties();
120
121 // Provide all sorts of operation actions
122 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
123 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
124 setOperationAction(ISD::SETCC, MVT::i32, Custom);
125 setOperationAction(ISD::SETCC, MVT::i64, Custom);
126 setOperationAction(ISD::SETCC, MVT::f32, Custom);
127 setOperationAction(ISD::SETCC, MVT::f64, Custom);
128 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
129 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
130 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
131 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
132 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
133 setOperationAction(ISD::SELECT, MVT::i32, Custom);
134 setOperationAction(ISD::SELECT, MVT::i64, Custom);
135 setOperationAction(ISD::SELECT, MVT::f32, Custom);
136 setOperationAction(ISD::SELECT, MVT::f64, Custom);
137 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
138 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
139 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
140 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
141 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
142 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
143
144 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
145 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
146 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
147
148 setOperationAction(ISD::FREM, MVT::f32, Expand);
149 setOperationAction(ISD::FREM, MVT::f64, Expand);
150 setOperationAction(ISD::FREM, MVT::f80, Expand);
151
152 // Custom lowering hooks are needed for XOR
153 // to fold it into CSINC/CSINV.
154 setOperationAction(ISD::XOR, MVT::i32, Custom);
155 setOperationAction(ISD::XOR, MVT::i64, Custom);
156
157 // Virtually no operation on f128 is legal, but LLVM can't expand them when
158 // there's a valid register class, so we need custom operations in most cases.
159 setOperationAction(ISD::FABS, MVT::f128, Expand);
160 setOperationAction(ISD::FADD, MVT::f128, Custom);
161 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
162 setOperationAction(ISD::FCOS, MVT::f128, Expand);
163 setOperationAction(ISD::FDIV, MVT::f128, Custom);
164 setOperationAction(ISD::FMA, MVT::f128, Expand);
165 setOperationAction(ISD::FMUL, MVT::f128, Custom);
166 setOperationAction(ISD::FNEG, MVT::f128, Expand);
167 setOperationAction(ISD::FPOW, MVT::f128, Expand);
168 setOperationAction(ISD::FREM, MVT::f128, Expand);
169 setOperationAction(ISD::FRINT, MVT::f128, Expand);
170 setOperationAction(ISD::FSIN, MVT::f128, Expand);
171 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
172 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
173 setOperationAction(ISD::FSUB, MVT::f128, Custom);
174 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
175 setOperationAction(ISD::SETCC, MVT::f128, Custom);
176 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
177 setOperationAction(ISD::SELECT, MVT::f128, Custom);
178 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
179 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
180
181 // Lowering for many of the conversions is actually specified by the non-f128
182 // type. The LowerXXX function will be trivial when f128 isn't involved.
183 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
184 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
185 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
186 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
187 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
188 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
189 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
190 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
191 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
192 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
193 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
194 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
195 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
196 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
197
198 // Variable arguments.
199 setOperationAction(ISD::VASTART, MVT::Other, Custom);
200 setOperationAction(ISD::VAARG, MVT::Other, Custom);
201 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
202 setOperationAction(ISD::VAEND, MVT::Other, Expand);
203
204 // Variable-sized objects.
205 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
206 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
207 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
208
209 // Exception handling.
210 // FIXME: These are guesses. Has this been defined yet?
211 setExceptionPointerRegister(AArch64::X0);
212 setExceptionSelectorRegister(AArch64::X1);
213
214 // Constant pool entries
215 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
216
217 // BlockAddress
218 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
219
220 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
221 setOperationAction(ISD::ADDC, MVT::i32, Custom);
222 setOperationAction(ISD::ADDE, MVT::i32, Custom);
223 setOperationAction(ISD::SUBC, MVT::i32, Custom);
224 setOperationAction(ISD::SUBE, MVT::i32, Custom);
225 setOperationAction(ISD::ADDC, MVT::i64, Custom);
226 setOperationAction(ISD::ADDE, MVT::i64, Custom);
227 setOperationAction(ISD::SUBC, MVT::i64, Custom);
228 setOperationAction(ISD::SUBE, MVT::i64, Custom);
229
230 // AArch64 lacks both left-rotate and popcount instructions.
231 setOperationAction(ISD::ROTL, MVT::i32, Expand);
232 setOperationAction(ISD::ROTL, MVT::i64, Expand);
233
234 // AArch64 doesn't have {U|S}MUL_LOHI.
235 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
236 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
237
238
239 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
240 // counterparts, which AArch64 supports directly.
241 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
242 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
243 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
244 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
245
246 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
247 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
248
249 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
250 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
251 setOperationAction(ISD::SREM, MVT::i32, Expand);
252 setOperationAction(ISD::SREM, MVT::i64, Expand);
253 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
254 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
255 setOperationAction(ISD::UREM, MVT::i32, Expand);
256 setOperationAction(ISD::UREM, MVT::i64, Expand);
257
258 // Custom lower Add/Sub/Mul with overflow.
259 setOperationAction(ISD::SADDO, MVT::i32, Custom);
260 setOperationAction(ISD::SADDO, MVT::i64, Custom);
261 setOperationAction(ISD::UADDO, MVT::i32, Custom);
262 setOperationAction(ISD::UADDO, MVT::i64, Custom);
263 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
264 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
265 setOperationAction(ISD::USUBO, MVT::i32, Custom);
266 setOperationAction(ISD::USUBO, MVT::i64, Custom);
267 setOperationAction(ISD::SMULO, MVT::i32, Custom);
268 setOperationAction(ISD::SMULO, MVT::i64, Custom);
269 setOperationAction(ISD::UMULO, MVT::i32, Custom);
270 setOperationAction(ISD::UMULO, MVT::i64, Custom);
271
272 setOperationAction(ISD::FSIN, MVT::f32, Expand);
273 setOperationAction(ISD::FSIN, MVT::f64, Expand);
274 setOperationAction(ISD::FCOS, MVT::f32, Expand);
275 setOperationAction(ISD::FCOS, MVT::f64, Expand);
276 setOperationAction(ISD::FPOW, MVT::f32, Expand);
277 setOperationAction(ISD::FPOW, MVT::f64, Expand);
278 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
279 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
280
281 // AArch64 has implementations of a lot of rounding-like FP operations.
282 static MVT RoundingTypes[] = { MVT::f32, MVT::f64};
283 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
284 MVT Ty = RoundingTypes[I];
285 setOperationAction(ISD::FFLOOR, Ty, Legal);
286 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
287 setOperationAction(ISD::FCEIL, Ty, Legal);
288 setOperationAction(ISD::FRINT, Ty, Legal);
289 setOperationAction(ISD::FTRUNC, Ty, Legal);
290 setOperationAction(ISD::FROUND, Ty, Legal);
291 }
292
293 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
294
295 if (Subtarget->isTargetMachO()) {
296 // For iOS, we don't want to the normal expansion of a libcall to
297 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
298 // traffic.
299 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
300 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
301 } else {
302 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
303 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
304 }
305
306 // AArch64 does not have floating-point extending loads, i1 sign-extending
307 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Tim Northoverb94f0852014-07-18 13:01:31 +0000308 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000309 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
310 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
311 setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
312 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
313 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
314 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
315 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
316 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
317 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
318 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
319 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000320
321 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
322 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
323
Tim Northover3b0846e2014-05-24 12:50:23 +0000324 // Indexed loads and stores are supported.
325 for (unsigned im = (unsigned)ISD::PRE_INC;
326 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
327 setIndexedLoadAction(im, MVT::i8, Legal);
328 setIndexedLoadAction(im, MVT::i16, Legal);
329 setIndexedLoadAction(im, MVT::i32, Legal);
330 setIndexedLoadAction(im, MVT::i64, Legal);
331 setIndexedLoadAction(im, MVT::f64, Legal);
332 setIndexedLoadAction(im, MVT::f32, Legal);
333 setIndexedStoreAction(im, MVT::i8, Legal);
334 setIndexedStoreAction(im, MVT::i16, Legal);
335 setIndexedStoreAction(im, MVT::i32, Legal);
336 setIndexedStoreAction(im, MVT::i64, Legal);
337 setIndexedStoreAction(im, MVT::f64, Legal);
338 setIndexedStoreAction(im, MVT::f32, Legal);
339 }
340
341 // Trap.
342 setOperationAction(ISD::TRAP, MVT::Other, Legal);
343
344 // We combine OR nodes for bitfield operations.
345 setTargetDAGCombine(ISD::OR);
346
347 // Vector add and sub nodes may conceal a high-half opportunity.
348 // Also, try to fold ADD into CSINC/CSINV..
349 setTargetDAGCombine(ISD::ADD);
350 setTargetDAGCombine(ISD::SUB);
351
352 setTargetDAGCombine(ISD::XOR);
353 setTargetDAGCombine(ISD::SINT_TO_FP);
354 setTargetDAGCombine(ISD::UINT_TO_FP);
355
356 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
357
358 setTargetDAGCombine(ISD::ANY_EXTEND);
359 setTargetDAGCombine(ISD::ZERO_EXTEND);
360 setTargetDAGCombine(ISD::SIGN_EXTEND);
361 setTargetDAGCombine(ISD::BITCAST);
362 setTargetDAGCombine(ISD::CONCAT_VECTORS);
363 setTargetDAGCombine(ISD::STORE);
364
365 setTargetDAGCombine(ISD::MUL);
366
367 setTargetDAGCombine(ISD::SELECT);
368 setTargetDAGCombine(ISD::VSELECT);
369
370 setTargetDAGCombine(ISD::INTRINSIC_VOID);
371 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
372 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
373
374 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
375 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
376 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
377
378 setStackPointerRegisterToSaveRestore(AArch64::SP);
379
380 setSchedulingPreference(Sched::Hybrid);
381
382 // Enable TBZ/TBNZ
383 MaskAndBranchFoldingIsLegal = true;
384
385 setMinFunctionAlignment(2);
386
387 RequireStrictAlign = (Align == StrictAlign);
388
389 setHasExtractBitsInsn(true);
390
391 if (Subtarget->hasNEON()) {
392 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
393 // silliness like this:
394 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
395 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
396 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
397 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
398 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
399 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
400 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
401 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
402 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
403 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
404 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
405 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
406 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
407 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
408 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
409 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
410 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
411 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
412 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
413 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
414 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
415 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
416 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
417 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
418 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
419
420 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
421 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
422 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
423 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
424 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
425
426 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
427
428 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
429 // elements smaller than i32, so promote the input to i32 first.
430 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
431 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
432 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
433 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
434 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
435 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
436 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
437 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
438 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
439
440 // AArch64 doesn't have MUL.2d:
441 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
442 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
443 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
444 // Likewise, narrowing and extending vector loads/stores aren't handled
445 // directly.
446 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
447 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
448
449 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
450 Expand);
451
452 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
453 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
454 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
455 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
456
457 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
458
459 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
460 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
461 setTruncStoreAction((MVT::SimpleValueType)VT,
462 (MVT::SimpleValueType)InnerVT, Expand);
463 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
464 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
465 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
466 }
467
468 // AArch64 has implementations of a lot of rounding-like FP operations.
469 static MVT RoundingVecTypes[] = {MVT::v2f32, MVT::v4f32, MVT::v2f64 };
470 for (unsigned I = 0; I < array_lengthof(RoundingVecTypes); ++I) {
471 MVT Ty = RoundingVecTypes[I];
472 setOperationAction(ISD::FFLOOR, Ty, Legal);
473 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
474 setOperationAction(ISD::FCEIL, Ty, Legal);
475 setOperationAction(ISD::FRINT, Ty, Legal);
476 setOperationAction(ISD::FTRUNC, Ty, Legal);
477 setOperationAction(ISD::FROUND, Ty, Legal);
478 }
479 }
480}
481
482void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
483 if (VT == MVT::v2f32) {
484 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
485 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
486
487 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
488 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
489 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
490 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
491 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
492
493 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
494 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
495 }
496
497 // Mark vector float intrinsics as expand.
498 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
499 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
500 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
501 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
502 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
503 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
504 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
505 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
506 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
507 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
508 }
509
510 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
511 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
512 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
513 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
514 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
515 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
516 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
517 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
518 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
519 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
520 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
521 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
522
523 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
524 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
525 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
526 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
527
528 // CNT supports only B element sizes.
529 if (VT != MVT::v8i8 && VT != MVT::v16i8)
530 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
531
532 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
533 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
534 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
535 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
536 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
537
538 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
539 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
540
541 if (Subtarget->isLittleEndian()) {
542 for (unsigned im = (unsigned)ISD::PRE_INC;
543 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
544 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
545 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
546 }
547 }
548}
549
550void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
551 addRegisterClass(VT, &AArch64::FPR64RegClass);
552 addTypeForNEON(VT, MVT::v2i32);
553}
554
555void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
556 addRegisterClass(VT, &AArch64::FPR128RegClass);
557 addTypeForNEON(VT, MVT::v4i32);
558}
559
560EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
561 if (!VT.isVector())
562 return MVT::i32;
563 return VT.changeVectorElementTypeToInteger();
564}
565
566/// computeKnownBitsForTargetNode - Determine which of the bits specified in
567/// Mask are known to be either zero or one and return them in the
568/// KnownZero/KnownOne bitsets.
569void AArch64TargetLowering::computeKnownBitsForTargetNode(
570 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
571 const SelectionDAG &DAG, unsigned Depth) const {
572 switch (Op.getOpcode()) {
573 default:
574 break;
575 case AArch64ISD::CSEL: {
576 APInt KnownZero2, KnownOne2;
577 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
578 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
579 KnownZero &= KnownZero2;
580 KnownOne &= KnownOne2;
581 break;
582 }
583 case ISD::INTRINSIC_W_CHAIN: {
584 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
585 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
586 switch (IntID) {
587 default: return;
588 case Intrinsic::aarch64_ldaxr:
589 case Intrinsic::aarch64_ldxr: {
590 unsigned BitWidth = KnownOne.getBitWidth();
591 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
592 unsigned MemBits = VT.getScalarType().getSizeInBits();
593 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
594 return;
595 }
596 }
597 break;
598 }
599 case ISD::INTRINSIC_WO_CHAIN:
600 case ISD::INTRINSIC_VOID: {
601 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
602 switch (IntNo) {
603 default:
604 break;
605 case Intrinsic::aarch64_neon_umaxv:
606 case Intrinsic::aarch64_neon_uminv: {
607 // Figure out the datatype of the vector operand. The UMINV instruction
608 // will zero extend the result, so we can mark as known zero all the
609 // bits larger than the element datatype. 32-bit or larget doesn't need
610 // this as those are legal types and will be handled by isel directly.
611 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
612 unsigned BitWidth = KnownZero.getBitWidth();
613 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
614 assert(BitWidth >= 8 && "Unexpected width!");
615 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
616 KnownZero |= Mask;
617 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
618 assert(BitWidth >= 16 && "Unexpected width!");
619 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
620 KnownZero |= Mask;
621 }
622 break;
623 } break;
624 }
625 }
626 }
627}
628
629MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
630 return MVT::i64;
631}
632
633unsigned AArch64TargetLowering::getMaximalGlobalOffset() const {
634 // FIXME: On AArch64, this depends on the type.
Tim Northover21feb2e2014-07-01 19:47:09 +0000635 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
Tim Northover3b0846e2014-05-24 12:50:23 +0000636 // and the offset has to be a multiple of the related size in bytes.
637 return 4095;
638}
639
640FastISel *
641AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
642 const TargetLibraryInfo *libInfo) const {
643 return AArch64::createFastISel(funcInfo, libInfo);
644}
645
646const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
647 switch (Opcode) {
648 default:
649 return nullptr;
650 case AArch64ISD::CALL: return "AArch64ISD::CALL";
651 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
652 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
653 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
654 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
655 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
656 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
657 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
658 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
659 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
660 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
661 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
662 case AArch64ISD::TLSDESC_CALL: return "AArch64ISD::TLSDESC_CALL";
663 case AArch64ISD::ADC: return "AArch64ISD::ADC";
664 case AArch64ISD::SBC: return "AArch64ISD::SBC";
665 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
666 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
667 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
668 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
669 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
670 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
671 case AArch64ISD::FMIN: return "AArch64ISD::FMIN";
672 case AArch64ISD::FMAX: return "AArch64ISD::FMAX";
673 case AArch64ISD::DUP: return "AArch64ISD::DUP";
674 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
675 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
676 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
677 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
678 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
679 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
680 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
681 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
682 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
683 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
684 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
685 case AArch64ISD::BICi: return "AArch64ISD::BICi";
686 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
687 case AArch64ISD::BSL: return "AArch64ISD::BSL";
688 case AArch64ISD::NEG: return "AArch64ISD::NEG";
689 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
690 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
691 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
692 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
693 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
694 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
695 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
696 case AArch64ISD::REV16: return "AArch64ISD::REV16";
697 case AArch64ISD::REV32: return "AArch64ISD::REV32";
698 case AArch64ISD::REV64: return "AArch64ISD::REV64";
699 case AArch64ISD::EXT: return "AArch64ISD::EXT";
700 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
701 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
702 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
703 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
704 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
705 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
706 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
707 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
708 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
709 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
710 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
711 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
712 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
713 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
714 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
715 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
716 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
717 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
718 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
719 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
720 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
721 case AArch64ISD::NOT: return "AArch64ISD::NOT";
722 case AArch64ISD::BIT: return "AArch64ISD::BIT";
723 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
724 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
725 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
726 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
727 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
728 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
729 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
730 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
731 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
732 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
733 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
734 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
735 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
736 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
737 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
738 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
739 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
740 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
741 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
742 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
743 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
744 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
745 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
746 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
747 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
748 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
749 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
750 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
751 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
752 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
753 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
754 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
755 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
756 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
757 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
758 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
759 }
760}
761
762MachineBasicBlock *
763AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
764 MachineBasicBlock *MBB) const {
765 // We materialise the F128CSEL pseudo-instruction as some control flow and a
766 // phi node:
767
768 // OrigBB:
769 // [... previous instrs leading to comparison ...]
770 // b.ne TrueBB
771 // b EndBB
772 // TrueBB:
773 // ; Fallthrough
774 // EndBB:
775 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
776
Eric Christopherd9134482014-08-04 21:25:23 +0000777 const TargetInstrInfo *TII =
778 getTargetMachine().getSubtargetImpl()->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000779 MachineFunction *MF = MBB->getParent();
780 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
781 DebugLoc DL = MI->getDebugLoc();
782 MachineFunction::iterator It = MBB;
783 ++It;
784
785 unsigned DestReg = MI->getOperand(0).getReg();
786 unsigned IfTrueReg = MI->getOperand(1).getReg();
787 unsigned IfFalseReg = MI->getOperand(2).getReg();
788 unsigned CondCode = MI->getOperand(3).getImm();
789 bool NZCVKilled = MI->getOperand(4).isKill();
790
791 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
792 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
793 MF->insert(It, TrueBB);
794 MF->insert(It, EndBB);
795
796 // Transfer rest of current basic-block to EndBB
797 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
798 MBB->end());
799 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
800
801 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
802 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
803 MBB->addSuccessor(TrueBB);
804 MBB->addSuccessor(EndBB);
805
806 // TrueBB falls through to the end.
807 TrueBB->addSuccessor(EndBB);
808
809 if (!NZCVKilled) {
810 TrueBB->addLiveIn(AArch64::NZCV);
811 EndBB->addLiveIn(AArch64::NZCV);
812 }
813
814 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
815 .addReg(IfTrueReg)
816 .addMBB(TrueBB)
817 .addReg(IfFalseReg)
818 .addMBB(MBB);
819
820 MI->eraseFromParent();
821 return EndBB;
822}
823
824MachineBasicBlock *
825AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
826 MachineBasicBlock *BB) const {
827 switch (MI->getOpcode()) {
828 default:
829#ifndef NDEBUG
830 MI->dump();
831#endif
Craig Topper35b2f752014-06-19 06:10:58 +0000832 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +0000833
834 case AArch64::F128CSEL:
835 return EmitF128CSEL(MI, BB);
836
837 case TargetOpcode::STACKMAP:
838 case TargetOpcode::PATCHPOINT:
839 return emitPatchPoint(MI, BB);
840 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000841}
842
843//===----------------------------------------------------------------------===//
844// AArch64 Lowering private implementation.
845//===----------------------------------------------------------------------===//
846
847//===----------------------------------------------------------------------===//
848// Lowering Code
849//===----------------------------------------------------------------------===//
850
851/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
852/// CC
853static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
854 switch (CC) {
855 default:
856 llvm_unreachable("Unknown condition code!");
857 case ISD::SETNE:
858 return AArch64CC::NE;
859 case ISD::SETEQ:
860 return AArch64CC::EQ;
861 case ISD::SETGT:
862 return AArch64CC::GT;
863 case ISD::SETGE:
864 return AArch64CC::GE;
865 case ISD::SETLT:
866 return AArch64CC::LT;
867 case ISD::SETLE:
868 return AArch64CC::LE;
869 case ISD::SETUGT:
870 return AArch64CC::HI;
871 case ISD::SETUGE:
872 return AArch64CC::HS;
873 case ISD::SETULT:
874 return AArch64CC::LO;
875 case ISD::SETULE:
876 return AArch64CC::LS;
877 }
878}
879
880/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
881static void changeFPCCToAArch64CC(ISD::CondCode CC,
882 AArch64CC::CondCode &CondCode,
883 AArch64CC::CondCode &CondCode2) {
884 CondCode2 = AArch64CC::AL;
885 switch (CC) {
886 default:
887 llvm_unreachable("Unknown FP condition!");
888 case ISD::SETEQ:
889 case ISD::SETOEQ:
890 CondCode = AArch64CC::EQ;
891 break;
892 case ISD::SETGT:
893 case ISD::SETOGT:
894 CondCode = AArch64CC::GT;
895 break;
896 case ISD::SETGE:
897 case ISD::SETOGE:
898 CondCode = AArch64CC::GE;
899 break;
900 case ISD::SETOLT:
901 CondCode = AArch64CC::MI;
902 break;
903 case ISD::SETOLE:
904 CondCode = AArch64CC::LS;
905 break;
906 case ISD::SETONE:
907 CondCode = AArch64CC::MI;
908 CondCode2 = AArch64CC::GT;
909 break;
910 case ISD::SETO:
911 CondCode = AArch64CC::VC;
912 break;
913 case ISD::SETUO:
914 CondCode = AArch64CC::VS;
915 break;
916 case ISD::SETUEQ:
917 CondCode = AArch64CC::EQ;
918 CondCode2 = AArch64CC::VS;
919 break;
920 case ISD::SETUGT:
921 CondCode = AArch64CC::HI;
922 break;
923 case ISD::SETUGE:
924 CondCode = AArch64CC::PL;
925 break;
926 case ISD::SETLT:
927 case ISD::SETULT:
928 CondCode = AArch64CC::LT;
929 break;
930 case ISD::SETLE:
931 case ISD::SETULE:
932 CondCode = AArch64CC::LE;
933 break;
934 case ISD::SETNE:
935 case ISD::SETUNE:
936 CondCode = AArch64CC::NE;
937 break;
938 }
939}
940
941/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
942/// CC usable with the vector instructions. Fewer operations are available
943/// without a real NZCV register, so we have to use less efficient combinations
944/// to get the same effect.
945static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
946 AArch64CC::CondCode &CondCode,
947 AArch64CC::CondCode &CondCode2,
948 bool &Invert) {
949 Invert = false;
950 switch (CC) {
951 default:
952 // Mostly the scalar mappings work fine.
953 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
954 break;
955 case ISD::SETUO:
956 Invert = true; // Fallthrough
957 case ISD::SETO:
958 CondCode = AArch64CC::MI;
959 CondCode2 = AArch64CC::GE;
960 break;
961 case ISD::SETUEQ:
962 case ISD::SETULT:
963 case ISD::SETULE:
964 case ISD::SETUGT:
965 case ISD::SETUGE:
966 // All of the compare-mask comparisons are ordered, but we can switch
967 // between the two by a double inversion. E.g. ULE == !OGT.
968 Invert = true;
969 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
970 break;
971 }
972}
973
974static bool isLegalArithImmed(uint64_t C) {
975 // Matches AArch64DAGToDAGISel::SelectArithImmed().
976 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
977}
978
979static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
980 SDLoc dl, SelectionDAG &DAG) {
981 EVT VT = LHS.getValueType();
982
983 if (VT.isFloatingPoint())
984 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
985
986 // The CMP instruction is just an alias for SUBS, and representing it as
987 // SUBS means that it's possible to get CSE with subtract operations.
988 // A later phase can perform the optimization of setting the destination
989 // register to WZR/XZR if it ends up being unused.
990 unsigned Opcode = AArch64ISD::SUBS;
991
992 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
993 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
994 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
995 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
996 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
997 // can be set differently by this operation. It comes down to whether
998 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
999 // everything is fine. If not then the optimization is wrong. Thus general
1000 // comparisons are only valid if op2 != 0.
1001
1002 // So, finally, the only LLVM-native comparisons that don't mention C and V
1003 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1004 // the absence of information about op2.
1005 Opcode = AArch64ISD::ADDS;
1006 RHS = RHS.getOperand(1);
1007 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1008 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1009 !isUnsignedIntSetCC(CC)) {
1010 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1011 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1012 // of the signed comparisons.
1013 Opcode = AArch64ISD::ANDS;
1014 RHS = LHS.getOperand(1);
1015 LHS = LHS.getOperand(0);
1016 }
1017
1018 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1019 .getValue(1);
1020}
1021
1022static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1023 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1024 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1025 EVT VT = RHS.getValueType();
1026 uint64_t C = RHSC->getZExtValue();
1027 if (!isLegalArithImmed(C)) {
1028 // Constant does not fit, try adjusting it by one?
1029 switch (CC) {
1030 default:
1031 break;
1032 case ISD::SETLT:
1033 case ISD::SETGE:
1034 if ((VT == MVT::i32 && C != 0x80000000 &&
1035 isLegalArithImmed((uint32_t)(C - 1))) ||
1036 (VT == MVT::i64 && C != 0x80000000ULL &&
1037 isLegalArithImmed(C - 1ULL))) {
1038 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1039 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1040 RHS = DAG.getConstant(C, VT);
1041 }
1042 break;
1043 case ISD::SETULT:
1044 case ISD::SETUGE:
1045 if ((VT == MVT::i32 && C != 0 &&
1046 isLegalArithImmed((uint32_t)(C - 1))) ||
1047 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1048 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1049 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1050 RHS = DAG.getConstant(C, VT);
1051 }
1052 break;
1053 case ISD::SETLE:
1054 case ISD::SETGT:
1055 if ((VT == MVT::i32 && C != 0x7fffffff &&
1056 isLegalArithImmed((uint32_t)(C + 1))) ||
1057 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1058 isLegalArithImmed(C + 1ULL))) {
1059 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1060 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1061 RHS = DAG.getConstant(C, VT);
1062 }
1063 break;
1064 case ISD::SETULE:
1065 case ISD::SETUGT:
1066 if ((VT == MVT::i32 && C != 0xffffffff &&
1067 isLegalArithImmed((uint32_t)(C + 1))) ||
1068 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1069 isLegalArithImmed(C + 1ULL))) {
1070 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1071 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1072 RHS = DAG.getConstant(C, VT);
1073 }
1074 break;
1075 }
1076 }
1077 }
1078
1079 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1080 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
1081 AArch64cc = DAG.getConstant(AArch64CC, MVT::i32);
1082 return Cmp;
1083}
1084
1085static std::pair<SDValue, SDValue>
1086getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1087 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1088 "Unsupported value type");
1089 SDValue Value, Overflow;
1090 SDLoc DL(Op);
1091 SDValue LHS = Op.getOperand(0);
1092 SDValue RHS = Op.getOperand(1);
1093 unsigned Opc = 0;
1094 switch (Op.getOpcode()) {
1095 default:
1096 llvm_unreachable("Unknown overflow instruction!");
1097 case ISD::SADDO:
1098 Opc = AArch64ISD::ADDS;
1099 CC = AArch64CC::VS;
1100 break;
1101 case ISD::UADDO:
1102 Opc = AArch64ISD::ADDS;
1103 CC = AArch64CC::HS;
1104 break;
1105 case ISD::SSUBO:
1106 Opc = AArch64ISD::SUBS;
1107 CC = AArch64CC::VS;
1108 break;
1109 case ISD::USUBO:
1110 Opc = AArch64ISD::SUBS;
1111 CC = AArch64CC::LO;
1112 break;
1113 // Multiply needs a little bit extra work.
1114 case ISD::SMULO:
1115 case ISD::UMULO: {
1116 CC = AArch64CC::NE;
1117 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1118 if (Op.getValueType() == MVT::i32) {
1119 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1120 // For a 32 bit multiply with overflow check we want the instruction
1121 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1122 // need to generate the following pattern:
1123 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1124 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1125 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1126 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1127 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1128 DAG.getConstant(0, MVT::i64));
1129 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1130 // operation. We need to clear out the upper 32 bits, because we used a
1131 // widening multiply that wrote all 64 bits. In the end this should be a
1132 // noop.
1133 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1134 if (IsSigned) {
1135 // The signed overflow check requires more than just a simple check for
1136 // any bit set in the upper 32 bits of the result. These bits could be
1137 // just the sign bits of a negative number. To perform the overflow
1138 // check we have to arithmetic shift right the 32nd bit of the result by
1139 // 31 bits. Then we compare the result to the upper 32 bits.
1140 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1141 DAG.getConstant(32, MVT::i64));
1142 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1143 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1144 DAG.getConstant(31, MVT::i64));
1145 // It is important that LowerBits is last, otherwise the arithmetic
1146 // shift will not be folded into the compare (SUBS).
1147 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1148 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1149 .getValue(1);
1150 } else {
1151 // The overflow check for unsigned multiply is easy. We only need to
1152 // check if any of the upper 32 bits are set. This can be done with a
1153 // CMP (shifted register). For that we need to generate the following
1154 // pattern:
1155 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1156 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1157 DAG.getConstant(32, MVT::i64));
1158 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1159 Overflow =
1160 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1161 UpperBits).getValue(1);
1162 }
1163 break;
1164 }
1165 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1166 // For the 64 bit multiply
1167 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1168 if (IsSigned) {
1169 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1170 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1171 DAG.getConstant(63, MVT::i64));
1172 // It is important that LowerBits is last, otherwise the arithmetic
1173 // shift will not be folded into the compare (SUBS).
1174 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1175 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1176 .getValue(1);
1177 } else {
1178 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1179 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1180 Overflow =
1181 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1182 UpperBits).getValue(1);
1183 }
1184 break;
1185 }
1186 } // switch (...)
1187
1188 if (Opc) {
1189 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1190
1191 // Emit the AArch64 operation with overflow check.
1192 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1193 Overflow = Value.getValue(1);
1194 }
1195 return std::make_pair(Value, Overflow);
1196}
1197
1198SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1199 RTLIB::Libcall Call) const {
1200 SmallVector<SDValue, 2> Ops;
1201 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1202 Ops.push_back(Op.getOperand(i));
1203
1204 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1205 SDLoc(Op)).first;
1206}
1207
1208static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1209 SDValue Sel = Op.getOperand(0);
1210 SDValue Other = Op.getOperand(1);
1211
1212 // If neither operand is a SELECT_CC, give up.
1213 if (Sel.getOpcode() != ISD::SELECT_CC)
1214 std::swap(Sel, Other);
1215 if (Sel.getOpcode() != ISD::SELECT_CC)
1216 return Op;
1217
1218 // The folding we want to perform is:
1219 // (xor x, (select_cc a, b, cc, 0, -1) )
1220 // -->
1221 // (csel x, (xor x, -1), cc ...)
1222 //
1223 // The latter will get matched to a CSINV instruction.
1224
1225 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1226 SDValue LHS = Sel.getOperand(0);
1227 SDValue RHS = Sel.getOperand(1);
1228 SDValue TVal = Sel.getOperand(2);
1229 SDValue FVal = Sel.getOperand(3);
1230 SDLoc dl(Sel);
1231
1232 // FIXME: This could be generalized to non-integer comparisons.
1233 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1234 return Op;
1235
1236 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1237 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1238
1239 // The the values aren't constants, this isn't the pattern we're looking for.
1240 if (!CFVal || !CTVal)
1241 return Op;
1242
1243 // We can commute the SELECT_CC by inverting the condition. This
1244 // might be needed to make this fit into a CSINV pattern.
1245 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1246 std::swap(TVal, FVal);
1247 std::swap(CTVal, CFVal);
1248 CC = ISD::getSetCCInverse(CC, true);
1249 }
1250
1251 // If the constants line up, perform the transform!
1252 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1253 SDValue CCVal;
1254 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1255
1256 FVal = Other;
1257 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1258 DAG.getConstant(-1ULL, Other.getValueType()));
1259
1260 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1261 CCVal, Cmp);
1262 }
1263
1264 return Op;
1265}
1266
1267static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1268 EVT VT = Op.getValueType();
1269
1270 // Let legalize expand this if it isn't a legal type yet.
1271 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1272 return SDValue();
1273
1274 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1275
1276 unsigned Opc;
1277 bool ExtraOp = false;
1278 switch (Op.getOpcode()) {
1279 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001280 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001281 case ISD::ADDC:
1282 Opc = AArch64ISD::ADDS;
1283 break;
1284 case ISD::SUBC:
1285 Opc = AArch64ISD::SUBS;
1286 break;
1287 case ISD::ADDE:
1288 Opc = AArch64ISD::ADCS;
1289 ExtraOp = true;
1290 break;
1291 case ISD::SUBE:
1292 Opc = AArch64ISD::SBCS;
1293 ExtraOp = true;
1294 break;
1295 }
1296
1297 if (!ExtraOp)
1298 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1299 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1300 Op.getOperand(2));
1301}
1302
1303static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1304 // Let legalize expand this if it isn't a legal type yet.
1305 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1306 return SDValue();
1307
1308 AArch64CC::CondCode CC;
1309 // The actual operation that sets the overflow or carry flag.
1310 SDValue Value, Overflow;
1311 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1312
1313 // We use 0 and 1 as false and true values.
1314 SDValue TVal = DAG.getConstant(1, MVT::i32);
1315 SDValue FVal = DAG.getConstant(0, MVT::i32);
1316
1317 // We use an inverted condition, because the conditional select is inverted
1318 // too. This will allow it to be selected to a single instruction:
1319 // CSINC Wd, WZR, WZR, invert(cond).
1320 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1321 Overflow = DAG.getNode(AArch64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal,
1322 CCVal, Overflow);
1323
1324 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1325 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1326}
1327
1328// Prefetch operands are:
1329// 1: Address to prefetch
1330// 2: bool isWrite
1331// 3: int locality (0 = no locality ... 3 = extreme locality)
1332// 4: bool isDataCache
1333static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1334 SDLoc DL(Op);
1335 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1336 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1337 // The data thing is not used.
1338 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1339
1340 bool IsStream = !Locality;
1341 // When the locality number is set
1342 if (Locality) {
1343 // The front-end should have filtered out the out-of-range values
1344 assert(Locality <= 3 && "Prefetch locality out-of-range");
1345 // The locality degree is the opposite of the cache speed.
1346 // Put the number the other way around.
1347 // The encoding starts at 0 for level 1
1348 Locality = 3 - Locality;
1349 }
1350
1351 // built the mask value encoding the expected behavior.
1352 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1353 (Locality << 1) | // Cache level bits
1354 (unsigned)IsStream; // Stream bit
1355 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1356 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1357}
1358
1359SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1360 SelectionDAG &DAG) const {
1361 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1362
1363 RTLIB::Libcall LC;
1364 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1365
1366 return LowerF128Call(Op, DAG, LC);
1367}
1368
1369SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1370 SelectionDAG &DAG) const {
1371 if (Op.getOperand(0).getValueType() != MVT::f128) {
1372 // It's legal except when f128 is involved
1373 return Op;
1374 }
1375
1376 RTLIB::Libcall LC;
1377 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1378
1379 // FP_ROUND node has a second operand indicating whether it is known to be
1380 // precise. That doesn't take part in the LibCall so we can't directly use
1381 // LowerF128Call.
1382 SDValue SrcVal = Op.getOperand(0);
1383 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1384 /*isSigned*/ false, SDLoc(Op)).first;
1385}
1386
1387static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1388 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1389 // Any additional optimization in this function should be recorded
1390 // in the cost tables.
1391 EVT InVT = Op.getOperand(0).getValueType();
1392 EVT VT = Op.getValueType();
1393
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001394 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001395 SDLoc dl(Op);
1396 SDValue Cv =
1397 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1398 Op.getOperand(0));
1399 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001400 }
1401
1402 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001403 SDLoc dl(Op);
1404 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Op.getOperand(0));
1405 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1406 }
1407
1408 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001409 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001410}
1411
1412SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1413 SelectionDAG &DAG) const {
1414 if (Op.getOperand(0).getValueType().isVector())
1415 return LowerVectorFP_TO_INT(Op, DAG);
1416
1417 if (Op.getOperand(0).getValueType() != MVT::f128) {
1418 // It's legal except when f128 is involved
1419 return Op;
1420 }
1421
1422 RTLIB::Libcall LC;
1423 if (Op.getOpcode() == ISD::FP_TO_SINT)
1424 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1425 else
1426 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1427
1428 SmallVector<SDValue, 2> Ops;
1429 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1430 Ops.push_back(Op.getOperand(i));
1431
1432 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1433 SDLoc(Op)).first;
1434}
1435
1436static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1437 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1438 // Any additional optimization in this function should be recorded
1439 // in the cost tables.
1440 EVT VT = Op.getValueType();
1441 SDLoc dl(Op);
1442 SDValue In = Op.getOperand(0);
1443 EVT InVT = In.getValueType();
1444
Tim Northoveref0d7602014-06-15 09:27:06 +00001445 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1446 MVT CastVT =
1447 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1448 InVT.getVectorNumElements());
1449 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1450 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001451 }
1452
Tim Northoveref0d7602014-06-15 09:27:06 +00001453 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1454 unsigned CastOpc =
1455 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1456 EVT CastVT = VT.changeVectorElementTypeToInteger();
1457 In = DAG.getNode(CastOpc, dl, CastVT, In);
1458 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001459 }
1460
Tim Northoveref0d7602014-06-15 09:27:06 +00001461 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001462}
1463
1464SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1465 SelectionDAG &DAG) const {
1466 if (Op.getValueType().isVector())
1467 return LowerVectorINT_TO_FP(Op, DAG);
1468
1469 // i128 conversions are libcalls.
1470 if (Op.getOperand(0).getValueType() == MVT::i128)
1471 return SDValue();
1472
1473 // Other conversions are legal, unless it's to the completely software-based
1474 // fp128.
1475 if (Op.getValueType() != MVT::f128)
1476 return Op;
1477
1478 RTLIB::Libcall LC;
1479 if (Op.getOpcode() == ISD::SINT_TO_FP)
1480 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1481 else
1482 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1483
1484 return LowerF128Call(Op, DAG, LC);
1485}
1486
1487SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1488 SelectionDAG &DAG) const {
1489 // For iOS, we want to call an alternative entry point: __sincos_stret,
1490 // which returns the values in two S / D registers.
1491 SDLoc dl(Op);
1492 SDValue Arg = Op.getOperand(0);
1493 EVT ArgVT = Arg.getValueType();
1494 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1495
1496 ArgListTy Args;
1497 ArgListEntry Entry;
1498
1499 Entry.Node = Arg;
1500 Entry.Ty = ArgTy;
1501 Entry.isSExt = false;
1502 Entry.isZExt = false;
1503 Args.push_back(Entry);
1504
1505 const char *LibcallName =
1506 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1507 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1508
1509 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1510 TargetLowering::CallLoweringInfo CLI(DAG);
1511 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00001512 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00001513
1514 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1515 return CallResult.first;
1516}
1517
Tim Northoverf8bfe212014-07-18 13:07:05 +00001518static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1519 if (Op.getValueType() != MVT::f16)
1520 return SDValue();
1521
1522 assert(Op.getOperand(0).getValueType() == MVT::i16);
1523 SDLoc DL(Op);
1524
1525 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1526 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1527 return SDValue(
1528 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1529 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
1530 0);
1531}
1532
1533
Tim Northover3b0846e2014-05-24 12:50:23 +00001534SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1535 SelectionDAG &DAG) const {
1536 switch (Op.getOpcode()) {
1537 default:
1538 llvm_unreachable("unimplemented operand");
1539 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00001540 case ISD::BITCAST:
1541 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00001542 case ISD::GlobalAddress:
1543 return LowerGlobalAddress(Op, DAG);
1544 case ISD::GlobalTLSAddress:
1545 return LowerGlobalTLSAddress(Op, DAG);
1546 case ISD::SETCC:
1547 return LowerSETCC(Op, DAG);
1548 case ISD::BR_CC:
1549 return LowerBR_CC(Op, DAG);
1550 case ISD::SELECT:
1551 return LowerSELECT(Op, DAG);
1552 case ISD::SELECT_CC:
1553 return LowerSELECT_CC(Op, DAG);
1554 case ISD::JumpTable:
1555 return LowerJumpTable(Op, DAG);
1556 case ISD::ConstantPool:
1557 return LowerConstantPool(Op, DAG);
1558 case ISD::BlockAddress:
1559 return LowerBlockAddress(Op, DAG);
1560 case ISD::VASTART:
1561 return LowerVASTART(Op, DAG);
1562 case ISD::VACOPY:
1563 return LowerVACOPY(Op, DAG);
1564 case ISD::VAARG:
1565 return LowerVAARG(Op, DAG);
1566 case ISD::ADDC:
1567 case ISD::ADDE:
1568 case ISD::SUBC:
1569 case ISD::SUBE:
1570 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1571 case ISD::SADDO:
1572 case ISD::UADDO:
1573 case ISD::SSUBO:
1574 case ISD::USUBO:
1575 case ISD::SMULO:
1576 case ISD::UMULO:
1577 return LowerXALUO(Op, DAG);
1578 case ISD::FADD:
1579 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1580 case ISD::FSUB:
1581 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1582 case ISD::FMUL:
1583 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1584 case ISD::FDIV:
1585 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1586 case ISD::FP_ROUND:
1587 return LowerFP_ROUND(Op, DAG);
1588 case ISD::FP_EXTEND:
1589 return LowerFP_EXTEND(Op, DAG);
1590 case ISD::FRAMEADDR:
1591 return LowerFRAMEADDR(Op, DAG);
1592 case ISD::RETURNADDR:
1593 return LowerRETURNADDR(Op, DAG);
1594 case ISD::INSERT_VECTOR_ELT:
1595 return LowerINSERT_VECTOR_ELT(Op, DAG);
1596 case ISD::EXTRACT_VECTOR_ELT:
1597 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1598 case ISD::BUILD_VECTOR:
1599 return LowerBUILD_VECTOR(Op, DAG);
1600 case ISD::VECTOR_SHUFFLE:
1601 return LowerVECTOR_SHUFFLE(Op, DAG);
1602 case ISD::EXTRACT_SUBVECTOR:
1603 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1604 case ISD::SRA:
1605 case ISD::SRL:
1606 case ISD::SHL:
1607 return LowerVectorSRA_SRL_SHL(Op, DAG);
1608 case ISD::SHL_PARTS:
1609 return LowerShiftLeftParts(Op, DAG);
1610 case ISD::SRL_PARTS:
1611 case ISD::SRA_PARTS:
1612 return LowerShiftRightParts(Op, DAG);
1613 case ISD::CTPOP:
1614 return LowerCTPOP(Op, DAG);
1615 case ISD::FCOPYSIGN:
1616 return LowerFCOPYSIGN(Op, DAG);
1617 case ISD::AND:
1618 return LowerVectorAND(Op, DAG);
1619 case ISD::OR:
1620 return LowerVectorOR(Op, DAG);
1621 case ISD::XOR:
1622 return LowerXOR(Op, DAG);
1623 case ISD::PREFETCH:
1624 return LowerPREFETCH(Op, DAG);
1625 case ISD::SINT_TO_FP:
1626 case ISD::UINT_TO_FP:
1627 return LowerINT_TO_FP(Op, DAG);
1628 case ISD::FP_TO_SINT:
1629 case ISD::FP_TO_UINT:
1630 return LowerFP_TO_INT(Op, DAG);
1631 case ISD::FSINCOS:
1632 return LowerFSINCOS(Op, DAG);
1633 }
1634}
1635
1636/// getFunctionAlignment - Return the Log2 alignment of this function.
1637unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
1638 return 2;
1639}
1640
1641//===----------------------------------------------------------------------===//
1642// Calling Convention Implementation
1643//===----------------------------------------------------------------------===//
1644
1645#include "AArch64GenCallingConv.inc"
1646
1647/// Selects the correct CCAssignFn for a the given CallingConvention
1648/// value.
1649CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1650 bool IsVarArg) const {
1651 switch (CC) {
1652 default:
1653 llvm_unreachable("Unsupported calling convention.");
1654 case CallingConv::WebKit_JS:
1655 return CC_AArch64_WebKit_JS;
1656 case CallingConv::C:
1657 case CallingConv::Fast:
1658 if (!Subtarget->isTargetDarwin())
1659 return CC_AArch64_AAPCS;
1660 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
1661 }
1662}
1663
1664SDValue AArch64TargetLowering::LowerFormalArguments(
1665 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1666 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1667 SmallVectorImpl<SDValue> &InVals) const {
1668 MachineFunction &MF = DAG.getMachineFunction();
1669 MachineFrameInfo *MFI = MF.getFrameInfo();
1670
1671 // Assign locations to all of the incoming arguments.
1672 SmallVector<CCValAssign, 16> ArgLocs;
1673 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1674 getTargetMachine(), ArgLocs, *DAG.getContext());
1675
1676 // At this point, Ins[].VT may already be promoted to i32. To correctly
1677 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1678 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
1679 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1680 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1681 // LocVT.
1682 unsigned NumArgs = Ins.size();
1683 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1684 unsigned CurArgIdx = 0;
1685 for (unsigned i = 0; i != NumArgs; ++i) {
1686 MVT ValVT = Ins[i].VT;
1687 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1688 CurArgIdx = Ins[i].OrigArgIndex;
1689
1690 // Get type of the original argument.
1691 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1692 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1693 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00001694 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00001695 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00001696 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00001697 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00001698
1699 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1700 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00001701 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00001702 assert(!Res && "Call operand has unhandled type");
1703 (void)Res;
1704 }
1705 assert(ArgLocs.size() == Ins.size());
1706 SmallVector<SDValue, 16> ArgValues;
1707 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1708 CCValAssign &VA = ArgLocs[i];
1709
1710 if (Ins[i].Flags.isByVal()) {
1711 // Byval is used for HFAs in the PCS, but the system should work in a
1712 // non-compliant manner for larger structs.
1713 EVT PtrTy = getPointerTy();
1714 int Size = Ins[i].Flags.getByValSize();
1715 unsigned NumRegs = (Size + 7) / 8;
1716
1717 // FIXME: This works on big-endian for composite byvals, which are the common
1718 // case. It should also work for fundamental types too.
1719 unsigned FrameIdx =
1720 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1721 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1722 InVals.push_back(FrameIdxN);
1723
1724 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00001725 }
1726
1727 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001728 // Arguments stored in registers.
1729 EVT RegVT = VA.getLocVT();
1730
1731 SDValue ArgValue;
1732 const TargetRegisterClass *RC;
1733
1734 if (RegVT == MVT::i32)
1735 RC = &AArch64::GPR32RegClass;
1736 else if (RegVT == MVT::i64)
1737 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00001738 else if (RegVT == MVT::f16)
1739 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00001740 else if (RegVT == MVT::f32)
1741 RC = &AArch64::FPR32RegClass;
1742 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
1743 RC = &AArch64::FPR64RegClass;
1744 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
1745 RC = &AArch64::FPR128RegClass;
1746 else
1747 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1748
1749 // Transform the arguments in physical registers into virtual ones.
1750 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1751 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1752
1753 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1754 // to 64 bits. Insert an assert[sz]ext to capture this, then
1755 // truncate to the right size.
1756 switch (VA.getLocInfo()) {
1757 default:
1758 llvm_unreachable("Unknown loc info!");
1759 case CCValAssign::Full:
1760 break;
1761 case CCValAssign::BCvt:
1762 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1763 break;
Tim Northover47e003c2014-05-26 17:21:53 +00001764 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00001765 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00001766 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00001767 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
1768 // nodes after our lowering.
1769 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00001770 break;
1771 }
1772
1773 InVals.push_back(ArgValue);
1774
1775 } else { // VA.isRegLoc()
1776 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1777 unsigned ArgOffset = VA.getLocMemOffset();
1778 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1779
1780 uint32_t BEAlign = 0;
1781 if (ArgSize < 8 && !Subtarget->isLittleEndian())
1782 BEAlign = 8 - ArgSize;
1783
1784 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
1785
1786 // Create load nodes to retrieve arguments from the stack.
1787 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1788 SDValue ArgValue;
1789
Jiangning Liucc4f38b2014-06-03 03:25:09 +00001790 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00001791 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00001792 MVT MemVT = VA.getValVT();
1793
Tim Northover47e003c2014-05-26 17:21:53 +00001794 switch (VA.getLocInfo()) {
1795 default:
1796 break;
Tim Northover6890add2014-06-03 13:54:53 +00001797 case CCValAssign::BCvt:
1798 MemVT = VA.getLocVT();
1799 break;
Tim Northover47e003c2014-05-26 17:21:53 +00001800 case CCValAssign::SExt:
1801 ExtType = ISD::SEXTLOAD;
1802 break;
1803 case CCValAssign::ZExt:
1804 ExtType = ISD::ZEXTLOAD;
1805 break;
1806 case CCValAssign::AExt:
1807 ExtType = ISD::EXTLOAD;
1808 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001809 }
1810
Tim Northover6890add2014-06-03 13:54:53 +00001811 ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
Tim Northover47e003c2014-05-26 17:21:53 +00001812 MachinePointerInfo::getFixedStack(FI),
Louis Gerbarg67474e32014-07-31 21:45:05 +00001813 MemVT, false, false, false, 0, nullptr);
Tim Northover47e003c2014-05-26 17:21:53 +00001814
Tim Northover3b0846e2014-05-24 12:50:23 +00001815 InVals.push_back(ArgValue);
1816 }
1817 }
1818
1819 // varargs
1820 if (isVarArg) {
1821 if (!Subtarget->isTargetDarwin()) {
1822 // The AAPCS variadic function ABI is identical to the non-variadic
1823 // one. As a result there may be more arguments in registers and we should
1824 // save them for future reference.
1825 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1826 }
1827
1828 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1829 // This will point to the next argument passed via stack.
1830 unsigned StackOffset = CCInfo.getNextStackOffset();
1831 // We currently pass all varargs at 8-byte alignment.
1832 StackOffset = ((StackOffset + 7) & ~7);
1833 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1834 }
1835
1836 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1837 unsigned StackArgSize = CCInfo.getNextStackOffset();
1838 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1839 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1840 // This is a non-standard ABI so by fiat I say we're allowed to make full
1841 // use of the stack area to be popped, which must be aligned to 16 bytes in
1842 // any case:
1843 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1844
1845 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1846 // a multiple of 16.
1847 FuncInfo->setArgumentStackToRestore(StackArgSize);
1848
1849 // This realignment carries over to the available bytes below. Our own
1850 // callers will guarantee the space is free by giving an aligned value to
1851 // CALLSEQ_START.
1852 }
1853 // Even if we're not expected to free up the space, it's useful to know how
1854 // much is there while considering tail calls (because we can reuse it).
1855 FuncInfo->setBytesInStackArgArea(StackArgSize);
1856
1857 return Chain;
1858}
1859
1860void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1861 SelectionDAG &DAG, SDLoc DL,
1862 SDValue &Chain) const {
1863 MachineFunction &MF = DAG.getMachineFunction();
1864 MachineFrameInfo *MFI = MF.getFrameInfo();
1865 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1866
1867 SmallVector<SDValue, 8> MemOps;
1868
1869 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
1870 AArch64::X3, AArch64::X4, AArch64::X5,
1871 AArch64::X6, AArch64::X7 };
1872 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1873 unsigned FirstVariadicGPR =
1874 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1875
1876 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1877 int GPRIdx = 0;
1878 if (GPRSaveSize != 0) {
1879 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1880
1881 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1882
1883 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1884 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
1885 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1886 SDValue Store =
1887 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1888 MachinePointerInfo::getStack(i * 8), false, false, 0);
1889 MemOps.push_back(Store);
1890 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1891 DAG.getConstant(8, getPointerTy()));
1892 }
1893 }
1894 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1895 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1896
1897 if (Subtarget->hasFPARMv8()) {
1898 static const MCPhysReg FPRArgRegs[] = {
1899 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
1900 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
1901 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1902 unsigned FirstVariadicFPR =
1903 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1904
1905 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1906 int FPRIdx = 0;
1907 if (FPRSaveSize != 0) {
1908 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1909
1910 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1911
1912 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1913 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
1914 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
1915
1916 SDValue Store =
1917 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1918 MachinePointerInfo::getStack(i * 16), false, false, 0);
1919 MemOps.push_back(Store);
1920 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1921 DAG.getConstant(16, getPointerTy()));
1922 }
1923 }
1924 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1925 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1926 }
1927
1928 if (!MemOps.empty()) {
1929 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1930 }
1931}
1932
1933/// LowerCallResult - Lower the result values of a call into the
1934/// appropriate copies out of appropriate physical registers.
1935SDValue AArch64TargetLowering::LowerCallResult(
1936 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1937 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1938 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1939 SDValue ThisVal) const {
1940 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
1941 ? RetCC_AArch64_WebKit_JS
1942 : RetCC_AArch64_AAPCS;
1943 // Assign locations to each value returned by this call.
1944 SmallVector<CCValAssign, 16> RVLocs;
1945 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1946 getTargetMachine(), RVLocs, *DAG.getContext());
1947 CCInfo.AnalyzeCallResult(Ins, RetCC);
1948
1949 // Copy all of the result registers out of their specified physreg.
1950 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1951 CCValAssign VA = RVLocs[i];
1952
1953 // Pass 'this' value directly from the argument to return value, to avoid
1954 // reg unit interference
1955 if (i == 0 && isThisReturn) {
1956 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1957 "unexpected return calling convention register assignment");
1958 InVals.push_back(ThisVal);
1959 continue;
1960 }
1961
1962 SDValue Val =
1963 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1964 Chain = Val.getValue(1);
1965 InFlag = Val.getValue(2);
1966
1967 switch (VA.getLocInfo()) {
1968 default:
1969 llvm_unreachable("Unknown loc info!");
1970 case CCValAssign::Full:
1971 break;
1972 case CCValAssign::BCvt:
1973 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1974 break;
1975 }
1976
1977 InVals.push_back(Val);
1978 }
1979
1980 return Chain;
1981}
1982
1983bool AArch64TargetLowering::isEligibleForTailCallOptimization(
1984 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1985 bool isCalleeStructRet, bool isCallerStructRet,
1986 const SmallVectorImpl<ISD::OutputArg> &Outs,
1987 const SmallVectorImpl<SDValue> &OutVals,
1988 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1989 // For CallingConv::C this function knows whether the ABI needs
1990 // changing. That's not true for other conventions so they will have to opt in
1991 // manually.
1992 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1993 return false;
1994
1995 const MachineFunction &MF = DAG.getMachineFunction();
1996 const Function *CallerF = MF.getFunction();
1997 CallingConv::ID CallerCC = CallerF->getCallingConv();
1998 bool CCMatch = CallerCC == CalleeCC;
1999
2000 // Byval parameters hand the function a pointer directly into the stack area
2001 // we want to reuse during a tail call. Working around this *is* possible (see
2002 // X86) but less efficient and uglier in LowerCall.
2003 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2004 e = CallerF->arg_end();
2005 i != e; ++i)
2006 if (i->hasByValAttr())
2007 return false;
2008
2009 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2010 if (IsTailCallConvention(CalleeCC) && CCMatch)
2011 return true;
2012 return false;
2013 }
2014
2015 // Now we search for cases where we can use a tail call without changing the
2016 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2017 // concept.
2018
2019 // I want anyone implementing a new calling convention to think long and hard
2020 // about this assert.
2021 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2022 "Unexpected variadic calling convention");
2023
2024 if (isVarArg && !Outs.empty()) {
2025 // At least two cases here: if caller is fastcc then we can't have any
2026 // memory arguments (we'd be expected to clean up the stack afterwards). If
2027 // caller is C then we could potentially use its argument area.
2028
2029 // FIXME: for now we take the most conservative of these in both cases:
2030 // disallow all variadic memory operands.
2031 SmallVector<CCValAssign, 16> ArgLocs;
2032 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2033 getTargetMachine(), ArgLocs, *DAG.getContext());
2034
2035 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2036 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2037 if (!ArgLocs[i].isRegLoc())
2038 return false;
2039 }
2040
2041 // If the calling conventions do not match, then we'd better make sure the
2042 // results are returned in the same way as what the caller expects.
2043 if (!CCMatch) {
2044 SmallVector<CCValAssign, 16> RVLocs1;
2045 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2046 getTargetMachine(), RVLocs1, *DAG.getContext());
2047 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2048
2049 SmallVector<CCValAssign, 16> RVLocs2;
2050 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2051 getTargetMachine(), RVLocs2, *DAG.getContext());
2052 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2053
2054 if (RVLocs1.size() != RVLocs2.size())
2055 return false;
2056 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2057 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2058 return false;
2059 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2060 return false;
2061 if (RVLocs1[i].isRegLoc()) {
2062 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2063 return false;
2064 } else {
2065 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2066 return false;
2067 }
2068 }
2069 }
2070
2071 // Nothing more to check if the callee is taking no arguments
2072 if (Outs.empty())
2073 return true;
2074
2075 SmallVector<CCValAssign, 16> ArgLocs;
2076 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2077 getTargetMachine(), ArgLocs, *DAG.getContext());
2078
2079 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2080
2081 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2082
2083 // If the stack arguments for this call would fit into our own save area then
2084 // the call can be made tail.
2085 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2086}
2087
2088SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2089 SelectionDAG &DAG,
2090 MachineFrameInfo *MFI,
2091 int ClobberedFI) const {
2092 SmallVector<SDValue, 8> ArgChains;
2093 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2094 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2095
2096 // Include the original chain at the beginning of the list. When this is
2097 // used by target LowerCall hooks, this helps legalize find the
2098 // CALLSEQ_BEGIN node.
2099 ArgChains.push_back(Chain);
2100
2101 // Add a chain value for each stack argument corresponding
2102 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2103 UE = DAG.getEntryNode().getNode()->use_end();
2104 U != UE; ++U)
2105 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2106 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2107 if (FI->getIndex() < 0) {
2108 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2109 int64_t InLastByte = InFirstByte;
2110 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2111
2112 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2113 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2114 ArgChains.push_back(SDValue(L, 1));
2115 }
2116
2117 // Build a tokenfactor for all the chains.
2118 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2119}
2120
2121bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2122 bool TailCallOpt) const {
2123 return CallCC == CallingConv::Fast && TailCallOpt;
2124}
2125
2126bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2127 return CallCC == CallingConv::Fast;
2128}
2129
2130/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2131/// and add input and output parameter nodes.
2132SDValue
2133AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2134 SmallVectorImpl<SDValue> &InVals) const {
2135 SelectionDAG &DAG = CLI.DAG;
2136 SDLoc &DL = CLI.DL;
2137 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2138 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2139 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2140 SDValue Chain = CLI.Chain;
2141 SDValue Callee = CLI.Callee;
2142 bool &IsTailCall = CLI.IsTailCall;
2143 CallingConv::ID CallConv = CLI.CallConv;
2144 bool IsVarArg = CLI.IsVarArg;
2145
2146 MachineFunction &MF = DAG.getMachineFunction();
2147 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2148 bool IsThisReturn = false;
2149
2150 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2151 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2152 bool IsSibCall = false;
2153
2154 if (IsTailCall) {
2155 // Check if it's really possible to do a tail call.
2156 IsTailCall = isEligibleForTailCallOptimization(
2157 Callee, CallConv, IsVarArg, IsStructRet,
2158 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2159 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2160 report_fatal_error("failed to perform tail call elimination on a call "
2161 "site marked musttail");
2162
2163 // A sibling call is one where we're under the usual C ABI and not planning
2164 // to change that but can still do a tail call:
2165 if (!TailCallOpt && IsTailCall)
2166 IsSibCall = true;
2167
2168 if (IsTailCall)
2169 ++NumTailCalls;
2170 }
2171
2172 // Analyze operands of the call, assigning locations to each operand.
2173 SmallVector<CCValAssign, 16> ArgLocs;
2174 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2175 getTargetMachine(), ArgLocs, *DAG.getContext());
2176
2177 if (IsVarArg) {
2178 // Handle fixed and variable vector arguments differently.
2179 // Variable vector arguments always go into memory.
2180 unsigned NumArgs = Outs.size();
2181
2182 for (unsigned i = 0; i != NumArgs; ++i) {
2183 MVT ArgVT = Outs[i].VT;
2184 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2185 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2186 /*IsVarArg=*/ !Outs[i].IsFixed);
2187 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2188 assert(!Res && "Call operand has unhandled type");
2189 (void)Res;
2190 }
2191 } else {
2192 // At this point, Outs[].VT may already be promoted to i32. To correctly
2193 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2194 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2195 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2196 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2197 // LocVT.
2198 unsigned NumArgs = Outs.size();
2199 for (unsigned i = 0; i != NumArgs; ++i) {
2200 MVT ValVT = Outs[i].VT;
2201 // Get type of the original argument.
2202 EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2203 /*AllowUnknown*/ true);
2204 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2205 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2206 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002207 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002208 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002209 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002210 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002211
2212 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002213 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002214 assert(!Res && "Call operand has unhandled type");
2215 (void)Res;
2216 }
2217 }
2218
2219 // Get a count of how many bytes are to be pushed on the stack.
2220 unsigned NumBytes = CCInfo.getNextStackOffset();
2221
2222 if (IsSibCall) {
2223 // Since we're not changing the ABI to make this a tail call, the memory
2224 // operands are already available in the caller's incoming argument space.
2225 NumBytes = 0;
2226 }
2227
2228 // FPDiff is the byte offset of the call's argument area from the callee's.
2229 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2230 // by this amount for a tail call. In a sibling call it must be 0 because the
2231 // caller will deallocate the entire stack and the callee still expects its
2232 // arguments to begin at SP+0. Completely unused for non-tail calls.
2233 int FPDiff = 0;
2234
2235 if (IsTailCall && !IsSibCall) {
2236 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2237
2238 // Since callee will pop argument stack as a tail call, we must keep the
2239 // popped size 16-byte aligned.
2240 NumBytes = RoundUpToAlignment(NumBytes, 16);
2241
2242 // FPDiff will be negative if this tail call requires more space than we
2243 // would automatically have in our incoming argument space. Positive if we
2244 // can actually shrink the stack.
2245 FPDiff = NumReusableBytes - NumBytes;
2246
2247 // The stack pointer must be 16-byte aligned at all times it's used for a
2248 // memory operation, which in practice means at *all* times and in
2249 // particular across call boundaries. Therefore our own arguments started at
2250 // a 16-byte aligned SP and the delta applied for the tail call should
2251 // satisfy the same constraint.
2252 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2253 }
2254
2255 // Adjust the stack pointer for the new arguments...
2256 // These operations are automatically eliminated by the prolog/epilog pass
2257 if (!IsSibCall)
2258 Chain =
2259 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2260
2261 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2262
2263 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2264 SmallVector<SDValue, 8> MemOpChains;
2265
2266 // Walk the register/memloc assignments, inserting copies/loads.
2267 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2268 ++i, ++realArgIdx) {
2269 CCValAssign &VA = ArgLocs[i];
2270 SDValue Arg = OutVals[realArgIdx];
2271 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2272
2273 // Promote the value if needed.
2274 switch (VA.getLocInfo()) {
2275 default:
2276 llvm_unreachable("Unknown loc info!");
2277 case CCValAssign::Full:
2278 break;
2279 case CCValAssign::SExt:
2280 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2281 break;
2282 case CCValAssign::ZExt:
2283 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2284 break;
2285 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00002286 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2287 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2288 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2289 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2290 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002291 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2292 break;
2293 case CCValAssign::BCvt:
2294 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2295 break;
2296 case CCValAssign::FPExt:
2297 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2298 break;
2299 }
2300
2301 if (VA.isRegLoc()) {
2302 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2303 assert(VA.getLocVT() == MVT::i64 &&
2304 "unexpected calling convention register assignment");
2305 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2306 "unexpected use of 'returned'");
2307 IsThisReturn = true;
2308 }
2309 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2310 } else {
2311 assert(VA.isMemLoc());
2312
2313 SDValue DstAddr;
2314 MachinePointerInfo DstInfo;
2315
2316 // FIXME: This works on big-endian for composite byvals, which are the
2317 // common case. It should also work for fundamental types too.
2318 uint32_t BEAlign = 0;
2319 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2320 : VA.getLocVT().getSizeInBits();
2321 OpSize = (OpSize + 7) / 8;
2322 if (!Subtarget->isLittleEndian() && !Flags.isByVal()) {
2323 if (OpSize < 8)
2324 BEAlign = 8 - OpSize;
2325 }
2326 unsigned LocMemOffset = VA.getLocMemOffset();
2327 int32_t Offset = LocMemOffset + BEAlign;
2328 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2329 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2330
2331 if (IsTailCall) {
2332 Offset = Offset + FPDiff;
2333 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2334
2335 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2336 DstInfo = MachinePointerInfo::getFixedStack(FI);
2337
2338 // Make sure any stack arguments overlapping with where we're storing
2339 // are loaded before this eventual operation. Otherwise they'll be
2340 // clobbered.
2341 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2342 } else {
2343 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2344
2345 DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2346 DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2347 }
2348
2349 if (Outs[i].Flags.isByVal()) {
2350 SDValue SizeNode =
2351 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2352 SDValue Cpy = DAG.getMemcpy(
2353 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2354 /*isVolatile = */ false,
2355 /*alwaysInline = */ false, DstInfo, MachinePointerInfo());
2356
2357 MemOpChains.push_back(Cpy);
2358 } else {
2359 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2360 // promoted to a legal register type i32, we should truncate Arg back to
2361 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00002362 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2363 VA.getValVT() == MVT::i16)
2364 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00002365
2366 SDValue Store =
2367 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2368 MemOpChains.push_back(Store);
2369 }
2370 }
2371 }
2372
2373 if (!MemOpChains.empty())
2374 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2375
2376 // Build a sequence of copy-to-reg nodes chained together with token chain
2377 // and flag operands which copy the outgoing args into the appropriate regs.
2378 SDValue InFlag;
2379 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2380 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2381 RegsToPass[i].second, InFlag);
2382 InFlag = Chain.getValue(1);
2383 }
2384
2385 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2386 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2387 // node so that legalize doesn't hack it.
2388 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2389 Subtarget->isTargetMachO()) {
2390 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2391 const GlobalValue *GV = G->getGlobal();
2392 bool InternalLinkage = GV->hasInternalLinkage();
2393 if (InternalLinkage)
2394 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2395 else {
2396 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2397 AArch64II::MO_GOT);
2398 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2399 }
2400 } else if (ExternalSymbolSDNode *S =
2401 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2402 const char *Sym = S->getSymbol();
2403 Callee =
2404 DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2405 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2406 }
2407 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2408 const GlobalValue *GV = G->getGlobal();
2409 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2410 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2411 const char *Sym = S->getSymbol();
2412 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2413 }
2414
2415 // We don't usually want to end the call-sequence here because we would tidy
2416 // the frame up *after* the call, however in the ABI-changing tail-call case
2417 // we've carefully laid out the parameters so that when sp is reset they'll be
2418 // in the correct location.
2419 if (IsTailCall && !IsSibCall) {
2420 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2421 DAG.getIntPtrConstant(0, true), InFlag, DL);
2422 InFlag = Chain.getValue(1);
2423 }
2424
2425 std::vector<SDValue> Ops;
2426 Ops.push_back(Chain);
2427 Ops.push_back(Callee);
2428
2429 if (IsTailCall) {
2430 // Each tail call may have to adjust the stack by a different amount, so
2431 // this information must travel along with the operation for eventual
2432 // consumption by emitEpilogue.
2433 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
2434 }
2435
2436 // Add argument registers to the end of the list so that they are known live
2437 // into the call.
2438 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2439 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2440 RegsToPass[i].second.getValueType()));
2441
2442 // Add a register mask operand representing the call-preserved registers.
2443 const uint32_t *Mask;
Eric Christopherd9134482014-08-04 21:25:23 +00002444 const TargetRegisterInfo *TRI =
2445 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002446 const AArch64RegisterInfo *ARI =
2447 static_cast<const AArch64RegisterInfo *>(TRI);
2448 if (IsThisReturn) {
2449 // For 'this' returns, use the X0-preserving mask if applicable
2450 Mask = ARI->getThisReturnPreservedMask(CallConv);
2451 if (!Mask) {
2452 IsThisReturn = false;
2453 Mask = ARI->getCallPreservedMask(CallConv);
2454 }
2455 } else
2456 Mask = ARI->getCallPreservedMask(CallConv);
2457
2458 assert(Mask && "Missing call preserved mask for calling convention");
2459 Ops.push_back(DAG.getRegisterMask(Mask));
2460
2461 if (InFlag.getNode())
2462 Ops.push_back(InFlag);
2463
2464 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2465
2466 // If we're doing a tall call, use a TC_RETURN here rather than an
2467 // actual call instruction.
2468 if (IsTailCall)
2469 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
2470
2471 // Returns a chain and a flag for retval copy to use.
2472 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2473 InFlag = Chain.getValue(1);
2474
2475 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2476 ? RoundUpToAlignment(NumBytes, 16)
2477 : 0;
2478
2479 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2480 DAG.getIntPtrConstant(CalleePopBytes, true),
2481 InFlag, DL);
2482 if (!Ins.empty())
2483 InFlag = Chain.getValue(1);
2484
2485 // Handle result values, copying them out of physregs into vregs that we
2486 // return.
2487 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2488 InVals, IsThisReturn,
2489 IsThisReturn ? OutVals[0] : SDValue());
2490}
2491
2492bool AArch64TargetLowering::CanLowerReturn(
2493 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2494 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2495 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2496 ? RetCC_AArch64_WebKit_JS
2497 : RetCC_AArch64_AAPCS;
2498 SmallVector<CCValAssign, 16> RVLocs;
2499 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2500 return CCInfo.CheckReturn(Outs, RetCC);
2501}
2502
2503SDValue
2504AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2505 bool isVarArg,
2506 const SmallVectorImpl<ISD::OutputArg> &Outs,
2507 const SmallVectorImpl<SDValue> &OutVals,
2508 SDLoc DL, SelectionDAG &DAG) const {
2509 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2510 ? RetCC_AArch64_WebKit_JS
2511 : RetCC_AArch64_AAPCS;
2512 SmallVector<CCValAssign, 16> RVLocs;
2513 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2514 getTargetMachine(), RVLocs, *DAG.getContext());
2515 CCInfo.AnalyzeReturn(Outs, RetCC);
2516
2517 // Copy the result values into the output registers.
2518 SDValue Flag;
2519 SmallVector<SDValue, 4> RetOps(1, Chain);
2520 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2521 ++i, ++realRVLocIdx) {
2522 CCValAssign &VA = RVLocs[i];
2523 assert(VA.isRegLoc() && "Can only return in registers!");
2524 SDValue Arg = OutVals[realRVLocIdx];
2525
2526 switch (VA.getLocInfo()) {
2527 default:
2528 llvm_unreachable("Unknown loc info!");
2529 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00002530 if (Outs[i].ArgVT == MVT::i1) {
2531 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2532 // value. This is strictly redundant on Darwin (which uses "zeroext
2533 // i1"), but will be optimised out before ISel.
2534 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2535 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2536 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002537 break;
2538 case CCValAssign::BCvt:
2539 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2540 break;
2541 }
2542
2543 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2544 Flag = Chain.getValue(1);
2545 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2546 }
2547
2548 RetOps[0] = Chain; // Update chain.
2549
2550 // Add the flag if we have it.
2551 if (Flag.getNode())
2552 RetOps.push_back(Flag);
2553
2554 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2555}
2556
2557//===----------------------------------------------------------------------===//
2558// Other Lowering Code
2559//===----------------------------------------------------------------------===//
2560
2561SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2562 SelectionDAG &DAG) const {
2563 EVT PtrVT = getPointerTy();
2564 SDLoc DL(Op);
2565 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2566 unsigned char OpFlags =
2567 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2568
2569 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2570 "unexpected offset in global node");
2571
2572 // This also catched the large code model case for Darwin.
2573 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2574 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2575 // FIXME: Once remat is capable of dealing with instructions with register
2576 // operands, expand this into two nodes instead of using a wrapper node.
2577 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2578 }
2579
2580 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2581 const unsigned char MO_NC = AArch64II::MO_NC;
2582 return DAG.getNode(
2583 AArch64ISD::WrapperLarge, DL, PtrVT,
2584 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
2585 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
2586 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
2587 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
2588 } else {
2589 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2590 // the only correct model on Darwin.
2591 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2592 OpFlags | AArch64II::MO_PAGE);
2593 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2594 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2595
2596 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2597 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2598 }
2599}
2600
2601/// \brief Convert a TLS address reference into the correct sequence of loads
2602/// and calls to compute the variable's address (for Darwin, currently) and
2603/// return an SDValue containing the final node.
2604
2605/// Darwin only has one TLS scheme which must be capable of dealing with the
2606/// fully general situation, in the worst case. This means:
2607/// + "extern __thread" declaration.
2608/// + Defined in a possibly unknown dynamic library.
2609///
2610/// The general system is that each __thread variable has a [3 x i64] descriptor
2611/// which contains information used by the runtime to calculate the address. The
2612/// only part of this the compiler needs to know about is the first xword, which
2613/// contains a function pointer that must be called with the address of the
2614/// entire descriptor in "x0".
2615///
2616/// Since this descriptor may be in a different unit, in general even the
2617/// descriptor must be accessed via an indirect load. The "ideal" code sequence
2618/// is:
2619/// adrp x0, _var@TLVPPAGE
2620/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2621/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2622/// ; the function pointer
2623/// blr x1 ; Uses descriptor address in x0
2624/// ; Address of _var is now in x0.
2625///
2626/// If the address of _var's descriptor *is* known to the linker, then it can
2627/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2628/// a slight efficiency gain.
2629SDValue
2630AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2631 SelectionDAG &DAG) const {
2632 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2633
2634 SDLoc DL(Op);
2635 MVT PtrVT = getPointerTy();
2636 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2637
2638 SDValue TLVPAddr =
2639 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2640 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2641
2642 // The first entry in the descriptor is a function pointer that we must call
2643 // to obtain the address of the variable.
2644 SDValue Chain = DAG.getEntryNode();
2645 SDValue FuncTLVGet =
2646 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2647 false, true, true, 8);
2648 Chain = FuncTLVGet.getValue(1);
2649
2650 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2651 MFI->setAdjustsStack(true);
2652
2653 // TLS calls preserve all registers except those that absolutely must be
2654 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2655 // silly).
Eric Christopherd9134482014-08-04 21:25:23 +00002656 const TargetRegisterInfo *TRI =
2657 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002658 const AArch64RegisterInfo *ARI =
2659 static_cast<const AArch64RegisterInfo *>(TRI);
2660 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2661
2662 // Finally, we can make the call. This is just a degenerate version of a
2663 // normal AArch64 call node: x0 takes the address of the descriptor, and
2664 // returns the address of the variable in this thread.
2665 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
2666 Chain =
2667 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2668 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
2669 DAG.getRegisterMask(Mask), Chain.getValue(1));
2670 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
2671}
2672
2673/// When accessing thread-local variables under either the general-dynamic or
2674/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2675/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2676/// is a function pointer to carry out the resolution. This function takes the
2677/// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2678/// other registers (except LR, NZCV) are preserved.
2679///
2680/// Thus, the ideal call sequence on AArch64 is:
2681///
2682/// adrp x0, :tlsdesc:thread_var
2683/// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2684/// add x0, x0, :tlsdesc_lo12:thread_var
2685/// .tlsdesccall thread_var
2686/// blr x8
2687/// (TPIDR_EL0 offset now in x0).
2688///
2689/// The ".tlsdesccall" directive instructs the assembler to insert a particular
2690/// relocation to help the linker relax this sequence if it turns out to be too
2691/// conservative.
2692///
2693/// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2694/// is harmless.
2695SDValue AArch64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2696 SDValue DescAddr, SDLoc DL,
2697 SelectionDAG &DAG) const {
2698 EVT PtrVT = getPointerTy();
2699
2700 // The function we need to call is simply the first entry in the GOT for this
2701 // descriptor, load it in preparation.
2702 SDValue Func = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, SymAddr);
2703
2704 // TLS calls preserve all registers except those that absolutely must be
2705 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2706 // silly).
Eric Christopherd9134482014-08-04 21:25:23 +00002707 const TargetRegisterInfo *TRI =
2708 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002709 const AArch64RegisterInfo *ARI =
2710 static_cast<const AArch64RegisterInfo *>(TRI);
2711 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2712
2713 // The function takes only one argument: the address of the descriptor itself
2714 // in X0.
2715 SDValue Glue, Chain;
2716 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2717 Glue = Chain.getValue(1);
2718
2719 // We're now ready to populate the argument list, as with a normal call:
2720 SmallVector<SDValue, 6> Ops;
2721 Ops.push_back(Chain);
2722 Ops.push_back(Func);
2723 Ops.push_back(SymAddr);
2724 Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2725 Ops.push_back(DAG.getRegisterMask(Mask));
2726 Ops.push_back(Glue);
2727
2728 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2729 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALL, DL, NodeTys, Ops);
2730 Glue = Chain.getValue(1);
2731
2732 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2733}
2734
2735SDValue
2736AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2737 SelectionDAG &DAG) const {
2738 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2739 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2740 "ELF TLS only supported in small memory model");
2741 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2742
2743 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2744
2745 SDValue TPOff;
2746 EVT PtrVT = getPointerTy();
2747 SDLoc DL(Op);
2748 const GlobalValue *GV = GA->getGlobal();
2749
2750 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2751
2752 if (Model == TLSModel::LocalExec) {
2753 SDValue HiVar = DAG.getTargetGlobalAddress(
2754 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
2755 SDValue LoVar = DAG.getTargetGlobalAddress(
2756 GV, DL, PtrVT, 0,
2757 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
2758
2759 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
2760 DAG.getTargetConstant(16, MVT::i32)),
2761 0);
2762 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2763 DAG.getTargetConstant(0, MVT::i32)),
2764 0);
2765 } else if (Model == TLSModel::InitialExec) {
2766 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2767 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
2768 } else if (Model == TLSModel::LocalDynamic) {
2769 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2770 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2771 // the beginning of the module's TLS region, followed by a DTPREL offset
2772 // calculation.
2773
2774 // These accesses will need deduplicating if there's more than one.
2775 AArch64FunctionInfo *MFI =
2776 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
2777 MFI->incNumLocalDynamicTLSAccesses();
2778
2779 // Accesses used in this sequence go via the TLS descriptor which lives in
2780 // the GOT. Prepare an address we can use to handle this.
2781 SDValue HiDesc = DAG.getTargetExternalSymbol(
2782 "_TLS_MODULE_BASE_", PtrVT, AArch64II::MO_TLS | AArch64II::MO_PAGE);
2783 SDValue LoDesc = DAG.getTargetExternalSymbol(
2784 "_TLS_MODULE_BASE_", PtrVT,
2785 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2786
2787 // First argument to the descriptor call is the address of the descriptor
2788 // itself.
2789 SDValue DescAddr = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, HiDesc);
2790 DescAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2791
2792 // The call needs a relocation too for linker relaxation. It doesn't make
2793 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2794 // the address.
2795 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2796 AArch64II::MO_TLS);
2797
2798 // Now we can calculate the offset from TPIDR_EL0 to this module's
2799 // thread-local area.
2800 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2801
2802 // Now use :dtprel_whatever: operations to calculate this variable's offset
2803 // in its thread-storage area.
2804 SDValue HiVar = DAG.getTargetGlobalAddress(
2805 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
2806 SDValue LoVar = DAG.getTargetGlobalAddress(
2807 GV, DL, MVT::i64, 0,
2808 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
2809
2810 SDValue DTPOff =
2811 SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
2812 DAG.getTargetConstant(16, MVT::i32)),
2813 0);
2814 DTPOff =
2815 SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2816 DAG.getTargetConstant(0, MVT::i32)),
2817 0);
2818
2819 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2820 } else if (Model == TLSModel::GeneralDynamic) {
2821 // Accesses used in this sequence go via the TLS descriptor which lives in
2822 // the GOT. Prepare an address we can use to handle this.
2823 SDValue HiDesc = DAG.getTargetGlobalAddress(
2824 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGE);
2825 SDValue LoDesc = DAG.getTargetGlobalAddress(
2826 GV, DL, PtrVT, 0,
2827 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2828
2829 // First argument to the descriptor call is the address of the descriptor
2830 // itself.
2831 SDValue DescAddr = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, HiDesc);
2832 DescAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2833
2834 // The call needs a relocation too for linker relaxation. It doesn't make
2835 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2836 // the address.
2837 SDValue SymAddr =
2838 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
2839
2840 // Finally we can make a call to calculate the offset from tpidr_el0.
2841 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2842 } else
2843 llvm_unreachable("Unsupported ELF TLS access model");
2844
2845 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2846}
2847
2848SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2849 SelectionDAG &DAG) const {
2850 if (Subtarget->isTargetDarwin())
2851 return LowerDarwinGlobalTLSAddress(Op, DAG);
2852 else if (Subtarget->isTargetELF())
2853 return LowerELFGlobalTLSAddress(Op, DAG);
2854
2855 llvm_unreachable("Unexpected platform trying to use TLS");
2856}
2857SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2858 SDValue Chain = Op.getOperand(0);
2859 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2860 SDValue LHS = Op.getOperand(2);
2861 SDValue RHS = Op.getOperand(3);
2862 SDValue Dest = Op.getOperand(4);
2863 SDLoc dl(Op);
2864
2865 // Handle f128 first, since lowering it will result in comparing the return
2866 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2867 // is expecting to deal with.
2868 if (LHS.getValueType() == MVT::f128) {
2869 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2870
2871 // If softenSetCCOperands returned a scalar, we need to compare the result
2872 // against zero to select between true and false values.
2873 if (!RHS.getNode()) {
2874 RHS = DAG.getConstant(0, LHS.getValueType());
2875 CC = ISD::SETNE;
2876 }
2877 }
2878
2879 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2880 // instruction.
2881 unsigned Opc = LHS.getOpcode();
2882 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2883 cast<ConstantSDNode>(RHS)->isOne() &&
2884 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2885 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2886 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2887 "Unexpected condition code.");
2888 // Only lower legal XALUO ops.
2889 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2890 return SDValue();
2891
2892 // The actual operation with overflow check.
2893 AArch64CC::CondCode OFCC;
2894 SDValue Value, Overflow;
2895 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
2896
2897 if (CC == ISD::SETNE)
2898 OFCC = getInvertedCondCode(OFCC);
2899 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2900
2901 return DAG.getNode(AArch64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2902 CCVal, Overflow);
2903 }
2904
2905 if (LHS.getValueType().isInteger()) {
2906 assert((LHS.getValueType() == RHS.getValueType()) &&
2907 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2908
2909 // If the RHS of the comparison is zero, we can potentially fold this
2910 // to a specialized branch.
2911 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2912 if (RHSC && RHSC->getZExtValue() == 0) {
2913 if (CC == ISD::SETEQ) {
2914 // See if we can use a TBZ to fold in an AND as well.
2915 // TBZ has a smaller branch displacement than CBZ. If the offset is
2916 // out of bounds, a late MI-layer pass rewrites branches.
2917 // 403.gcc is an example that hits this case.
2918 if (LHS.getOpcode() == ISD::AND &&
2919 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2920 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2921 SDValue Test = LHS.getOperand(0);
2922 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00002923 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
2924 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2925 }
2926
2927 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2928 } else if (CC == ISD::SETNE) {
2929 // See if we can use a TBZ to fold in an AND as well.
2930 // TBZ has a smaller branch displacement than CBZ. If the offset is
2931 // out of bounds, a late MI-layer pass rewrites branches.
2932 // 403.gcc is an example that hits this case.
2933 if (LHS.getOpcode() == ISD::AND &&
2934 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2935 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2936 SDValue Test = LHS.getOperand(0);
2937 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00002938 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2939 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2940 }
2941
2942 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00002943 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
2944 // Don't combine AND since emitComparison converts the AND to an ANDS
2945 // (a.k.a. TST) and the test in the test bit and branch instruction
2946 // becomes redundant. This would also increase register pressure.
2947 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
2948 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
2949 DAG.getConstant(Mask, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00002950 }
2951 }
Chad Rosier579c02c2014-08-01 14:48:56 +00002952 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
2953 LHS.getOpcode() != ISD::AND) {
2954 // Don't combine AND since emitComparison converts the AND to an ANDS
2955 // (a.k.a. TST) and the test in the test bit and branch instruction
2956 // becomes redundant. This would also increase register pressure.
2957 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
2958 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
2959 DAG.getConstant(Mask, MVT::i64), Dest);
2960 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002961
2962 SDValue CCVal;
2963 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2964 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2965 Cmp);
2966 }
2967
2968 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2969
2970 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
2971 // clean. Some of them require two branches to implement.
2972 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2973 AArch64CC::CondCode CC1, CC2;
2974 changeFPCCToAArch64CC(CC, CC1, CC2);
2975 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2976 SDValue BR1 =
2977 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2978 if (CC2 != AArch64CC::AL) {
2979 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2980 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2981 Cmp);
2982 }
2983
2984 return BR1;
2985}
2986
2987SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2988 SelectionDAG &DAG) const {
2989 EVT VT = Op.getValueType();
2990 SDLoc DL(Op);
2991
2992 SDValue In1 = Op.getOperand(0);
2993 SDValue In2 = Op.getOperand(1);
2994 EVT SrcVT = In2.getValueType();
2995 if (SrcVT != VT) {
2996 if (SrcVT == MVT::f32 && VT == MVT::f64)
2997 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2998 else if (SrcVT == MVT::f64 && VT == MVT::f32)
2999 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3000 else
3001 // FIXME: Src type is different, bail out for now. Can VT really be a
3002 // vector type?
3003 return SDValue();
3004 }
3005
3006 EVT VecVT;
3007 EVT EltVT;
3008 SDValue EltMask, VecVal1, VecVal2;
3009 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3010 EltVT = MVT::i32;
3011 VecVT = MVT::v4i32;
3012 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
3013
3014 if (!VT.isVector()) {
3015 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3016 DAG.getUNDEF(VecVT), In1);
3017 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3018 DAG.getUNDEF(VecVT), In2);
3019 } else {
3020 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3021 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3022 }
3023 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3024 EltVT = MVT::i64;
3025 VecVT = MVT::v2i64;
3026
3027 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3028 // immediate moves cannot materialize that in a single instruction for
3029 // 64-bit elements. Instead, materialize zero and then negate it.
3030 EltMask = DAG.getConstant(0, EltVT);
3031
3032 if (!VT.isVector()) {
3033 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3034 DAG.getUNDEF(VecVT), In1);
3035 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3036 DAG.getUNDEF(VecVT), In2);
3037 } else {
3038 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3039 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3040 }
3041 } else {
3042 llvm_unreachable("Invalid type for copysign!");
3043 }
3044
3045 std::vector<SDValue> BuildVectorOps;
3046 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
3047 BuildVectorOps.push_back(EltMask);
3048
3049 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
3050
3051 // If we couldn't materialize the mask above, then the mask vector will be
3052 // the zero vector, and we need to negate it here.
3053 if (VT == MVT::f64 || VT == MVT::v2f64) {
3054 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3055 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3056 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3057 }
3058
3059 SDValue Sel =
3060 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3061
3062 if (VT == MVT::f32)
3063 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3064 else if (VT == MVT::f64)
3065 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3066 else
3067 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3068}
3069
3070SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3071 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
3072 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
3073 return SDValue();
3074
3075 // While there is no integer popcount instruction, it can
3076 // be more efficiently lowered to the following sequence that uses
3077 // AdvSIMD registers/instructions as long as the copies to/from
3078 // the AdvSIMD registers are cheap.
3079 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3080 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3081 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3082 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3083 SDValue Val = Op.getOperand(0);
3084 SDLoc DL(Op);
3085 EVT VT = Op.getValueType();
3086 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
3087
3088 SDValue VecVal;
3089 if (VT == MVT::i32) {
3090 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
3091 VecVal = DAG.getTargetInsertSubreg(AArch64::ssub, DL, MVT::v8i8, ZeroVec,
3092 VecVal);
3093 } else {
3094 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3095 }
3096
3097 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
3098 SDValue UaddLV = DAG.getNode(
3099 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3100 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, MVT::i32), CtPop);
3101
3102 if (VT == MVT::i64)
3103 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3104 return UaddLV;
3105}
3106
3107SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3108
3109 if (Op.getValueType().isVector())
3110 return LowerVSETCC(Op, DAG);
3111
3112 SDValue LHS = Op.getOperand(0);
3113 SDValue RHS = Op.getOperand(1);
3114 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3115 SDLoc dl(Op);
3116
3117 // We chose ZeroOrOneBooleanContents, so use zero and one.
3118 EVT VT = Op.getValueType();
3119 SDValue TVal = DAG.getConstant(1, VT);
3120 SDValue FVal = DAG.getConstant(0, VT);
3121
3122 // Handle f128 first, since one possible outcome is a normal integer
3123 // comparison which gets picked up by the next if statement.
3124 if (LHS.getValueType() == MVT::f128) {
3125 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3126
3127 // If softenSetCCOperands returned a scalar, use it.
3128 if (!RHS.getNode()) {
3129 assert(LHS.getValueType() == Op.getValueType() &&
3130 "Unexpected setcc expansion!");
3131 return LHS;
3132 }
3133 }
3134
3135 if (LHS.getValueType().isInteger()) {
3136 SDValue CCVal;
3137 SDValue Cmp =
3138 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3139
3140 // Note that we inverted the condition above, so we reverse the order of
3141 // the true and false operands here. This will allow the setcc to be
3142 // matched to a single CSINC instruction.
3143 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3144 }
3145
3146 // Now we know we're dealing with FP values.
3147 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3148
3149 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3150 // and do the comparison.
3151 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3152
3153 AArch64CC::CondCode CC1, CC2;
3154 changeFPCCToAArch64CC(CC, CC1, CC2);
3155 if (CC2 == AArch64CC::AL) {
3156 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3157 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3158
3159 // Note that we inverted the condition above, so we reverse the order of
3160 // the true and false operands here. This will allow the setcc to be
3161 // matched to a single CSINC instruction.
3162 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3163 } else {
3164 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3165 // totally clean. Some of them require two CSELs to implement. As is in
3166 // this case, we emit the first CSEL and then emit a second using the output
3167 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3168
3169 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3170 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3171 SDValue CS1 =
3172 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3173
3174 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3175 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3176 }
3177}
3178
3179/// A SELECT_CC operation is really some kind of max or min if both values being
3180/// compared are, in some sense, equal to the results in either case. However,
3181/// it is permissible to compare f32 values and produce directly extended f64
3182/// values.
3183///
3184/// Extending the comparison operands would also be allowed, but is less likely
3185/// to happen in practice since their use is right here. Note that truncate
3186/// operations would *not* be semantically equivalent.
3187static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3188 if (Cmp == Result)
3189 return true;
3190
3191 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3192 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3193 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3194 Result.getValueType() == MVT::f64) {
3195 bool Lossy;
3196 APFloat CmpVal = CCmp->getValueAPF();
3197 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3198 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3199 }
3200
3201 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3202}
3203
3204SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3205 SelectionDAG &DAG) const {
3206 SDValue CC = Op->getOperand(0);
3207 SDValue TVal = Op->getOperand(1);
3208 SDValue FVal = Op->getOperand(2);
3209 SDLoc DL(Op);
3210
3211 unsigned Opc = CC.getOpcode();
3212 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3213 // instruction.
3214 if (CC.getResNo() == 1 &&
3215 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3216 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3217 // Only lower legal XALUO ops.
3218 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3219 return SDValue();
3220
3221 AArch64CC::CondCode OFCC;
3222 SDValue Value, Overflow;
3223 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CC.getValue(0), DAG);
3224 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3225
3226 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3227 CCVal, Overflow);
3228 }
3229
3230 if (CC.getOpcode() == ISD::SETCC)
3231 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3232 cast<CondCodeSDNode>(CC.getOperand(2))->get());
3233 else
3234 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3235 FVal, ISD::SETNE);
3236}
3237
3238SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3239 SelectionDAG &DAG) const {
3240 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3241 SDValue LHS = Op.getOperand(0);
3242 SDValue RHS = Op.getOperand(1);
3243 SDValue TVal = Op.getOperand(2);
3244 SDValue FVal = Op.getOperand(3);
3245 SDLoc dl(Op);
3246
3247 // Handle f128 first, because it will result in a comparison of some RTLIB
3248 // call result against zero.
3249 if (LHS.getValueType() == MVT::f128) {
3250 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3251
3252 // If softenSetCCOperands returned a scalar, we need to compare the result
3253 // against zero to select between true and false values.
3254 if (!RHS.getNode()) {
3255 RHS = DAG.getConstant(0, LHS.getValueType());
3256 CC = ISD::SETNE;
3257 }
3258 }
3259
3260 // Handle integers first.
3261 if (LHS.getValueType().isInteger()) {
3262 assert((LHS.getValueType() == RHS.getValueType()) &&
3263 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3264
3265 unsigned Opcode = AArch64ISD::CSEL;
3266
3267 // If both the TVal and the FVal are constants, see if we can swap them in
3268 // order to for a CSINV or CSINC out of them.
3269 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3270 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3271
3272 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3273 std::swap(TVal, FVal);
3274 std::swap(CTVal, CFVal);
3275 CC = ISD::getSetCCInverse(CC, true);
3276 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3277 std::swap(TVal, FVal);
3278 std::swap(CTVal, CFVal);
3279 CC = ISD::getSetCCInverse(CC, true);
3280 } else if (TVal.getOpcode() == ISD::XOR) {
3281 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3282 // with a CSINV rather than a CSEL.
3283 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3284
3285 if (CVal && CVal->isAllOnesValue()) {
3286 std::swap(TVal, FVal);
3287 std::swap(CTVal, CFVal);
3288 CC = ISD::getSetCCInverse(CC, true);
3289 }
3290 } else if (TVal.getOpcode() == ISD::SUB) {
3291 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3292 // that we can match with a CSNEG rather than a CSEL.
3293 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3294
3295 if (CVal && CVal->isNullValue()) {
3296 std::swap(TVal, FVal);
3297 std::swap(CTVal, CFVal);
3298 CC = ISD::getSetCCInverse(CC, true);
3299 }
3300 } else if (CTVal && CFVal) {
3301 const int64_t TrueVal = CTVal->getSExtValue();
3302 const int64_t FalseVal = CFVal->getSExtValue();
3303 bool Swap = false;
3304
3305 // If both TVal and FVal are constants, see if FVal is the
3306 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3307 // instead of a CSEL in that case.
3308 if (TrueVal == ~FalseVal) {
3309 Opcode = AArch64ISD::CSINV;
3310 } else if (TrueVal == -FalseVal) {
3311 Opcode = AArch64ISD::CSNEG;
3312 } else if (TVal.getValueType() == MVT::i32) {
3313 // If our operands are only 32-bit wide, make sure we use 32-bit
3314 // arithmetic for the check whether we can use CSINC. This ensures that
3315 // the addition in the check will wrap around properly in case there is
3316 // an overflow (which would not be the case if we do the check with
3317 // 64-bit arithmetic).
3318 const uint32_t TrueVal32 = CTVal->getZExtValue();
3319 const uint32_t FalseVal32 = CFVal->getZExtValue();
3320
3321 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3322 Opcode = AArch64ISD::CSINC;
3323
3324 if (TrueVal32 > FalseVal32) {
3325 Swap = true;
3326 }
3327 }
3328 // 64-bit check whether we can use CSINC.
3329 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3330 Opcode = AArch64ISD::CSINC;
3331
3332 if (TrueVal > FalseVal) {
3333 Swap = true;
3334 }
3335 }
3336
3337 // Swap TVal and FVal if necessary.
3338 if (Swap) {
3339 std::swap(TVal, FVal);
3340 std::swap(CTVal, CFVal);
3341 CC = ISD::getSetCCInverse(CC, true);
3342 }
3343
3344 if (Opcode != AArch64ISD::CSEL) {
3345 // Drop FVal since we can get its value by simply inverting/negating
3346 // TVal.
3347 FVal = TVal;
3348 }
3349 }
3350
3351 SDValue CCVal;
3352 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3353
3354 EVT VT = Op.getValueType();
3355 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3356 }
3357
3358 // Now we know we're dealing with FP values.
3359 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3360 assert(LHS.getValueType() == RHS.getValueType());
3361 EVT VT = Op.getValueType();
3362
3363 // Try to match this select into a max/min operation, which have dedicated
3364 // opcode in the instruction set.
3365 // FIXME: This is not correct in the presence of NaNs, so we only enable this
3366 // in no-NaNs mode.
3367 if (getTargetMachine().Options.NoNaNsFPMath) {
3368 SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3369 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3370 selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3371 CC = ISD::getSetCCSwappedOperands(CC);
3372 std::swap(MinMaxLHS, MinMaxRHS);
3373 }
3374
3375 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3376 selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3377 switch (CC) {
3378 default:
3379 break;
3380 case ISD::SETGT:
3381 case ISD::SETGE:
3382 case ISD::SETUGT:
3383 case ISD::SETUGE:
3384 case ISD::SETOGT:
3385 case ISD::SETOGE:
3386 return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3387 break;
3388 case ISD::SETLT:
3389 case ISD::SETLE:
3390 case ISD::SETULT:
3391 case ISD::SETULE:
3392 case ISD::SETOLT:
3393 case ISD::SETOLE:
3394 return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3395 break;
3396 }
3397 }
3398 }
3399
3400 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3401 // and do the comparison.
3402 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3403
3404 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3405 // clean. Some of them require two CSELs to implement.
3406 AArch64CC::CondCode CC1, CC2;
3407 changeFPCCToAArch64CC(CC, CC1, CC2);
3408 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3409 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3410
3411 // If we need a second CSEL, emit it, using the output of the first as the
3412 // RHS. We're effectively OR'ing the two CC's together.
3413 if (CC2 != AArch64CC::AL) {
3414 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3415 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3416 }
3417
3418 // Otherwise, return the output of the first CSEL.
3419 return CS1;
3420}
3421
3422SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3423 SelectionDAG &DAG) const {
3424 // Jump table entries as PC relative offsets. No additional tweaking
3425 // is necessary here. Just get the address of the jump table.
3426 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3427 EVT PtrVT = getPointerTy();
3428 SDLoc DL(Op);
3429
3430 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3431 !Subtarget->isTargetMachO()) {
3432 const unsigned char MO_NC = AArch64II::MO_NC;
3433 return DAG.getNode(
3434 AArch64ISD::WrapperLarge, DL, PtrVT,
3435 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3436 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3437 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3438 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3439 AArch64II::MO_G0 | MO_NC));
3440 }
3441
3442 SDValue Hi =
3443 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3444 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3445 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3446 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3447 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3448}
3449
3450SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3451 SelectionDAG &DAG) const {
3452 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3453 EVT PtrVT = getPointerTy();
3454 SDLoc DL(Op);
3455
3456 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3457 // Use the GOT for the large code model on iOS.
3458 if (Subtarget->isTargetMachO()) {
3459 SDValue GotAddr = DAG.getTargetConstantPool(
3460 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3461 AArch64II::MO_GOT);
3462 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3463 }
3464
3465 const unsigned char MO_NC = AArch64II::MO_NC;
3466 return DAG.getNode(
3467 AArch64ISD::WrapperLarge, DL, PtrVT,
3468 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3469 CP->getOffset(), AArch64II::MO_G3),
3470 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3471 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3472 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3473 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3474 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3475 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3476 } else {
3477 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3478 // ELF, the only valid one on Darwin.
3479 SDValue Hi =
3480 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3481 CP->getOffset(), AArch64II::MO_PAGE);
3482 SDValue Lo = DAG.getTargetConstantPool(
3483 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3484 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3485
3486 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3487 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3488 }
3489}
3490
3491SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3492 SelectionDAG &DAG) const {
3493 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3494 EVT PtrVT = getPointerTy();
3495 SDLoc DL(Op);
3496 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3497 !Subtarget->isTargetMachO()) {
3498 const unsigned char MO_NC = AArch64II::MO_NC;
3499 return DAG.getNode(
3500 AArch64ISD::WrapperLarge, DL, PtrVT,
3501 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3502 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3503 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3504 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3505 } else {
3506 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3507 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3508 AArch64II::MO_NC);
3509 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3510 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3511 }
3512}
3513
3514SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3515 SelectionDAG &DAG) const {
3516 AArch64FunctionInfo *FuncInfo =
3517 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3518
3519 SDLoc DL(Op);
3520 SDValue FR =
3521 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3522 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3523 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3524 MachinePointerInfo(SV), false, false, 0);
3525}
3526
3527SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3528 SelectionDAG &DAG) const {
3529 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3530 // Standard, section B.3.
3531 MachineFunction &MF = DAG.getMachineFunction();
3532 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3533 SDLoc DL(Op);
3534
3535 SDValue Chain = Op.getOperand(0);
3536 SDValue VAList = Op.getOperand(1);
3537 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3538 SmallVector<SDValue, 4> MemOps;
3539
3540 // void *__stack at offset 0
3541 SDValue Stack =
3542 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3543 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3544 MachinePointerInfo(SV), false, false, 8));
3545
3546 // void *__gr_top at offset 8
3547 int GPRSize = FuncInfo->getVarArgsGPRSize();
3548 if (GPRSize > 0) {
3549 SDValue GRTop, GRTopAddr;
3550
3551 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3552 DAG.getConstant(8, getPointerTy()));
3553
3554 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3555 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3556 DAG.getConstant(GPRSize, getPointerTy()));
3557
3558 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3559 MachinePointerInfo(SV, 8), false, false, 8));
3560 }
3561
3562 // void *__vr_top at offset 16
3563 int FPRSize = FuncInfo->getVarArgsFPRSize();
3564 if (FPRSize > 0) {
3565 SDValue VRTop, VRTopAddr;
3566 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3567 DAG.getConstant(16, getPointerTy()));
3568
3569 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3570 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3571 DAG.getConstant(FPRSize, getPointerTy()));
3572
3573 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3574 MachinePointerInfo(SV, 16), false, false, 8));
3575 }
3576
3577 // int __gr_offs at offset 24
3578 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3579 DAG.getConstant(24, getPointerTy()));
3580 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3581 GROffsAddr, MachinePointerInfo(SV, 24), false,
3582 false, 4));
3583
3584 // int __vr_offs at offset 28
3585 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3586 DAG.getConstant(28, getPointerTy()));
3587 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3588 VROffsAddr, MachinePointerInfo(SV, 28), false,
3589 false, 4));
3590
3591 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3592}
3593
3594SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3595 SelectionDAG &DAG) const {
3596 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3597 : LowerAAPCS_VASTART(Op, DAG);
3598}
3599
3600SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3601 SelectionDAG &DAG) const {
3602 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3603 // pointer.
3604 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3605 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3606 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3607
3608 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3609 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3610 8, false, false, MachinePointerInfo(DestSV),
3611 MachinePointerInfo(SrcSV));
3612}
3613
3614SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3615 assert(Subtarget->isTargetDarwin() &&
3616 "automatic va_arg instruction only works on Darwin");
3617
3618 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3619 EVT VT = Op.getValueType();
3620 SDLoc DL(Op);
3621 SDValue Chain = Op.getOperand(0);
3622 SDValue Addr = Op.getOperand(1);
3623 unsigned Align = Op.getConstantOperandVal(3);
3624
3625 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3626 MachinePointerInfo(V), false, false, false, 0);
3627 Chain = VAList.getValue(1);
3628
3629 if (Align > 8) {
3630 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3631 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3632 DAG.getConstant(Align - 1, getPointerTy()));
3633 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3634 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3635 }
3636
3637 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3638 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3639
3640 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3641 // up to 64 bits. At the very least, we have to increase the striding of the
3642 // vaargs list to match this, and for FP values we need to introduce
3643 // FP_ROUND nodes as well.
3644 if (VT.isInteger() && !VT.isVector())
3645 ArgSize = 8;
3646 bool NeedFPTrunc = false;
3647 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3648 ArgSize = 8;
3649 NeedFPTrunc = true;
3650 }
3651
3652 // Increment the pointer, VAList, to the next vaarg
3653 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3654 DAG.getConstant(ArgSize, getPointerTy()));
3655 // Store the incremented VAList to the legalized pointer
3656 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3657 false, false, 0);
3658
3659 // Load the actual argument out of the pointer VAList
3660 if (NeedFPTrunc) {
3661 // Load the value as an f64.
3662 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3663 MachinePointerInfo(), false, false, false, 0);
3664 // Round the value down to an f32.
3665 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3666 DAG.getIntPtrConstant(1));
3667 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3668 // Merge the rounded value with the chain output of the load.
3669 return DAG.getMergeValues(Ops, DL);
3670 }
3671
3672 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3673 false, false, 0);
3674}
3675
3676SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
3677 SelectionDAG &DAG) const {
3678 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3679 MFI->setFrameAddressIsTaken(true);
3680
3681 EVT VT = Op.getValueType();
3682 SDLoc DL(Op);
3683 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3684 SDValue FrameAddr =
3685 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
3686 while (Depth--)
3687 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3688 MachinePointerInfo(), false, false, false, 0);
3689 return FrameAddr;
3690}
3691
3692// FIXME? Maybe this could be a TableGen attribute on some registers and
3693// this table could be generated automatically from RegInfo.
3694unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
3695 EVT VT) const {
3696 unsigned Reg = StringSwitch<unsigned>(RegName)
3697 .Case("sp", AArch64::SP)
3698 .Default(0);
3699 if (Reg)
3700 return Reg;
3701 report_fatal_error("Invalid register name global variable");
3702}
3703
3704SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
3705 SelectionDAG &DAG) const {
3706 MachineFunction &MF = DAG.getMachineFunction();
3707 MachineFrameInfo *MFI = MF.getFrameInfo();
3708 MFI->setReturnAddressIsTaken(true);
3709
3710 EVT VT = Op.getValueType();
3711 SDLoc DL(Op);
3712 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3713 if (Depth) {
3714 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3715 SDValue Offset = DAG.getConstant(8, getPointerTy());
3716 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3717 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3718 MachinePointerInfo(), false, false, false, 0);
3719 }
3720
3721 // Return LR, which contains the return address. Mark it an implicit live-in.
3722 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
3723 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3724}
3725
3726/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3727/// i64 values and take a 2 x i64 value to shift plus a shift amount.
3728SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
3729 SelectionDAG &DAG) const {
3730 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3731 EVT VT = Op.getValueType();
3732 unsigned VTBits = VT.getSizeInBits();
3733 SDLoc dl(Op);
3734 SDValue ShOpLo = Op.getOperand(0);
3735 SDValue ShOpHi = Op.getOperand(1);
3736 SDValue ShAmt = Op.getOperand(2);
3737 SDValue ARMcc;
3738 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3739
3740 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3741
3742 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3743 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3744 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3745 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3746 DAG.getConstant(VTBits, MVT::i64));
3747 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3748
3749 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3750 ISD::SETGE, dl, DAG);
3751 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
3752
3753 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3754 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3755 SDValue Lo =
3756 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3757
3758 // AArch64 shifts larger than the register width are wrapped rather than
3759 // clamped, so we can't just emit "hi >> x".
3760 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3761 SDValue TrueValHi = Opc == ISD::SRA
3762 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3763 DAG.getConstant(VTBits - 1, MVT::i64))
3764 : DAG.getConstant(0, VT);
3765 SDValue Hi =
3766 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3767
3768 SDValue Ops[2] = { Lo, Hi };
3769 return DAG.getMergeValues(Ops, dl);
3770}
3771
3772/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3773/// i64 values and take a 2 x i64 value to shift plus a shift amount.
3774SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
3775 SelectionDAG &DAG) const {
3776 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3777 EVT VT = Op.getValueType();
3778 unsigned VTBits = VT.getSizeInBits();
3779 SDLoc dl(Op);
3780 SDValue ShOpLo = Op.getOperand(0);
3781 SDValue ShOpHi = Op.getOperand(1);
3782 SDValue ShAmt = Op.getOperand(2);
3783 SDValue ARMcc;
3784
3785 assert(Op.getOpcode() == ISD::SHL_PARTS);
3786 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3787 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3788 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3789 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3790 DAG.getConstant(VTBits, MVT::i64));
3791 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3792 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3793
3794 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3795
3796 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3797 ISD::SETGE, dl, DAG);
3798 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
3799 SDValue Hi =
3800 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3801
3802 // AArch64 shifts of larger than register sizes are wrapped rather than
3803 // clamped, so we can't just emit "lo << a" if a is too big.
3804 SDValue TrueValLo = DAG.getConstant(0, VT);
3805 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3806 SDValue Lo =
3807 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3808
3809 SDValue Ops[2] = { Lo, Hi };
3810 return DAG.getMergeValues(Ops, dl);
3811}
3812
3813bool AArch64TargetLowering::isOffsetFoldingLegal(
3814 const GlobalAddressSDNode *GA) const {
3815 // The AArch64 target doesn't support folding offsets into global addresses.
3816 return false;
3817}
3818
3819bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3820 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3821 // FIXME: We should be able to handle f128 as well with a clever lowering.
3822 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3823 return true;
3824
3825 if (VT == MVT::f64)
3826 return AArch64_AM::getFP64Imm(Imm) != -1;
3827 else if (VT == MVT::f32)
3828 return AArch64_AM::getFP32Imm(Imm) != -1;
3829 return false;
3830}
3831
3832//===----------------------------------------------------------------------===//
3833// AArch64 Optimization Hooks
3834//===----------------------------------------------------------------------===//
3835
3836//===----------------------------------------------------------------------===//
3837// AArch64 Inline Assembly Support
3838//===----------------------------------------------------------------------===//
3839
3840// Table of Constraints
3841// TODO: This is the current set of constraints supported by ARM for the
3842// compiler, not all of them may make sense, e.g. S may be difficult to support.
3843//
3844// r - A general register
3845// w - An FP/SIMD register of some size in the range v0-v31
3846// x - An FP/SIMD register of some size in the range v0-v15
3847// I - Constant that can be used with an ADD instruction
3848// J - Constant that can be used with a SUB instruction
3849// K - Constant that can be used with a 32-bit logical instruction
3850// L - Constant that can be used with a 64-bit logical instruction
3851// M - Constant that can be used as a 32-bit MOV immediate
3852// N - Constant that can be used as a 64-bit MOV immediate
3853// Q - A memory reference with base register and no offset
3854// S - A symbolic address
3855// Y - Floating point constant zero
3856// Z - Integer constant zero
3857//
3858// Note that general register operands will be output using their 64-bit x
3859// register name, whatever the size of the variable, unless the asm operand
3860// is prefixed by the %w modifier. Floating-point and SIMD register operands
3861// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3862// %q modifier.
3863
3864/// getConstraintType - Given a constraint letter, return the type of
3865/// constraint it is for this target.
3866AArch64TargetLowering::ConstraintType
3867AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3868 if (Constraint.size() == 1) {
3869 switch (Constraint[0]) {
3870 default:
3871 break;
3872 case 'z':
3873 return C_Other;
3874 case 'x':
3875 case 'w':
3876 return C_RegisterClass;
3877 // An address with a single base register. Due to the way we
3878 // currently handle addresses it is the same as 'r'.
3879 case 'Q':
3880 return C_Memory;
3881 }
3882 }
3883 return TargetLowering::getConstraintType(Constraint);
3884}
3885
3886/// Examine constraint type and operand type and determine a weight value.
3887/// This object must already have been set up with the operand type
3888/// and the current alternative constraint selected.
3889TargetLowering::ConstraintWeight
3890AArch64TargetLowering::getSingleConstraintMatchWeight(
3891 AsmOperandInfo &info, const char *constraint) const {
3892 ConstraintWeight weight = CW_Invalid;
3893 Value *CallOperandVal = info.CallOperandVal;
3894 // If we don't have a value, we can't do a match,
3895 // but allow it at the lowest weight.
3896 if (!CallOperandVal)
3897 return CW_Default;
3898 Type *type = CallOperandVal->getType();
3899 // Look at the constraint type.
3900 switch (*constraint) {
3901 default:
3902 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3903 break;
3904 case 'x':
3905 case 'w':
3906 if (type->isFloatingPointTy() || type->isVectorTy())
3907 weight = CW_Register;
3908 break;
3909 case 'z':
3910 weight = CW_Constant;
3911 break;
3912 }
3913 return weight;
3914}
3915
3916std::pair<unsigned, const TargetRegisterClass *>
3917AArch64TargetLowering::getRegForInlineAsmConstraint(
3918 const std::string &Constraint, MVT VT) const {
3919 if (Constraint.size() == 1) {
3920 switch (Constraint[0]) {
3921 case 'r':
3922 if (VT.getSizeInBits() == 64)
3923 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
3924 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
3925 case 'w':
3926 if (VT == MVT::f32)
3927 return std::make_pair(0U, &AArch64::FPR32RegClass);
3928 if (VT.getSizeInBits() == 64)
3929 return std::make_pair(0U, &AArch64::FPR64RegClass);
3930 if (VT.getSizeInBits() == 128)
3931 return std::make_pair(0U, &AArch64::FPR128RegClass);
3932 break;
3933 // The instructions that this constraint is designed for can
3934 // only take 128-bit registers so just use that regclass.
3935 case 'x':
3936 if (VT.getSizeInBits() == 128)
3937 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
3938 break;
3939 }
3940 }
3941 if (StringRef("{cc}").equals_lower(Constraint))
3942 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
3943
3944 // Use the default implementation in TargetLowering to convert the register
3945 // constraint into a member of a register class.
3946 std::pair<unsigned, const TargetRegisterClass *> Res;
3947 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3948
3949 // Not found as a standard register?
3950 if (!Res.second) {
3951 unsigned Size = Constraint.size();
3952 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3953 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3954 const std::string Reg =
3955 std::string(&Constraint[2], &Constraint[Size - 1]);
3956 int RegNo = atoi(Reg.c_str());
3957 if (RegNo >= 0 && RegNo <= 31) {
3958 // v0 - v31 are aliases of q0 - q31.
3959 // By default we'll emit v0-v31 for this unless there's a modifier where
3960 // we'll emit the correct register as well.
3961 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
3962 Res.second = &AArch64::FPR128RegClass;
3963 }
3964 }
3965 }
3966
3967 return Res;
3968}
3969
3970/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3971/// vector. If it is invalid, don't add anything to Ops.
3972void AArch64TargetLowering::LowerAsmOperandForConstraint(
3973 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3974 SelectionDAG &DAG) const {
3975 SDValue Result;
3976
3977 // Currently only support length 1 constraints.
3978 if (Constraint.length() != 1)
3979 return;
3980
3981 char ConstraintLetter = Constraint[0];
3982 switch (ConstraintLetter) {
3983 default:
3984 break;
3985
3986 // This set of constraints deal with valid constants for various instructions.
3987 // Validate and return a target constant for them if we can.
3988 case 'z': {
3989 // 'z' maps to xzr or wzr so it needs an input of 0.
3990 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3991 if (!C || C->getZExtValue() != 0)
3992 return;
3993
3994 if (Op.getValueType() == MVT::i64)
3995 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
3996 else
3997 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
3998 break;
3999 }
4000
4001 case 'I':
4002 case 'J':
4003 case 'K':
4004 case 'L':
4005 case 'M':
4006 case 'N':
4007 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4008 if (!C)
4009 return;
4010
4011 // Grab the value and do some validation.
4012 uint64_t CVal = C->getZExtValue();
4013 switch (ConstraintLetter) {
4014 // The I constraint applies only to simple ADD or SUB immediate operands:
4015 // i.e. 0 to 4095 with optional shift by 12
4016 // The J constraint applies only to ADD or SUB immediates that would be
4017 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4018 // instruction [or vice versa], in other words -1 to -4095 with optional
4019 // left shift by 12.
4020 case 'I':
4021 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4022 break;
4023 return;
4024 case 'J': {
4025 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004026 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4027 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004028 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004029 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004030 return;
4031 }
4032 // The K and L constraints apply *only* to logical immediates, including
4033 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4034 // been removed and MOV should be used). So these constraints have to
4035 // distinguish between bit patterns that are valid 32-bit or 64-bit
4036 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4037 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4038 // versa.
4039 case 'K':
4040 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4041 break;
4042 return;
4043 case 'L':
4044 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4045 break;
4046 return;
4047 // The M and N constraints are a superset of K and L respectively, for use
4048 // with the MOV (immediate) alias. As well as the logical immediates they
4049 // also match 32 or 64-bit immediates that can be loaded either using a
4050 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4051 // (M) or 64-bit 0x1234000000000000 (N) etc.
4052 // As a note some of this code is liberally stolen from the asm parser.
4053 case 'M': {
4054 if (!isUInt<32>(CVal))
4055 return;
4056 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4057 break;
4058 if ((CVal & 0xFFFF) == CVal)
4059 break;
4060 if ((CVal & 0xFFFF0000ULL) == CVal)
4061 break;
4062 uint64_t NCVal = ~(uint32_t)CVal;
4063 if ((NCVal & 0xFFFFULL) == NCVal)
4064 break;
4065 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4066 break;
4067 return;
4068 }
4069 case 'N': {
4070 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4071 break;
4072 if ((CVal & 0xFFFFULL) == CVal)
4073 break;
4074 if ((CVal & 0xFFFF0000ULL) == CVal)
4075 break;
4076 if ((CVal & 0xFFFF00000000ULL) == CVal)
4077 break;
4078 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4079 break;
4080 uint64_t NCVal = ~CVal;
4081 if ((NCVal & 0xFFFFULL) == NCVal)
4082 break;
4083 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4084 break;
4085 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4086 break;
4087 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4088 break;
4089 return;
4090 }
4091 default:
4092 return;
4093 }
4094
4095 // All assembler immediates are 64-bit integers.
4096 Result = DAG.getTargetConstant(CVal, MVT::i64);
4097 break;
4098 }
4099
4100 if (Result.getNode()) {
4101 Ops.push_back(Result);
4102 return;
4103 }
4104
4105 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4106}
4107
4108//===----------------------------------------------------------------------===//
4109// AArch64 Advanced SIMD Support
4110//===----------------------------------------------------------------------===//
4111
4112/// WidenVector - Given a value in the V64 register class, produce the
4113/// equivalent value in the V128 register class.
4114static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4115 EVT VT = V64Reg.getValueType();
4116 unsigned NarrowSize = VT.getVectorNumElements();
4117 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4118 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4119 SDLoc DL(V64Reg);
4120
4121 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4122 V64Reg, DAG.getConstant(0, MVT::i32));
4123}
4124
4125/// getExtFactor - Determine the adjustment factor for the position when
4126/// generating an "extract from vector registers" instruction.
4127static unsigned getExtFactor(SDValue &V) {
4128 EVT EltType = V.getValueType().getVectorElementType();
4129 return EltType.getSizeInBits() / 8;
4130}
4131
4132/// NarrowVector - Given a value in the V128 register class, produce the
4133/// equivalent value in the V64 register class.
4134static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4135 EVT VT = V128Reg.getValueType();
4136 unsigned WideSize = VT.getVectorNumElements();
4137 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4138 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4139 SDLoc DL(V128Reg);
4140
4141 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4142}
4143
4144// Gather data to see if the operation can be modelled as a
4145// shuffle in combination with VEXTs.
4146SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4147 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004148 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004149 SDLoc dl(Op);
4150 EVT VT = Op.getValueType();
4151 unsigned NumElts = VT.getVectorNumElements();
4152
Tim Northover7324e842014-07-24 15:39:55 +00004153 struct ShuffleSourceInfo {
4154 SDValue Vec;
4155 unsigned MinElt;
4156 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004157
Tim Northover7324e842014-07-24 15:39:55 +00004158 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4159 // be compatible with the shuffle we intend to construct. As a result
4160 // ShuffleVec will be some sliding window into the original Vec.
4161 SDValue ShuffleVec;
4162
4163 // Code should guarantee that element i in Vec starts at element "WindowBase
4164 // + i * WindowScale in ShuffleVec".
4165 int WindowBase;
4166 int WindowScale;
4167
4168 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4169 ShuffleSourceInfo(SDValue Vec)
4170 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4171 WindowScale(1) {}
4172 };
4173
4174 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4175 // node.
4176 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004177 for (unsigned i = 0; i < NumElts; ++i) {
4178 SDValue V = Op.getOperand(i);
4179 if (V.getOpcode() == ISD::UNDEF)
4180 continue;
4181 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4182 // A shuffle can only come from building a vector from various
4183 // elements of other vectors.
4184 return SDValue();
4185 }
4186
Tim Northover7324e842014-07-24 15:39:55 +00004187 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004188 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004189 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4190 if (Source == Sources.end())
4191 Sources.push_back(ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004192
Tim Northover7324e842014-07-24 15:39:55 +00004193 // Update the minimum and maximum lane number seen.
4194 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4195 Source->MinElt = std::min(Source->MinElt, EltNo);
4196 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004197 }
4198
4199 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004200 // are involved.
4201 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004202 return SDValue();
4203
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004204 // Find out the smallest element size among result and two sources, and use
4205 // it as element size to build the shuffle_vector.
4206 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004207 for (auto &Source : Sources) {
4208 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004209 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4210 SmallestEltTy = SrcEltTy;
4211 }
4212 }
4213 unsigned ResMultiplier =
4214 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004215 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4216 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004217
Tim Northover7324e842014-07-24 15:39:55 +00004218 // If the source vector is too wide or too narrow, we may nevertheless be able
4219 // to construct a compatible shuffle either by concatenating it with UNDEF or
4220 // extracting a suitable range of elements.
4221 for (auto &Src : Sources) {
4222 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004223
Tim Northover7324e842014-07-24 15:39:55 +00004224 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004225 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004226
4227 // This stage of the search produces a source with the same element type as
4228 // the original, but with a total width matching the BUILD_VECTOR output.
4229 EVT EltVT = SrcVT.getVectorElementType();
4230 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
4231 VT.getSizeInBits() / EltVT.getSizeInBits());
4232
4233 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4234 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004235 // We can pad out the smaller vector for free, so if it's part of a
4236 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004237 Src.ShuffleVec =
4238 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4239 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004240 continue;
4241 }
4242
Tim Northover7324e842014-07-24 15:39:55 +00004243 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004244
Tim Northover7324e842014-07-24 15:39:55 +00004245 if (Src.MaxElt - Src.MinElt >= NumElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004246 // Span too large for a VEXT to cope
4247 return SDValue();
4248 }
4249
Tim Northover7324e842014-07-24 15:39:55 +00004250 if (Src.MinElt >= NumElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004251 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004252 Src.ShuffleVec =
4253 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4254 DAG.getIntPtrConstant(NumElts));
4255 Src.WindowBase = -NumElts;
4256 } else if (Src.MaxElt < NumElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004257 // The extraction can just take the first half
Tim Northover7324e842014-07-24 15:39:55 +00004258 Src.ShuffleVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4259 Src.ShuffleVec, DAG.getIntPtrConstant(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00004260 } else {
4261 // An actual VEXT is needed
Tim Northover7324e842014-07-24 15:39:55 +00004262 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4263 Src.ShuffleVec, DAG.getIntPtrConstant(0));
4264 SDValue VEXTSrc2 =
4265 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4266 DAG.getIntPtrConstant(NumElts));
4267 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4268
4269 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004270 VEXTSrc2, DAG.getConstant(Imm, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004271 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004272 }
4273 }
4274
Tim Northover7324e842014-07-24 15:39:55 +00004275 // Another possible incompatibility occurs from the vector element types. We
4276 // can fix this by bitcasting the source vectors to the same type we intend
4277 // for the shuffle.
4278 for (auto &Src : Sources) {
4279 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4280 if (SrcEltTy == SmallestEltTy)
4281 continue;
4282 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4283 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4284 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4285 Src.WindowBase *= Src.WindowScale;
4286 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004287
Tim Northover7324e842014-07-24 15:39:55 +00004288 // Final sanity check before we try to actually produce a shuffle.
4289 DEBUG(
4290 for (auto Src : Sources)
4291 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4292 );
4293
4294 // The stars all align, our next step is to produce the mask for the shuffle.
4295 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4296 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004297 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004298 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00004299 if (Entry.getOpcode() == ISD::UNDEF)
4300 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00004301
Tim Northover7324e842014-07-24 15:39:55 +00004302 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4303 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4304
4305 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4306 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4307 // segment.
4308 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4309 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4310 VT.getVectorElementType().getSizeInBits());
4311 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4312
4313 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4314 // starting at the appropriate offset.
4315 int *LaneMask = &Mask[i * ResMultiplier];
4316
4317 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4318 ExtractBase += NumElts * (Src - Sources.begin());
4319 for (int j = 0; j < LanesDefined; ++j)
4320 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00004321 }
4322
4323 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00004324 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4325 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004326
Tim Northover7324e842014-07-24 15:39:55 +00004327 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4328 for (unsigned i = 0; i < Sources.size(); ++i)
4329 ShuffleOps[i] = Sources[i].ShuffleVec;
4330
4331 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4332 ShuffleOps[1], &Mask[0]);
4333 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00004334}
4335
4336// check if an EXT instruction can handle the shuffle mask when the
4337// vector sources of the shuffle are the same.
4338static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4339 unsigned NumElts = VT.getVectorNumElements();
4340
4341 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4342 if (M[0] < 0)
4343 return false;
4344
4345 Imm = M[0];
4346
4347 // If this is a VEXT shuffle, the immediate value is the index of the first
4348 // element. The other shuffle indices must be the successive elements after
4349 // the first one.
4350 unsigned ExpectedElt = Imm;
4351 for (unsigned i = 1; i < NumElts; ++i) {
4352 // Increment the expected index. If it wraps around, just follow it
4353 // back to index zero and keep going.
4354 ++ExpectedElt;
4355 if (ExpectedElt == NumElts)
4356 ExpectedElt = 0;
4357
4358 if (M[i] < 0)
4359 continue; // ignore UNDEF indices
4360 if (ExpectedElt != static_cast<unsigned>(M[i]))
4361 return false;
4362 }
4363
4364 return true;
4365}
4366
4367// check if an EXT instruction can handle the shuffle mask when the
4368// vector sources of the shuffle are different.
4369static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4370 unsigned &Imm) {
4371 // Look for the first non-undef element.
4372 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4373 [](int Elt) {return Elt >= 0;});
4374
4375 // Benefit form APInt to handle overflow when calculating expected element.
4376 unsigned NumElts = VT.getVectorNumElements();
4377 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4378 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4379 // The following shuffle indices must be the successive elements after the
4380 // first real element.
4381 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4382 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4383 if (FirstWrongElt != M.end())
4384 return false;
4385
4386 // The index of an EXT is the first element if it is not UNDEF.
4387 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4388 // value of the first element. E.g.
4389 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4390 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4391 // ExpectedElt is the last mask index plus 1.
4392 Imm = ExpectedElt.getZExtValue();
4393
4394 // There are two difference cases requiring to reverse input vectors.
4395 // For example, for vector <4 x i32> we have the following cases,
4396 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4397 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4398 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4399 // to reverse two input vectors.
4400 if (Imm < NumElts)
4401 ReverseEXT = true;
4402 else
4403 Imm -= NumElts;
4404
4405 return true;
4406}
4407
4408/// isREVMask - Check if a vector shuffle corresponds to a REV
4409/// instruction with the specified blocksize. (The order of the elements
4410/// within each block of the vector is reversed.)
4411static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4412 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4413 "Only possible block sizes for REV are: 16, 32, 64");
4414
4415 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4416 if (EltSz == 64)
4417 return false;
4418
4419 unsigned NumElts = VT.getVectorNumElements();
4420 unsigned BlockElts = M[0] + 1;
4421 // If the first shuffle index is UNDEF, be optimistic.
4422 if (M[0] < 0)
4423 BlockElts = BlockSize / EltSz;
4424
4425 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4426 return false;
4427
4428 for (unsigned i = 0; i < NumElts; ++i) {
4429 if (M[i] < 0)
4430 continue; // ignore UNDEF indices
4431 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4432 return false;
4433 }
4434
4435 return true;
4436}
4437
4438static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4439 unsigned NumElts = VT.getVectorNumElements();
4440 WhichResult = (M[0] == 0 ? 0 : 1);
4441 unsigned Idx = WhichResult * NumElts / 2;
4442 for (unsigned i = 0; i != NumElts; i += 2) {
4443 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4444 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4445 return false;
4446 Idx += 1;
4447 }
4448
4449 return true;
4450}
4451
4452static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4453 unsigned NumElts = VT.getVectorNumElements();
4454 WhichResult = (M[0] == 0 ? 0 : 1);
4455 for (unsigned i = 0; i != NumElts; ++i) {
4456 if (M[i] < 0)
4457 continue; // ignore UNDEF indices
4458 if ((unsigned)M[i] != 2 * i + WhichResult)
4459 return false;
4460 }
4461
4462 return true;
4463}
4464
4465static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4466 unsigned NumElts = VT.getVectorNumElements();
4467 WhichResult = (M[0] == 0 ? 0 : 1);
4468 for (unsigned i = 0; i < NumElts; i += 2) {
4469 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4470 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4471 return false;
4472 }
4473 return true;
4474}
4475
4476/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4477/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4478/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4479static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4480 unsigned NumElts = VT.getVectorNumElements();
4481 WhichResult = (M[0] == 0 ? 0 : 1);
4482 unsigned Idx = WhichResult * NumElts / 2;
4483 for (unsigned i = 0; i != NumElts; i += 2) {
4484 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4485 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4486 return false;
4487 Idx += 1;
4488 }
4489
4490 return true;
4491}
4492
4493/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4494/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4495/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4496static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4497 unsigned Half = VT.getVectorNumElements() / 2;
4498 WhichResult = (M[0] == 0 ? 0 : 1);
4499 for (unsigned j = 0; j != 2; ++j) {
4500 unsigned Idx = WhichResult;
4501 for (unsigned i = 0; i != Half; ++i) {
4502 int MIdx = M[i + j * Half];
4503 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4504 return false;
4505 Idx += 2;
4506 }
4507 }
4508
4509 return true;
4510}
4511
4512/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4513/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4514/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4515static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4516 unsigned NumElts = VT.getVectorNumElements();
4517 WhichResult = (M[0] == 0 ? 0 : 1);
4518 for (unsigned i = 0; i < NumElts; i += 2) {
4519 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4520 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4521 return false;
4522 }
4523 return true;
4524}
4525
4526static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4527 bool &DstIsLeft, int &Anomaly) {
4528 if (M.size() != static_cast<size_t>(NumInputElements))
4529 return false;
4530
4531 int NumLHSMatch = 0, NumRHSMatch = 0;
4532 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4533
4534 for (int i = 0; i < NumInputElements; ++i) {
4535 if (M[i] == -1) {
4536 ++NumLHSMatch;
4537 ++NumRHSMatch;
4538 continue;
4539 }
4540
4541 if (M[i] == i)
4542 ++NumLHSMatch;
4543 else
4544 LastLHSMismatch = i;
4545
4546 if (M[i] == i + NumInputElements)
4547 ++NumRHSMatch;
4548 else
4549 LastRHSMismatch = i;
4550 }
4551
4552 if (NumLHSMatch == NumInputElements - 1) {
4553 DstIsLeft = true;
4554 Anomaly = LastLHSMismatch;
4555 return true;
4556 } else if (NumRHSMatch == NumInputElements - 1) {
4557 DstIsLeft = false;
4558 Anomaly = LastRHSMismatch;
4559 return true;
4560 }
4561
4562 return false;
4563}
4564
4565static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4566 if (VT.getSizeInBits() != 128)
4567 return false;
4568
4569 unsigned NumElts = VT.getVectorNumElements();
4570
4571 for (int I = 0, E = NumElts / 2; I != E; I++) {
4572 if (Mask[I] != I)
4573 return false;
4574 }
4575
4576 int Offset = NumElts / 2;
4577 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4578 if (Mask[I] != I + SplitLHS * Offset)
4579 return false;
4580 }
4581
4582 return true;
4583}
4584
4585static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4586 SDLoc DL(Op);
4587 EVT VT = Op.getValueType();
4588 SDValue V0 = Op.getOperand(0);
4589 SDValue V1 = Op.getOperand(1);
4590 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4591
4592 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4593 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4594 return SDValue();
4595
4596 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4597
4598 if (!isConcatMask(Mask, VT, SplitV0))
4599 return SDValue();
4600
4601 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4602 VT.getVectorNumElements() / 2);
4603 if (SplitV0) {
4604 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4605 DAG.getConstant(0, MVT::i64));
4606 }
4607 if (V1.getValueType().getSizeInBits() == 128) {
4608 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4609 DAG.getConstant(0, MVT::i64));
4610 }
4611 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4612}
4613
4614/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4615/// the specified operations to build the shuffle.
4616static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4617 SDValue RHS, SelectionDAG &DAG,
4618 SDLoc dl) {
4619 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4620 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4621 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4622
4623 enum {
4624 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4625 OP_VREV,
4626 OP_VDUP0,
4627 OP_VDUP1,
4628 OP_VDUP2,
4629 OP_VDUP3,
4630 OP_VEXT1,
4631 OP_VEXT2,
4632 OP_VEXT3,
4633 OP_VUZPL, // VUZP, left result
4634 OP_VUZPR, // VUZP, right result
4635 OP_VZIPL, // VZIP, left result
4636 OP_VZIPR, // VZIP, right result
4637 OP_VTRNL, // VTRN, left result
4638 OP_VTRNR // VTRN, right result
4639 };
4640
4641 if (OpNum == OP_COPY) {
4642 if (LHSID == (1 * 9 + 2) * 9 + 3)
4643 return LHS;
4644 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4645 return RHS;
4646 }
4647
4648 SDValue OpLHS, OpRHS;
4649 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4650 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4651 EVT VT = OpLHS.getValueType();
4652
4653 switch (OpNum) {
4654 default:
4655 llvm_unreachable("Unknown shuffle opcode!");
4656 case OP_VREV:
4657 // VREV divides the vector in half and swaps within the half.
4658 if (VT.getVectorElementType() == MVT::i32 ||
4659 VT.getVectorElementType() == MVT::f32)
4660 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
4661 // vrev <4 x i16> -> REV32
4662 if (VT.getVectorElementType() == MVT::i16)
4663 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
4664 // vrev <4 x i8> -> REV16
4665 assert(VT.getVectorElementType() == MVT::i8);
4666 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
4667 case OP_VDUP0:
4668 case OP_VDUP1:
4669 case OP_VDUP2:
4670 case OP_VDUP3: {
4671 EVT EltTy = VT.getVectorElementType();
4672 unsigned Opcode;
4673 if (EltTy == MVT::i8)
4674 Opcode = AArch64ISD::DUPLANE8;
4675 else if (EltTy == MVT::i16)
4676 Opcode = AArch64ISD::DUPLANE16;
4677 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4678 Opcode = AArch64ISD::DUPLANE32;
4679 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4680 Opcode = AArch64ISD::DUPLANE64;
4681 else
4682 llvm_unreachable("Invalid vector element type?");
4683
4684 if (VT.getSizeInBits() == 64)
4685 OpLHS = WidenVector(OpLHS, DAG);
4686 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4687 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4688 }
4689 case OP_VEXT1:
4690 case OP_VEXT2:
4691 case OP_VEXT3: {
4692 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4693 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
4694 DAG.getConstant(Imm, MVT::i32));
4695 }
4696 case OP_VUZPL:
4697 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
4698 OpRHS);
4699 case OP_VUZPR:
4700 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
4701 OpRHS);
4702 case OP_VZIPL:
4703 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
4704 OpRHS);
4705 case OP_VZIPR:
4706 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
4707 OpRHS);
4708 case OP_VTRNL:
4709 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
4710 OpRHS);
4711 case OP_VTRNR:
4712 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
4713 OpRHS);
4714 }
4715}
4716
4717static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4718 SelectionDAG &DAG) {
4719 // Check to see if we can use the TBL instruction.
4720 SDValue V1 = Op.getOperand(0);
4721 SDValue V2 = Op.getOperand(1);
4722 SDLoc DL(Op);
4723
4724 EVT EltVT = Op.getValueType().getVectorElementType();
4725 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4726
4727 SmallVector<SDValue, 8> TBLMask;
4728 for (int Val : ShuffleMask) {
4729 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4730 unsigned Offset = Byte + Val * BytesPerElt;
4731 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4732 }
4733 }
4734
4735 MVT IndexVT = MVT::v8i8;
4736 unsigned IndexLen = 8;
4737 if (Op.getValueType().getSizeInBits() == 128) {
4738 IndexVT = MVT::v16i8;
4739 IndexLen = 16;
4740 }
4741
4742 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4743 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4744
4745 SDValue Shuffle;
4746 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4747 if (IndexLen == 8)
4748 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4749 Shuffle = DAG.getNode(
4750 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4751 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
4752 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4753 makeArrayRef(TBLMask.data(), IndexLen)));
4754 } else {
4755 if (IndexLen == 8) {
4756 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4757 Shuffle = DAG.getNode(
4758 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4759 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
4760 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4761 makeArrayRef(TBLMask.data(), IndexLen)));
4762 } else {
4763 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4764 // cannot currently represent the register constraints on the input
4765 // table registers.
4766 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4767 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4768 // &TBLMask[0], IndexLen));
4769 Shuffle = DAG.getNode(
4770 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4771 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4772 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4773 makeArrayRef(TBLMask.data(), IndexLen)));
4774 }
4775 }
4776 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4777}
4778
4779static unsigned getDUPLANEOp(EVT EltType) {
4780 if (EltType == MVT::i8)
4781 return AArch64ISD::DUPLANE8;
4782 if (EltType == MVT::i16)
4783 return AArch64ISD::DUPLANE16;
4784 if (EltType == MVT::i32 || EltType == MVT::f32)
4785 return AArch64ISD::DUPLANE32;
4786 if (EltType == MVT::i64 || EltType == MVT::f64)
4787 return AArch64ISD::DUPLANE64;
4788
4789 llvm_unreachable("Invalid vector element type?");
4790}
4791
4792SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4793 SelectionDAG &DAG) const {
4794 SDLoc dl(Op);
4795 EVT VT = Op.getValueType();
4796
4797 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4798
4799 // Convert shuffles that are directly supported on NEON to target-specific
4800 // DAG nodes, instead of keeping them as shuffles and matching them again
4801 // during code selection. This is more efficient and avoids the possibility
4802 // of inconsistencies between legalization and selection.
4803 ArrayRef<int> ShuffleMask = SVN->getMask();
4804
4805 SDValue V1 = Op.getOperand(0);
4806 SDValue V2 = Op.getOperand(1);
4807
4808 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4809 V1.getValueType().getSimpleVT())) {
4810 int Lane = SVN->getSplatIndex();
4811 // If this is undef splat, generate it via "just" vdup, if possible.
4812 if (Lane == -1)
4813 Lane = 0;
4814
4815 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4816 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
4817 V1.getOperand(0));
4818 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4819 // constant. If so, we can just reference the lane's definition directly.
4820 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4821 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4822 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
4823
4824 // Otherwise, duplicate from the lane of the input vector.
4825 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4826
4827 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4828 // to make a vector of the same size as this SHUFFLE. We can ignore the
4829 // extract entirely, and canonicalise the concat using WidenVector.
4830 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4831 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4832 V1 = V1.getOperand(0);
4833 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4834 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4835 Lane -= Idx * VT.getVectorNumElements() / 2;
4836 V1 = WidenVector(V1.getOperand(Idx), DAG);
4837 } else if (VT.getSizeInBits() == 64)
4838 V1 = WidenVector(V1, DAG);
4839
4840 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4841 }
4842
4843 if (isREVMask(ShuffleMask, VT, 64))
4844 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
4845 if (isREVMask(ShuffleMask, VT, 32))
4846 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
4847 if (isREVMask(ShuffleMask, VT, 16))
4848 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
4849
4850 bool ReverseEXT = false;
4851 unsigned Imm;
4852 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4853 if (ReverseEXT)
4854 std::swap(V1, V2);
4855 Imm *= getExtFactor(V1);
4856 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
4857 DAG.getConstant(Imm, MVT::i32));
4858 } else if (V2->getOpcode() == ISD::UNDEF &&
4859 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4860 Imm *= getExtFactor(V1);
4861 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
4862 DAG.getConstant(Imm, MVT::i32));
4863 }
4864
4865 unsigned WhichResult;
4866 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4867 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
4868 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4869 }
4870 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4871 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
4872 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4873 }
4874 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4875 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
4876 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4877 }
4878
4879 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4880 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
4881 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4882 }
4883 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4884 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
4885 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4886 }
4887 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4888 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
4889 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4890 }
4891
4892 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4893 if (Concat.getNode())
4894 return Concat;
4895
4896 bool DstIsLeft;
4897 int Anomaly;
4898 int NumInputElements = V1.getValueType().getVectorNumElements();
4899 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4900 SDValue DstVec = DstIsLeft ? V1 : V2;
4901 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4902
4903 SDValue SrcVec = V1;
4904 int SrcLane = ShuffleMask[Anomaly];
4905 if (SrcLane >= NumInputElements) {
4906 SrcVec = V2;
4907 SrcLane -= VT.getVectorNumElements();
4908 }
4909 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4910
4911 EVT ScalarVT = VT.getVectorElementType();
4912 if (ScalarVT.getSizeInBits() < 32)
4913 ScalarVT = MVT::i32;
4914
4915 return DAG.getNode(
4916 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4917 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4918 DstLaneV);
4919 }
4920
4921 // If the shuffle is not directly supported and it has 4 elements, use
4922 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4923 unsigned NumElts = VT.getVectorNumElements();
4924 if (NumElts == 4) {
4925 unsigned PFIndexes[4];
4926 for (unsigned i = 0; i != 4; ++i) {
4927 if (ShuffleMask[i] < 0)
4928 PFIndexes[i] = 8;
4929 else
4930 PFIndexes[i] = ShuffleMask[i];
4931 }
4932
4933 // Compute the index in the perfect shuffle table.
4934 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4935 PFIndexes[2] * 9 + PFIndexes[3];
4936 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4937 unsigned Cost = (PFEntry >> 30);
4938
4939 if (Cost <= 4)
4940 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4941 }
4942
4943 return GenerateTBL(Op, ShuffleMask, DAG);
4944}
4945
4946static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4947 APInt &UndefBits) {
4948 EVT VT = BVN->getValueType(0);
4949 APInt SplatBits, SplatUndef;
4950 unsigned SplatBitSize;
4951 bool HasAnyUndefs;
4952 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4953 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4954
4955 for (unsigned i = 0; i < NumSplats; ++i) {
4956 CnstBits <<= SplatBitSize;
4957 UndefBits <<= SplatBitSize;
4958 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4959 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4960 }
4961
4962 return true;
4963 }
4964
4965 return false;
4966}
4967
4968SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
4969 SelectionDAG &DAG) const {
4970 BuildVectorSDNode *BVN =
4971 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4972 SDValue LHS = Op.getOperand(0);
4973 SDLoc dl(Op);
4974 EVT VT = Op.getValueType();
4975
4976 if (!BVN)
4977 return Op;
4978
4979 APInt CnstBits(VT.getSizeInBits(), 0);
4980 APInt UndefBits(VT.getSizeInBits(), 0);
4981 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4982 // We only have BIC vector immediate instruction, which is and-not.
4983 CnstBits = ~CnstBits;
4984
4985 // We make use of a little bit of goto ickiness in order to avoid having to
4986 // duplicate the immediate matching logic for the undef toggled case.
4987 bool SecondTry = false;
4988 AttemptModImm:
4989
4990 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4991 CnstBits = CnstBits.zextOrTrunc(64);
4992 uint64_t CnstVal = CnstBits.getZExtValue();
4993
4994 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
4995 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
4996 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4997 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
4998 DAG.getConstant(CnstVal, MVT::i32),
4999 DAG.getConstant(0, MVT::i32));
5000 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5001 }
5002
5003 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5004 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5005 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5006 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5007 DAG.getConstant(CnstVal, MVT::i32),
5008 DAG.getConstant(8, MVT::i32));
5009 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5010 }
5011
5012 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5013 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5014 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5015 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5016 DAG.getConstant(CnstVal, MVT::i32),
5017 DAG.getConstant(16, MVT::i32));
5018 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5019 }
5020
5021 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5022 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5023 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5024 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5025 DAG.getConstant(CnstVal, MVT::i32),
5026 DAG.getConstant(24, MVT::i32));
5027 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5028 }
5029
5030 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5031 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5032 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5033 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5034 DAG.getConstant(CnstVal, MVT::i32),
5035 DAG.getConstant(0, MVT::i32));
5036 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5037 }
5038
5039 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5040 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5041 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5042 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5043 DAG.getConstant(CnstVal, MVT::i32),
5044 DAG.getConstant(8, MVT::i32));
5045 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5046 }
5047 }
5048
5049 if (SecondTry)
5050 goto FailedModImm;
5051 SecondTry = true;
5052 CnstBits = ~UndefBits;
5053 goto AttemptModImm;
5054 }
5055
5056// We can always fall back to a non-immediate AND.
5057FailedModImm:
5058 return Op;
5059}
5060
5061// Specialized code to quickly find if PotentialBVec is a BuildVector that
5062// consists of only the same constant int value, returned in reference arg
5063// ConstVal
5064static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5065 uint64_t &ConstVal) {
5066 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5067 if (!Bvec)
5068 return false;
5069 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5070 if (!FirstElt)
5071 return false;
5072 EVT VT = Bvec->getValueType(0);
5073 unsigned NumElts = VT.getVectorNumElements();
5074 for (unsigned i = 1; i < NumElts; ++i)
5075 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5076 return false;
5077 ConstVal = FirstElt->getZExtValue();
5078 return true;
5079}
5080
5081static unsigned getIntrinsicID(const SDNode *N) {
5082 unsigned Opcode = N->getOpcode();
5083 switch (Opcode) {
5084 default:
5085 return Intrinsic::not_intrinsic;
5086 case ISD::INTRINSIC_WO_CHAIN: {
5087 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5088 if (IID < Intrinsic::num_intrinsics)
5089 return IID;
5090 return Intrinsic::not_intrinsic;
5091 }
5092 }
5093}
5094
5095// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5096// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5097// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5098// Also, logical shift right -> sri, with the same structure.
5099static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5100 EVT VT = N->getValueType(0);
5101
5102 if (!VT.isVector())
5103 return SDValue();
5104
5105 SDLoc DL(N);
5106
5107 // Is the first op an AND?
5108 const SDValue And = N->getOperand(0);
5109 if (And.getOpcode() != ISD::AND)
5110 return SDValue();
5111
5112 // Is the second op an shl or lshr?
5113 SDValue Shift = N->getOperand(1);
5114 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5115 // or AArch64ISD::VLSHR vector, #shift
5116 unsigned ShiftOpc = Shift.getOpcode();
5117 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5118 return SDValue();
5119 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5120
5121 // Is the shift amount constant?
5122 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5123 if (!C2node)
5124 return SDValue();
5125
5126 // Is the and mask vector all constant?
5127 uint64_t C1;
5128 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5129 return SDValue();
5130
5131 // Is C1 == ~C2, taking into account how much one can shift elements of a
5132 // particular size?
5133 uint64_t C2 = C2node->getZExtValue();
5134 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5135 if (C2 > ElemSizeInBits)
5136 return SDValue();
5137 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5138 if ((C1 & ElemMask) != (~C2 & ElemMask))
5139 return SDValue();
5140
5141 SDValue X = And.getOperand(0);
5142 SDValue Y = Shift.getOperand(0);
5143
5144 unsigned Intrin =
5145 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5146 SDValue ResultSLI =
5147 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5148 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5149
5150 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5151 DEBUG(N->dump(&DAG));
5152 DEBUG(dbgs() << "into: \n");
5153 DEBUG(ResultSLI->dump(&DAG));
5154
5155 ++NumShiftInserts;
5156 return ResultSLI;
5157}
5158
5159SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5160 SelectionDAG &DAG) const {
5161 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5162 if (EnableAArch64SlrGeneration) {
5163 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5164 if (Res.getNode())
5165 return Res;
5166 }
5167
5168 BuildVectorSDNode *BVN =
5169 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5170 SDValue LHS = Op.getOperand(1);
5171 SDLoc dl(Op);
5172 EVT VT = Op.getValueType();
5173
5174 // OR commutes, so try swapping the operands.
5175 if (!BVN) {
5176 LHS = Op.getOperand(0);
5177 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5178 }
5179 if (!BVN)
5180 return Op;
5181
5182 APInt CnstBits(VT.getSizeInBits(), 0);
5183 APInt UndefBits(VT.getSizeInBits(), 0);
5184 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5185 // We make use of a little bit of goto ickiness in order to avoid having to
5186 // duplicate the immediate matching logic for the undef toggled case.
5187 bool SecondTry = false;
5188 AttemptModImm:
5189
5190 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5191 CnstBits = CnstBits.zextOrTrunc(64);
5192 uint64_t CnstVal = CnstBits.getZExtValue();
5193
5194 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5195 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5196 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5197 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5198 DAG.getConstant(CnstVal, MVT::i32),
5199 DAG.getConstant(0, MVT::i32));
5200 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5201 }
5202
5203 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5204 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5205 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5206 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5207 DAG.getConstant(CnstVal, MVT::i32),
5208 DAG.getConstant(8, MVT::i32));
5209 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5210 }
5211
5212 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5213 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5214 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5215 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5216 DAG.getConstant(CnstVal, MVT::i32),
5217 DAG.getConstant(16, MVT::i32));
5218 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5219 }
5220
5221 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5222 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5223 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5224 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5225 DAG.getConstant(CnstVal, MVT::i32),
5226 DAG.getConstant(24, MVT::i32));
5227 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5228 }
5229
5230 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5231 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5232 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5233 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5234 DAG.getConstant(CnstVal, MVT::i32),
5235 DAG.getConstant(0, MVT::i32));
5236 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5237 }
5238
5239 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5240 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5241 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5242 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5243 DAG.getConstant(CnstVal, MVT::i32),
5244 DAG.getConstant(8, MVT::i32));
5245 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5246 }
5247 }
5248
5249 if (SecondTry)
5250 goto FailedModImm;
5251 SecondTry = true;
5252 CnstBits = UndefBits;
5253 goto AttemptModImm;
5254 }
5255
5256// We can always fall back to a non-immediate OR.
5257FailedModImm:
5258 return Op;
5259}
5260
Kevin Qin4473c192014-07-07 02:45:40 +00005261// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5262// be truncated to fit element width.
5263static SDValue NormalizeBuildVector(SDValue Op,
5264 SelectionDAG &DAG) {
5265 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005266 SDLoc dl(Op);
5267 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005268 EVT EltTy= VT.getVectorElementType();
5269
5270 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5271 return Op;
5272
5273 SmallVector<SDValue, 16> Ops;
5274 for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5275 SDValue Lane = Op.getOperand(I);
5276 if (Lane.getOpcode() == ISD::Constant) {
5277 APInt LowBits(EltTy.getSizeInBits(),
5278 cast<ConstantSDNode>(Lane)->getZExtValue());
5279 Lane = DAG.getConstant(LowBits.getZExtValue(), MVT::i32);
5280 }
5281 Ops.push_back(Lane);
5282 }
5283 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5284}
5285
5286SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5287 SelectionDAG &DAG) const {
5288 SDLoc dl(Op);
5289 EVT VT = Op.getValueType();
5290 Op = NormalizeBuildVector(Op, DAG);
5291 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00005292
5293 APInt CnstBits(VT.getSizeInBits(), 0);
5294 APInt UndefBits(VT.getSizeInBits(), 0);
5295 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5296 // We make use of a little bit of goto ickiness in order to avoid having to
5297 // duplicate the immediate matching logic for the undef toggled case.
5298 bool SecondTry = false;
5299 AttemptModImm:
5300
5301 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5302 CnstBits = CnstBits.zextOrTrunc(64);
5303 uint64_t CnstVal = CnstBits.getZExtValue();
5304
5305 // Certain magic vector constants (used to express things like NOT
5306 // and NEG) are passed through unmodified. This allows codegen patterns
5307 // for these operations to match. Special-purpose patterns will lower
5308 // these immediates to MOVIs if it proves necessary.
5309 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5310 return Op;
5311
5312 // The many faces of MOVI...
5313 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5314 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5315 if (VT.getSizeInBits() == 128) {
5316 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5317 DAG.getConstant(CnstVal, MVT::i32));
5318 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5319 }
5320
5321 // Support the V64 version via subregister insertion.
5322 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5323 DAG.getConstant(CnstVal, MVT::i32));
5324 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5325 }
5326
5327 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5328 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5329 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5330 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5331 DAG.getConstant(CnstVal, MVT::i32),
5332 DAG.getConstant(0, MVT::i32));
5333 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5334 }
5335
5336 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5337 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5338 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5339 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5340 DAG.getConstant(CnstVal, MVT::i32),
5341 DAG.getConstant(8, MVT::i32));
5342 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5343 }
5344
5345 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5346 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5347 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5348 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5349 DAG.getConstant(CnstVal, MVT::i32),
5350 DAG.getConstant(16, MVT::i32));
5351 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5352 }
5353
5354 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5355 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5356 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5357 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5358 DAG.getConstant(CnstVal, MVT::i32),
5359 DAG.getConstant(24, MVT::i32));
5360 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5361 }
5362
5363 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5364 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5365 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5366 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5367 DAG.getConstant(CnstVal, MVT::i32),
5368 DAG.getConstant(0, MVT::i32));
5369 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5370 }
5371
5372 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5373 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5374 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5375 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5376 DAG.getConstant(CnstVal, MVT::i32),
5377 DAG.getConstant(8, MVT::i32));
5378 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5379 }
5380
5381 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5382 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5383 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5384 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5385 DAG.getConstant(CnstVal, MVT::i32),
5386 DAG.getConstant(264, MVT::i32));
5387 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5388 }
5389
5390 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5391 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5392 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5393 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5394 DAG.getConstant(CnstVal, MVT::i32),
5395 DAG.getConstant(272, MVT::i32));
5396 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5397 }
5398
5399 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5400 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5401 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5402 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
5403 DAG.getConstant(CnstVal, MVT::i32));
5404 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5405 }
5406
5407 // The few faces of FMOV...
5408 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5409 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5410 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5411 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
5412 DAG.getConstant(CnstVal, MVT::i32));
5413 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5414 }
5415
5416 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5417 VT.getSizeInBits() == 128) {
5418 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5419 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
5420 DAG.getConstant(CnstVal, MVT::i32));
5421 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5422 }
5423
5424 // The many faces of MVNI...
5425 CnstVal = ~CnstVal;
5426 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5427 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5428 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5429 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5430 DAG.getConstant(CnstVal, MVT::i32),
5431 DAG.getConstant(0, MVT::i32));
5432 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5433 }
5434
5435 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5436 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5437 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5438 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5439 DAG.getConstant(CnstVal, MVT::i32),
5440 DAG.getConstant(8, MVT::i32));
5441 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5442 }
5443
5444 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5445 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5446 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5447 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5448 DAG.getConstant(CnstVal, MVT::i32),
5449 DAG.getConstant(16, MVT::i32));
5450 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5451 }
5452
5453 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5454 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5455 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5456 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5457 DAG.getConstant(CnstVal, MVT::i32),
5458 DAG.getConstant(24, MVT::i32));
5459 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5460 }
5461
5462 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5463 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5464 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5465 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5466 DAG.getConstant(CnstVal, MVT::i32),
5467 DAG.getConstant(0, MVT::i32));
5468 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5469 }
5470
5471 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5472 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5473 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5474 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5475 DAG.getConstant(CnstVal, MVT::i32),
5476 DAG.getConstant(8, MVT::i32));
5477 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5478 }
5479
5480 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5481 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5482 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5483 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5484 DAG.getConstant(CnstVal, MVT::i32),
5485 DAG.getConstant(264, MVT::i32));
5486 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5487 }
5488
5489 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5490 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5491 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5492 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5493 DAG.getConstant(CnstVal, MVT::i32),
5494 DAG.getConstant(272, MVT::i32));
5495 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5496 }
5497 }
5498
5499 if (SecondTry)
5500 goto FailedModImm;
5501 SecondTry = true;
5502 CnstBits = UndefBits;
5503 goto AttemptModImm;
5504 }
5505FailedModImm:
5506
5507 // Scan through the operands to find some interesting properties we can
5508 // exploit:
5509 // 1) If only one value is used, we can use a DUP, or
5510 // 2) if only the low element is not undef, we can just insert that, or
5511 // 3) if only one constant value is used (w/ some non-constant lanes),
5512 // we can splat the constant value into the whole vector then fill
5513 // in the non-constant lanes.
5514 // 4) FIXME: If different constant values are used, but we can intelligently
5515 // select the values we'll be overwriting for the non-constant
5516 // lanes such that we can directly materialize the vector
5517 // some other way (MOVI, e.g.), we can be sneaky.
5518 unsigned NumElts = VT.getVectorNumElements();
5519 bool isOnlyLowElement = true;
5520 bool usesOnlyOneValue = true;
5521 bool usesOnlyOneConstantValue = true;
5522 bool isConstant = true;
5523 unsigned NumConstantLanes = 0;
5524 SDValue Value;
5525 SDValue ConstantValue;
5526 for (unsigned i = 0; i < NumElts; ++i) {
5527 SDValue V = Op.getOperand(i);
5528 if (V.getOpcode() == ISD::UNDEF)
5529 continue;
5530 if (i > 0)
5531 isOnlyLowElement = false;
5532 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5533 isConstant = false;
5534
5535 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5536 ++NumConstantLanes;
5537 if (!ConstantValue.getNode())
5538 ConstantValue = V;
5539 else if (ConstantValue != V)
5540 usesOnlyOneConstantValue = false;
5541 }
5542
5543 if (!Value.getNode())
5544 Value = V;
5545 else if (V != Value)
5546 usesOnlyOneValue = false;
5547 }
5548
5549 if (!Value.getNode())
5550 return DAG.getUNDEF(VT);
5551
5552 if (isOnlyLowElement)
5553 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5554
5555 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5556 // i32 and try again.
5557 if (usesOnlyOneValue) {
5558 if (!isConstant) {
5559 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5560 Value.getValueType() != VT)
5561 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5562
5563 // This is actually a DUPLANExx operation, which keeps everything vectory.
5564
5565 // DUPLANE works on 128-bit vectors, widen it if necessary.
5566 SDValue Lane = Value.getOperand(1);
5567 Value = Value.getOperand(0);
5568 if (Value.getValueType().getSizeInBits() == 64)
5569 Value = WidenVector(Value, DAG);
5570
5571 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5572 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5573 }
5574
5575 if (VT.getVectorElementType().isFloatingPoint()) {
5576 SmallVector<SDValue, 8> Ops;
5577 MVT NewType =
5578 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5579 for (unsigned i = 0; i < NumElts; ++i)
5580 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5581 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5582 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5583 Val = LowerBUILD_VECTOR(Val, DAG);
5584 if (Val.getNode())
5585 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5586 }
5587 }
5588
5589 // If there was only one constant value used and for more than one lane,
5590 // start by splatting that value, then replace the non-constant lanes. This
5591 // is better than the default, which will perform a separate initialization
5592 // for each lane.
5593 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5594 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
5595 // Now insert the non-constant lanes.
5596 for (unsigned i = 0; i < NumElts; ++i) {
5597 SDValue V = Op.getOperand(i);
5598 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5599 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5600 // Note that type legalization likely mucked about with the VT of the
5601 // source operand, so we may have to convert it here before inserting.
5602 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5603 }
5604 }
5605 return Val;
5606 }
5607
5608 // If all elements are constants and the case above didn't get hit, fall back
5609 // to the default expansion, which will generate a load from the constant
5610 // pool.
5611 if (isConstant)
5612 return SDValue();
5613
5614 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5615 if (NumElts >= 4) {
5616 SDValue shuffle = ReconstructShuffle(Op, DAG);
5617 if (shuffle != SDValue())
5618 return shuffle;
5619 }
5620
5621 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5622 // know the default expansion would otherwise fall back on something even
5623 // worse. For a vector with one or two non-undef values, that's
5624 // scalar_to_vector for the elements followed by a shuffle (provided the
5625 // shuffle is valid for the target) and materialization element by element
5626 // on the stack followed by a load for everything else.
5627 if (!isConstant && !usesOnlyOneValue) {
5628 SDValue Vec = DAG.getUNDEF(VT);
5629 SDValue Op0 = Op.getOperand(0);
5630 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5631 unsigned i = 0;
5632 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5633 // a) Avoid a RMW dependency on the full vector register, and
5634 // b) Allow the register coalescer to fold away the copy if the
5635 // value is already in an S or D register.
5636 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5637 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
5638 MachineSDNode *N =
5639 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5640 DAG.getTargetConstant(SubIdx, MVT::i32));
5641 Vec = SDValue(N, 0);
5642 ++i;
5643 }
5644 for (; i < NumElts; ++i) {
5645 SDValue V = Op.getOperand(i);
5646 if (V.getOpcode() == ISD::UNDEF)
5647 continue;
5648 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5649 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5650 }
5651 return Vec;
5652 }
5653
5654 // Just use the default expansion. We failed to find a better alternative.
5655 return SDValue();
5656}
5657
5658SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5659 SelectionDAG &DAG) const {
5660 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5661
Tim Northovere4b8e132014-07-15 10:00:26 +00005662 // Check for non-constant or out of range lane.
5663 EVT VT = Op.getOperand(0).getValueType();
5664 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
5665 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00005666 return SDValue();
5667
Tim Northover3b0846e2014-05-24 12:50:23 +00005668
5669 // Insertion/extraction are legal for V128 types.
5670 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5671 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5672 return Op;
5673
5674 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5675 VT != MVT::v1i64 && VT != MVT::v2f32)
5676 return SDValue();
5677
5678 // For V64 types, we perform insertion by expanding the value
5679 // to a V128 type and perform the insertion on that.
5680 SDLoc DL(Op);
5681 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5682 EVT WideTy = WideVec.getValueType();
5683
5684 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5685 Op.getOperand(1), Op.getOperand(2));
5686 // Re-narrow the resultant vector.
5687 return NarrowVector(Node, DAG);
5688}
5689
5690SDValue
5691AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5692 SelectionDAG &DAG) const {
5693 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5694
Tim Northovere4b8e132014-07-15 10:00:26 +00005695 // Check for non-constant or out of range lane.
5696 EVT VT = Op.getOperand(0).getValueType();
5697 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5698 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00005699 return SDValue();
5700
Tim Northover3b0846e2014-05-24 12:50:23 +00005701
5702 // Insertion/extraction are legal for V128 types.
5703 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5704 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5705 return Op;
5706
5707 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5708 VT != MVT::v1i64 && VT != MVT::v2f32)
5709 return SDValue();
5710
5711 // For V64 types, we perform extraction by expanding the value
5712 // to a V128 type and perform the extraction on that.
5713 SDLoc DL(Op);
5714 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5715 EVT WideTy = WideVec.getValueType();
5716
5717 EVT ExtrTy = WideTy.getVectorElementType();
5718 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5719 ExtrTy = MVT::i32;
5720
5721 // For extractions, we just return the result directly.
5722 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5723 Op.getOperand(1));
5724}
5725
5726SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5727 SelectionDAG &DAG) const {
5728 EVT VT = Op.getOperand(0).getValueType();
5729 SDLoc dl(Op);
5730 // Just in case...
5731 if (!VT.isVector())
5732 return SDValue();
5733
5734 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5735 if (!Cst)
5736 return SDValue();
5737 unsigned Val = Cst->getZExtValue();
5738
5739 unsigned Size = Op.getValueType().getSizeInBits();
5740 if (Val == 0) {
5741 switch (Size) {
5742 case 8:
5743 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
5744 Op.getOperand(0));
5745 case 16:
5746 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
5747 Op.getOperand(0));
5748 case 32:
5749 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
5750 Op.getOperand(0));
5751 case 64:
5752 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
5753 Op.getOperand(0));
5754 default:
5755 llvm_unreachable("Unexpected vector type in extract_subvector!");
5756 }
5757 }
5758 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5759 // that directly.
5760 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5761 return Op;
5762
5763 return SDValue();
5764}
5765
5766bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5767 EVT VT) const {
5768 if (VT.getVectorNumElements() == 4 &&
5769 (VT.is128BitVector() || VT.is64BitVector())) {
5770 unsigned PFIndexes[4];
5771 for (unsigned i = 0; i != 4; ++i) {
5772 if (M[i] < 0)
5773 PFIndexes[i] = 8;
5774 else
5775 PFIndexes[i] = M[i];
5776 }
5777
5778 // Compute the index in the perfect shuffle table.
5779 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5780 PFIndexes[2] * 9 + PFIndexes[3];
5781 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5782 unsigned Cost = (PFEntry >> 30);
5783
5784 if (Cost <= 4)
5785 return true;
5786 }
5787
5788 bool DummyBool;
5789 int DummyInt;
5790 unsigned DummyUnsigned;
5791
5792 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5793 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5794 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5795 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5796 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5797 isZIPMask(M, VT, DummyUnsigned) ||
5798 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5799 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5800 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5801 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5802 isConcatMask(M, VT, VT.getSizeInBits() == 128));
5803}
5804
5805/// getVShiftImm - Check if this is a valid build_vector for the immediate
5806/// operand of a vector shift operation, where all the elements of the
5807/// build_vector must have the same constant integer value.
5808static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5809 // Ignore bit_converts.
5810 while (Op.getOpcode() == ISD::BITCAST)
5811 Op = Op.getOperand(0);
5812 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5813 APInt SplatBits, SplatUndef;
5814 unsigned SplatBitSize;
5815 bool HasAnyUndefs;
5816 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5817 HasAnyUndefs, ElementBits) ||
5818 SplatBitSize > ElementBits)
5819 return false;
5820 Cnt = SplatBits.getSExtValue();
5821 return true;
5822}
5823
5824/// isVShiftLImm - Check if this is a valid build_vector for the immediate
5825/// operand of a vector shift left operation. That value must be in the range:
5826/// 0 <= Value < ElementBits for a left shift; or
5827/// 0 <= Value <= ElementBits for a long left shift.
5828static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5829 assert(VT.isVector() && "vector shift count is not a vector type");
5830 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5831 if (!getVShiftImm(Op, ElementBits, Cnt))
5832 return false;
5833 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5834}
5835
5836/// isVShiftRImm - Check if this is a valid build_vector for the immediate
5837/// operand of a vector shift right operation. For a shift opcode, the value
5838/// is positive, but for an intrinsic the value count must be negative. The
5839/// absolute value must be in the range:
5840/// 1 <= |Value| <= ElementBits for a right shift; or
5841/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5842static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5843 int64_t &Cnt) {
5844 assert(VT.isVector() && "vector shift count is not a vector type");
5845 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5846 if (!getVShiftImm(Op, ElementBits, Cnt))
5847 return false;
5848 if (isIntrinsic)
5849 Cnt = -Cnt;
5850 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5851}
5852
5853SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5854 SelectionDAG &DAG) const {
5855 EVT VT = Op.getValueType();
5856 SDLoc DL(Op);
5857 int64_t Cnt;
5858
5859 if (!Op.getOperand(1).getValueType().isVector())
5860 return Op;
5861 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5862
5863 switch (Op.getOpcode()) {
5864 default:
5865 llvm_unreachable("unexpected shift opcode");
5866
5867 case ISD::SHL:
5868 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5869 return DAG.getNode(AArch64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5870 DAG.getConstant(Cnt, MVT::i32));
5871 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5872 DAG.getConstant(Intrinsic::aarch64_neon_ushl, MVT::i32),
5873 Op.getOperand(0), Op.getOperand(1));
5874 case ISD::SRA:
5875 case ISD::SRL:
5876 // Right shift immediate
5877 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5878 Cnt < EltSize) {
5879 unsigned Opc =
5880 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
5881 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5882 DAG.getConstant(Cnt, MVT::i32));
5883 }
5884
5885 // Right shift register. Note, there is not a shift right register
5886 // instruction, but the shift left register instruction takes a signed
5887 // value, where negative numbers specify a right shift.
5888 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
5889 : Intrinsic::aarch64_neon_ushl;
5890 // negate the shift amount
5891 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
5892 SDValue NegShiftLeft =
5893 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5894 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5895 return NegShiftLeft;
5896 }
5897
5898 return SDValue();
5899}
5900
5901static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5902 AArch64CC::CondCode CC, bool NoNans, EVT VT,
5903 SDLoc dl, SelectionDAG &DAG) {
5904 EVT SrcVT = LHS.getValueType();
5905
5906 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5907 APInt CnstBits(VT.getSizeInBits(), 0);
5908 APInt UndefBits(VT.getSizeInBits(), 0);
5909 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5910 bool IsZero = IsCnst && (CnstBits == 0);
5911
5912 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5913 switch (CC) {
5914 default:
5915 return SDValue();
5916 case AArch64CC::NE: {
5917 SDValue Fcmeq;
5918 if (IsZero)
5919 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
5920 else
5921 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
5922 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
5923 }
5924 case AArch64CC::EQ:
5925 if (IsZero)
5926 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
5927 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
5928 case AArch64CC::GE:
5929 if (IsZero)
5930 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
5931 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
5932 case AArch64CC::GT:
5933 if (IsZero)
5934 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
5935 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
5936 case AArch64CC::LS:
5937 if (IsZero)
5938 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
5939 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
5940 case AArch64CC::LT:
5941 if (!NoNans)
5942 return SDValue();
5943 // If we ignore NaNs then we can use to the MI implementation.
5944 // Fallthrough.
5945 case AArch64CC::MI:
5946 if (IsZero)
5947 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
5948 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
5949 }
5950 }
5951
5952 switch (CC) {
5953 default:
5954 return SDValue();
5955 case AArch64CC::NE: {
5956 SDValue Cmeq;
5957 if (IsZero)
5958 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
5959 else
5960 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
5961 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
5962 }
5963 case AArch64CC::EQ:
5964 if (IsZero)
5965 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
5966 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
5967 case AArch64CC::GE:
5968 if (IsZero)
5969 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
5970 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
5971 case AArch64CC::GT:
5972 if (IsZero)
5973 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
5974 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
5975 case AArch64CC::LE:
5976 if (IsZero)
5977 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
5978 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
5979 case AArch64CC::LS:
5980 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
5981 case AArch64CC::LO:
5982 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
5983 case AArch64CC::LT:
5984 if (IsZero)
5985 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
5986 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
5987 case AArch64CC::HI:
5988 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
5989 case AArch64CC::HS:
5990 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
5991 }
5992}
5993
5994SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
5995 SelectionDAG &DAG) const {
5996 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5997 SDValue LHS = Op.getOperand(0);
5998 SDValue RHS = Op.getOperand(1);
5999 SDLoc dl(Op);
6000
6001 if (LHS.getValueType().getVectorElementType().isInteger()) {
6002 assert(LHS.getValueType() == RHS.getValueType());
6003 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6004 return EmitVectorComparison(LHS, RHS, AArch64CC, false, Op.getValueType(),
6005 dl, DAG);
6006 }
6007
6008 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6009 LHS.getValueType().getVectorElementType() == MVT::f64);
6010
6011 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6012 // clean. Some of them require two branches to implement.
6013 AArch64CC::CondCode CC1, CC2;
6014 bool ShouldInvert;
6015 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6016
6017 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6018 SDValue Cmp =
6019 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
6020 if (!Cmp.getNode())
6021 return SDValue();
6022
6023 if (CC2 != AArch64CC::AL) {
6024 SDValue Cmp2 =
6025 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
6026 if (!Cmp2.getNode())
6027 return SDValue();
6028
6029 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
6030 }
6031
6032 if (ShouldInvert)
6033 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6034
6035 return Cmp;
6036}
6037
6038/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6039/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6040/// specified in the intrinsic calls.
6041bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6042 const CallInst &I,
6043 unsigned Intrinsic) const {
6044 switch (Intrinsic) {
6045 case Intrinsic::aarch64_neon_ld2:
6046 case Intrinsic::aarch64_neon_ld3:
6047 case Intrinsic::aarch64_neon_ld4:
6048 case Intrinsic::aarch64_neon_ld1x2:
6049 case Intrinsic::aarch64_neon_ld1x3:
6050 case Intrinsic::aarch64_neon_ld1x4:
6051 case Intrinsic::aarch64_neon_ld2lane:
6052 case Intrinsic::aarch64_neon_ld3lane:
6053 case Intrinsic::aarch64_neon_ld4lane:
6054 case Intrinsic::aarch64_neon_ld2r:
6055 case Intrinsic::aarch64_neon_ld3r:
6056 case Intrinsic::aarch64_neon_ld4r: {
6057 Info.opc = ISD::INTRINSIC_W_CHAIN;
6058 // Conservatively set memVT to the entire set of vectors loaded.
6059 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6060 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6061 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6062 Info.offset = 0;
6063 Info.align = 0;
6064 Info.vol = false; // volatile loads with NEON intrinsics not supported
6065 Info.readMem = true;
6066 Info.writeMem = false;
6067 return true;
6068 }
6069 case Intrinsic::aarch64_neon_st2:
6070 case Intrinsic::aarch64_neon_st3:
6071 case Intrinsic::aarch64_neon_st4:
6072 case Intrinsic::aarch64_neon_st1x2:
6073 case Intrinsic::aarch64_neon_st1x3:
6074 case Intrinsic::aarch64_neon_st1x4:
6075 case Intrinsic::aarch64_neon_st2lane:
6076 case Intrinsic::aarch64_neon_st3lane:
6077 case Intrinsic::aarch64_neon_st4lane: {
6078 Info.opc = ISD::INTRINSIC_VOID;
6079 // Conservatively set memVT to the entire set of vectors stored.
6080 unsigned NumElts = 0;
6081 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6082 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6083 if (!ArgTy->isVectorTy())
6084 break;
6085 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6086 }
6087 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6088 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6089 Info.offset = 0;
6090 Info.align = 0;
6091 Info.vol = false; // volatile stores with NEON intrinsics not supported
6092 Info.readMem = false;
6093 Info.writeMem = true;
6094 return true;
6095 }
6096 case Intrinsic::aarch64_ldaxr:
6097 case Intrinsic::aarch64_ldxr: {
6098 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6099 Info.opc = ISD::INTRINSIC_W_CHAIN;
6100 Info.memVT = MVT::getVT(PtrTy->getElementType());
6101 Info.ptrVal = I.getArgOperand(0);
6102 Info.offset = 0;
6103 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6104 Info.vol = true;
6105 Info.readMem = true;
6106 Info.writeMem = false;
6107 return true;
6108 }
6109 case Intrinsic::aarch64_stlxr:
6110 case Intrinsic::aarch64_stxr: {
6111 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6112 Info.opc = ISD::INTRINSIC_W_CHAIN;
6113 Info.memVT = MVT::getVT(PtrTy->getElementType());
6114 Info.ptrVal = I.getArgOperand(1);
6115 Info.offset = 0;
6116 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6117 Info.vol = true;
6118 Info.readMem = false;
6119 Info.writeMem = true;
6120 return true;
6121 }
6122 case Intrinsic::aarch64_ldaxp:
6123 case Intrinsic::aarch64_ldxp: {
6124 Info.opc = ISD::INTRINSIC_W_CHAIN;
6125 Info.memVT = MVT::i128;
6126 Info.ptrVal = I.getArgOperand(0);
6127 Info.offset = 0;
6128 Info.align = 16;
6129 Info.vol = true;
6130 Info.readMem = true;
6131 Info.writeMem = false;
6132 return true;
6133 }
6134 case Intrinsic::aarch64_stlxp:
6135 case Intrinsic::aarch64_stxp: {
6136 Info.opc = ISD::INTRINSIC_W_CHAIN;
6137 Info.memVT = MVT::i128;
6138 Info.ptrVal = I.getArgOperand(2);
6139 Info.offset = 0;
6140 Info.align = 16;
6141 Info.vol = true;
6142 Info.readMem = false;
6143 Info.writeMem = true;
6144 return true;
6145 }
6146 default:
6147 break;
6148 }
6149
6150 return false;
6151}
6152
6153// Truncations from 64-bit GPR to 32-bit GPR is free.
6154bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6155 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6156 return false;
6157 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6158 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006159 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006160}
6161bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006162 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006163 return false;
6164 unsigned NumBits1 = VT1.getSizeInBits();
6165 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006166 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006167}
6168
6169// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6170// 64-bit GPR.
6171bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6172 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6173 return false;
6174 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6175 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006176 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006177}
6178bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006179 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006180 return false;
6181 unsigned NumBits1 = VT1.getSizeInBits();
6182 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006183 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006184}
6185
6186bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6187 EVT VT1 = Val.getValueType();
6188 if (isZExtFree(VT1, VT2)) {
6189 return true;
6190 }
6191
6192 if (Val.getOpcode() != ISD::LOAD)
6193 return false;
6194
6195 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006196 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6197 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6198 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006199}
6200
6201bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6202 unsigned &RequiredAligment) const {
6203 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6204 return false;
6205 // Cyclone supports unaligned accesses.
6206 RequiredAligment = 0;
6207 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6208 return NumBits == 32 || NumBits == 64;
6209}
6210
6211bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6212 unsigned &RequiredAligment) const {
6213 if (!LoadedType.isSimple() ||
6214 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6215 return false;
6216 // Cyclone supports unaligned accesses.
6217 RequiredAligment = 0;
6218 unsigned NumBits = LoadedType.getSizeInBits();
6219 return NumBits == 32 || NumBits == 64;
6220}
6221
6222static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6223 unsigned AlignCheck) {
6224 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6225 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6226}
6227
6228EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6229 unsigned SrcAlign, bool IsMemset,
6230 bool ZeroMemset,
6231 bool MemcpyStrSrc,
6232 MachineFunction &MF) const {
6233 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6234 // instruction to materialize the v2i64 zero and one store (with restrictive
6235 // addressing mode). Just do two i64 store of zero-registers.
6236 bool Fast;
6237 const Function *F = MF.getFunction();
6238 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
6239 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
6240 Attribute::NoImplicitFloat) &&
6241 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00006242 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00006243 return MVT::f128;
6244
6245 return Size >= 8 ? MVT::i64 : MVT::i32;
6246}
6247
6248// 12-bit optionally shifted immediates are legal for adds.
6249bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6250 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6251 return true;
6252 return false;
6253}
6254
6255// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6256// immediates is the same as for an add or a sub.
6257bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6258 if (Immed < 0)
6259 Immed *= -1;
6260 return isLegalAddImmediate(Immed);
6261}
6262
6263/// isLegalAddressingMode - Return true if the addressing mode represented
6264/// by AM is legal for this target, for a load/store of the specified type.
6265bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6266 Type *Ty) const {
6267 // AArch64 has five basic addressing modes:
6268 // reg
6269 // reg + 9-bit signed offset
6270 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6271 // reg1 + reg2
6272 // reg + SIZE_IN_BYTES * reg
6273
6274 // No global is ever allowed as a base.
6275 if (AM.BaseGV)
6276 return false;
6277
6278 // No reg+reg+imm addressing.
6279 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6280 return false;
6281
6282 // check reg + imm case:
6283 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6284 uint64_t NumBytes = 0;
6285 if (Ty->isSized()) {
6286 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6287 NumBytes = NumBits / 8;
6288 if (!isPowerOf2_64(NumBits))
6289 NumBytes = 0;
6290 }
6291
6292 if (!AM.Scale) {
6293 int64_t Offset = AM.BaseOffs;
6294
6295 // 9-bit signed offset
6296 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6297 return true;
6298
6299 // 12-bit unsigned offset
6300 unsigned shift = Log2_64(NumBytes);
6301 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6302 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6303 (Offset >> shift) << shift == Offset)
6304 return true;
6305 return false;
6306 }
6307
6308 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6309
6310 if (!AM.Scale || AM.Scale == 1 ||
6311 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6312 return true;
6313 return false;
6314}
6315
6316int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6317 Type *Ty) const {
6318 // Scaling factors are not free at all.
6319 // Operands | Rt Latency
6320 // -------------------------------------------
6321 // Rt, [Xn, Xm] | 4
6322 // -------------------------------------------
6323 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6324 // Rt, [Xn, Wm, <extend> #imm] |
6325 if (isLegalAddressingMode(AM, Ty))
6326 // Scale represents reg2 * scale, thus account for 1 if
6327 // it is not equal to 0 or 1.
6328 return AM.Scale != 0 && AM.Scale != 1;
6329 return -1;
6330}
6331
6332bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6333 VT = VT.getScalarType();
6334
6335 if (!VT.isSimple())
6336 return false;
6337
6338 switch (VT.getSimpleVT().SimpleTy) {
6339 case MVT::f32:
6340 case MVT::f64:
6341 return true;
6342 default:
6343 break;
6344 }
6345
6346 return false;
6347}
6348
6349const MCPhysReg *
6350AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6351 // LR is a callee-save register, but we must treat it as clobbered by any call
6352 // site. Hence we include LR in the scratch registers, which are in turn added
6353 // as implicit-defs for stackmaps and patchpoints.
6354 static const MCPhysReg ScratchRegs[] = {
6355 AArch64::X16, AArch64::X17, AArch64::LR, 0
6356 };
6357 return ScratchRegs;
6358}
6359
6360bool
6361AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6362 EVT VT = N->getValueType(0);
6363 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6364 // it with shift to let it be lowered to UBFX.
6365 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6366 isa<ConstantSDNode>(N->getOperand(1))) {
6367 uint64_t TruncMask = N->getConstantOperandVal(1);
6368 if (isMask_64(TruncMask) &&
6369 N->getOperand(0).getOpcode() == ISD::SRL &&
6370 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6371 return false;
6372 }
6373 return true;
6374}
6375
6376bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6377 Type *Ty) const {
6378 assert(Ty->isIntegerTy());
6379
6380 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6381 if (BitSize == 0)
6382 return false;
6383
6384 int64_t Val = Imm.getSExtValue();
6385 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6386 return true;
6387
6388 if ((int64_t)Val < 0)
6389 Val = ~Val;
6390 if (BitSize == 32)
6391 Val &= (1LL << 32) - 1;
6392
6393 unsigned LZ = countLeadingZeros((uint64_t)Val);
6394 unsigned Shift = (63 - LZ) / 16;
6395 // MOVZ is free so return true for one or fewer MOVK.
6396 return (Shift < 3) ? true : false;
6397}
6398
6399// Generate SUBS and CSEL for integer abs.
6400static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6401 EVT VT = N->getValueType(0);
6402
6403 SDValue N0 = N->getOperand(0);
6404 SDValue N1 = N->getOperand(1);
6405 SDLoc DL(N);
6406
6407 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6408 // and change it to SUB and CSEL.
6409 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6410 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6411 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6412 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6413 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6414 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6415 N0.getOperand(0));
6416 // Generate SUBS & CSEL.
6417 SDValue Cmp =
6418 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6419 N0.getOperand(0), DAG.getConstant(0, VT));
6420 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6421 DAG.getConstant(AArch64CC::PL, MVT::i32),
6422 SDValue(Cmp.getNode(), 1));
6423 }
6424 return SDValue();
6425}
6426
6427// performXorCombine - Attempts to handle integer ABS.
6428static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6429 TargetLowering::DAGCombinerInfo &DCI,
6430 const AArch64Subtarget *Subtarget) {
6431 if (DCI.isBeforeLegalizeOps())
6432 return SDValue();
6433
6434 return performIntegerAbsCombine(N, DAG);
6435}
6436
Chad Rosier17020f92014-07-23 14:57:52 +00006437SDValue
6438AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6439 SelectionDAG &DAG,
6440 std::vector<SDNode *> *Created) const {
6441 // fold (sdiv X, pow2)
6442 EVT VT = N->getValueType(0);
6443 if ((VT != MVT::i32 && VT != MVT::i64) ||
6444 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6445 return SDValue();
6446
6447 SDLoc DL(N);
6448 SDValue N0 = N->getOperand(0);
6449 unsigned Lg2 = Divisor.countTrailingZeros();
6450 SDValue Zero = DAG.getConstant(0, VT);
6451 SDValue Pow2MinusOne = DAG.getConstant((1 << Lg2) - 1, VT);
6452
6453 // Add (N0 < 0) ? Pow2 - 1 : 0;
6454 SDValue CCVal;
6455 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6456 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6457 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6458
6459 if (Created) {
6460 Created->push_back(Cmp.getNode());
6461 Created->push_back(Add.getNode());
6462 Created->push_back(CSel.getNode());
6463 }
6464
6465 // Divide by pow2.
6466 SDValue SRA =
6467 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, MVT::i64));
6468
6469 // If we're dividing by a positive value, we're done. Otherwise, we must
6470 // negate the result.
6471 if (Divisor.isNonNegative())
6472 return SRA;
6473
6474 if (Created)
6475 Created->push_back(SRA.getNode());
6476 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), SRA);
6477}
6478
Tim Northover3b0846e2014-05-24 12:50:23 +00006479static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6480 TargetLowering::DAGCombinerInfo &DCI,
6481 const AArch64Subtarget *Subtarget) {
6482 if (DCI.isBeforeLegalizeOps())
6483 return SDValue();
6484
6485 // Multiplication of a power of two plus/minus one can be done more
6486 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6487 // future CPUs have a cheaper MADD instruction, this may need to be
6488 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6489 // 64-bit is 5 cycles, so this is always a win.
6490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6491 APInt Value = C->getAPIntValue();
6492 EVT VT = N->getValueType(0);
Chad Rosiere6b87612014-06-30 14:51:14 +00006493 if (Value.isNonNegative()) {
6494 // (mul x, 2^N + 1) => (add (shl x, N), x)
6495 APInt VM1 = Value - 1;
6496 if (VM1.isPowerOf2()) {
6497 SDValue ShiftedVal =
6498 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6499 DAG.getConstant(VM1.logBase2(), MVT::i64));
6500 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal,
6501 N->getOperand(0));
6502 }
6503 // (mul x, 2^N - 1) => (sub (shl x, N), x)
6504 APInt VP1 = Value + 1;
6505 if (VP1.isPowerOf2()) {
6506 SDValue ShiftedVal =
6507 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6508 DAG.getConstant(VP1.logBase2(), MVT::i64));
6509 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal,
6510 N->getOperand(0));
6511 }
6512 } else {
6513 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6514 APInt VNM1 = -Value - 1;
6515 if (VNM1.isPowerOf2()) {
6516 SDValue ShiftedVal =
6517 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6518 DAG.getConstant(VNM1.logBase2(), MVT::i64));
6519 SDValue Add =
6520 DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6521 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), Add);
6522 }
6523 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6524 APInt VNP1 = -Value + 1;
6525 if (VNP1.isPowerOf2()) {
6526 SDValue ShiftedVal =
6527 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6528 DAG.getConstant(VNP1.logBase2(), MVT::i64));
6529 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N->getOperand(0),
6530 ShiftedVal);
6531 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00006532 }
Tim Northover3b0846e2014-05-24 12:50:23 +00006533 }
6534 return SDValue();
6535}
6536
Jim Grosbachf7502c42014-07-18 00:40:52 +00006537static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
6538 SelectionDAG &DAG) {
6539 // Take advantage of vector comparisons producing 0 or -1 in each lane to
6540 // optimize away operation when it's from a constant.
6541 //
6542 // The general transformation is:
6543 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
6544 // AND(VECTOR_CMP(x,y), constant2)
6545 // constant2 = UNARYOP(constant)
6546
Jim Grosbach8f6f0852014-07-23 20:41:38 +00006547 // Early exit if this isn't a vector operation, the operand of the
6548 // unary operation isn't a bitwise AND, or if the sizes of the operations
6549 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00006550 EVT VT = N->getValueType(0);
6551 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00006552 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
6553 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00006554 return SDValue();
6555
Jim Grosbach724e4382014-07-23 20:41:43 +00006556 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00006557 // make the transformation for non-constant splats as well, but it's unclear
6558 // that would be a benefit as it would not eliminate any operations, just
6559 // perform one more step in scalar code before moving to the vector unit.
6560 if (BuildVectorSDNode *BV =
6561 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00006562 // Bail out if the vector isn't a constant.
6563 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00006564 return SDValue();
6565
6566 // Everything checks out. Build up the new and improved node.
6567 SDLoc DL(N);
6568 EVT IntVT = BV->getValueType(0);
6569 // Create a new constant of the appropriate type for the transformed
6570 // DAG.
6571 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
6572 // The AND node needs bitcasts to/from an integer vector type around it.
6573 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
6574 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
6575 N->getOperand(0)->getOperand(0), MaskConst);
6576 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
6577 return Res;
6578 }
6579
6580 return SDValue();
6581}
6582
Tim Northover3b0846e2014-05-24 12:50:23 +00006583static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00006584 // First try to optimize away the conversion when it's conditionally from
6585 // a constant. Vectors only.
6586 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
6587 if (Res != SDValue())
6588 return Res;
6589
Tim Northover3b0846e2014-05-24 12:50:23 +00006590 EVT VT = N->getValueType(0);
6591 if (VT != MVT::f32 && VT != MVT::f64)
6592 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00006593
Tim Northover3b0846e2014-05-24 12:50:23 +00006594 // Only optimize when the source and destination types have the same width.
6595 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6596 return SDValue();
6597
6598 // If the result of an integer load is only used by an integer-to-float
6599 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6600 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6601 SDValue N0 = N->getOperand(0);
6602 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6603 // Do not change the width of a volatile load.
6604 !cast<LoadSDNode>(N0)->isVolatile()) {
6605 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6606 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6607 LN0->getPointerInfo(), LN0->isVolatile(),
6608 LN0->isNonTemporal(), LN0->isInvariant(),
6609 LN0->getAlignment());
6610
6611 // Make sure successors of the original load stay after it by updating them
6612 // to use the new Chain.
6613 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6614
6615 unsigned Opcode =
6616 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
6617 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6618 }
6619
6620 return SDValue();
6621}
6622
6623/// An EXTR instruction is made up of two shifts, ORed together. This helper
6624/// searches for and classifies those shifts.
6625static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6626 bool &FromHi) {
6627 if (N.getOpcode() == ISD::SHL)
6628 FromHi = false;
6629 else if (N.getOpcode() == ISD::SRL)
6630 FromHi = true;
6631 else
6632 return false;
6633
6634 if (!isa<ConstantSDNode>(N.getOperand(1)))
6635 return false;
6636
6637 ShiftAmount = N->getConstantOperandVal(1);
6638 Src = N->getOperand(0);
6639 return true;
6640}
6641
6642/// EXTR instruction extracts a contiguous chunk of bits from two existing
6643/// registers viewed as a high/low pair. This function looks for the pattern:
6644/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6645/// EXTR. Can't quite be done in TableGen because the two immediates aren't
6646/// independent.
6647static SDValue tryCombineToEXTR(SDNode *N,
6648 TargetLowering::DAGCombinerInfo &DCI) {
6649 SelectionDAG &DAG = DCI.DAG;
6650 SDLoc DL(N);
6651 EVT VT = N->getValueType(0);
6652
6653 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6654
6655 if (VT != MVT::i32 && VT != MVT::i64)
6656 return SDValue();
6657
6658 SDValue LHS;
6659 uint32_t ShiftLHS = 0;
6660 bool LHSFromHi = 0;
6661 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6662 return SDValue();
6663
6664 SDValue RHS;
6665 uint32_t ShiftRHS = 0;
6666 bool RHSFromHi = 0;
6667 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6668 return SDValue();
6669
6670 // If they're both trying to come from the high part of the register, they're
6671 // not really an EXTR.
6672 if (LHSFromHi == RHSFromHi)
6673 return SDValue();
6674
6675 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6676 return SDValue();
6677
6678 if (LHSFromHi) {
6679 std::swap(LHS, RHS);
6680 std::swap(ShiftLHS, ShiftRHS);
6681 }
6682
6683 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
6684 DAG.getConstant(ShiftRHS, MVT::i64));
6685}
6686
6687static SDValue tryCombineToBSL(SDNode *N,
6688 TargetLowering::DAGCombinerInfo &DCI) {
6689 EVT VT = N->getValueType(0);
6690 SelectionDAG &DAG = DCI.DAG;
6691 SDLoc DL(N);
6692
6693 if (!VT.isVector())
6694 return SDValue();
6695
6696 SDValue N0 = N->getOperand(0);
6697 if (N0.getOpcode() != ISD::AND)
6698 return SDValue();
6699
6700 SDValue N1 = N->getOperand(1);
6701 if (N1.getOpcode() != ISD::AND)
6702 return SDValue();
6703
6704 // We only have to look for constant vectors here since the general, variable
6705 // case can be handled in TableGen.
6706 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6707 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6708 for (int i = 1; i >= 0; --i)
6709 for (int j = 1; j >= 0; --j) {
6710 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6711 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6712 if (!BVN0 || !BVN1)
6713 continue;
6714
6715 bool FoundMatch = true;
6716 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6717 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6718 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6719 if (!CN0 || !CN1 ||
6720 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6721 FoundMatch = false;
6722 break;
6723 }
6724 }
6725
6726 if (FoundMatch)
6727 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6728 N0->getOperand(1 - i), N1->getOperand(1 - j));
6729 }
6730
6731 return SDValue();
6732}
6733
6734static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6735 const AArch64Subtarget *Subtarget) {
6736 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6737 if (!EnableAArch64ExtrGeneration)
6738 return SDValue();
6739 SelectionDAG &DAG = DCI.DAG;
6740 EVT VT = N->getValueType(0);
6741
6742 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6743 return SDValue();
6744
6745 SDValue Res = tryCombineToEXTR(N, DCI);
6746 if (Res.getNode())
6747 return Res;
6748
6749 Res = tryCombineToBSL(N, DCI);
6750 if (Res.getNode())
6751 return Res;
6752
6753 return SDValue();
6754}
6755
6756static SDValue performBitcastCombine(SDNode *N,
6757 TargetLowering::DAGCombinerInfo &DCI,
6758 SelectionDAG &DAG) {
6759 // Wait 'til after everything is legalized to try this. That way we have
6760 // legal vector types and such.
6761 if (DCI.isBeforeLegalizeOps())
6762 return SDValue();
6763
6764 // Remove extraneous bitcasts around an extract_subvector.
6765 // For example,
6766 // (v4i16 (bitconvert
6767 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6768 // becomes
6769 // (extract_subvector ((v8i16 ...), (i64 4)))
6770
6771 // Only interested in 64-bit vectors as the ultimate result.
6772 EVT VT = N->getValueType(0);
6773 if (!VT.isVector())
6774 return SDValue();
6775 if (VT.getSimpleVT().getSizeInBits() != 64)
6776 return SDValue();
6777 // Is the operand an extract_subvector starting at the beginning or halfway
6778 // point of the vector? A low half may also come through as an
6779 // EXTRACT_SUBREG, so look for that, too.
6780 SDValue Op0 = N->getOperand(0);
6781 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6782 !(Op0->isMachineOpcode() &&
6783 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
6784 return SDValue();
6785 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6786 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6787 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6788 return SDValue();
6789 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
6790 if (idx != AArch64::dsub)
6791 return SDValue();
6792 // The dsub reference is equivalent to a lane zero subvector reference.
6793 idx = 0;
6794 }
6795 // Look through the bitcast of the input to the extract.
6796 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6797 return SDValue();
6798 SDValue Source = Op0->getOperand(0)->getOperand(0);
6799 // If the source type has twice the number of elements as our destination
6800 // type, we know this is an extract of the high or low half of the vector.
6801 EVT SVT = Source->getValueType(0);
6802 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6803 return SDValue();
6804
6805 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
6806
6807 // Create the simplified form to just extract the low or high half of the
6808 // vector directly rather than bothering with the bitcasts.
6809 SDLoc dl(N);
6810 unsigned NumElements = VT.getVectorNumElements();
6811 if (idx) {
6812 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6813 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6814 } else {
6815 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, MVT::i32);
6816 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6817 Source, SubReg),
6818 0);
6819 }
6820}
6821
6822static SDValue performConcatVectorsCombine(SDNode *N,
6823 TargetLowering::DAGCombinerInfo &DCI,
6824 SelectionDAG &DAG) {
6825 // Wait 'til after everything is legalized to try this. That way we have
6826 // legal vector types and such.
6827 if (DCI.isBeforeLegalizeOps())
6828 return SDValue();
6829
6830 SDLoc dl(N);
6831 EVT VT = N->getValueType(0);
6832
6833 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6834 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6835 // canonicalise to that.
6836 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6837 assert(VT.getVectorElementType().getSizeInBits() == 64);
6838 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT,
6839 WidenVector(N->getOperand(0), DAG),
6840 DAG.getConstant(0, MVT::i64));
6841 }
6842
6843 // Canonicalise concat_vectors so that the right-hand vector has as few
6844 // bit-casts as possible before its real operation. The primary matching
6845 // destination for these operations will be the narrowing "2" instructions,
6846 // which depend on the operation being performed on this right-hand vector.
6847 // For example,
6848 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6849 // becomes
6850 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6851
6852 SDValue Op1 = N->getOperand(1);
6853 if (Op1->getOpcode() != ISD::BITCAST)
6854 return SDValue();
6855 SDValue RHS = Op1->getOperand(0);
6856 MVT RHSTy = RHS.getValueType().getSimpleVT();
6857 // If the RHS is not a vector, this is not the pattern we're looking for.
6858 if (!RHSTy.isVector())
6859 return SDValue();
6860
6861 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
6862
6863 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6864 RHSTy.getVectorNumElements() * 2);
6865 return DAG.getNode(
6866 ISD::BITCAST, dl, VT,
6867 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6868 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6869}
6870
6871static SDValue tryCombineFixedPointConvert(SDNode *N,
6872 TargetLowering::DAGCombinerInfo &DCI,
6873 SelectionDAG &DAG) {
6874 // Wait 'til after everything is legalized to try this. That way we have
6875 // legal vector types and such.
6876 if (DCI.isBeforeLegalizeOps())
6877 return SDValue();
6878 // Transform a scalar conversion of a value from a lane extract into a
6879 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6880 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6881 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6882 //
6883 // The second form interacts better with instruction selection and the
6884 // register allocator to avoid cross-class register copies that aren't
6885 // coalescable due to a lane reference.
6886
6887 // Check the operand and see if it originates from a lane extract.
6888 SDValue Op1 = N->getOperand(1);
6889 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6890 // Yep, no additional predication needed. Perform the transform.
6891 SDValue IID = N->getOperand(0);
6892 SDValue Shift = N->getOperand(2);
6893 SDValue Vec = Op1.getOperand(0);
6894 SDValue Lane = Op1.getOperand(1);
6895 EVT ResTy = N->getValueType(0);
6896 EVT VecResTy;
6897 SDLoc DL(N);
6898
6899 // The vector width should be 128 bits by the time we get here, even
6900 // if it started as 64 bits (the extract_vector handling will have
6901 // done so).
6902 assert(Vec.getValueType().getSizeInBits() == 128 &&
6903 "unexpected vector size on extract_vector_elt!");
6904 if (Vec.getValueType() == MVT::v4i32)
6905 VecResTy = MVT::v4f32;
6906 else if (Vec.getValueType() == MVT::v2i64)
6907 VecResTy = MVT::v2f64;
6908 else
Craig Topper2a30d782014-06-18 05:05:13 +00006909 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006910
6911 SDValue Convert =
6912 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6913 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6914 }
6915 return SDValue();
6916}
6917
6918// AArch64 high-vector "long" operations are formed by performing the non-high
6919// version on an extract_subvector of each operand which gets the high half:
6920//
6921// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6922//
6923// However, there are cases which don't have an extract_high explicitly, but
6924// have another operation that can be made compatible with one for free. For
6925// example:
6926//
6927// (dupv64 scalar) --> (extract_high (dup128 scalar))
6928//
6929// This routine does the actual conversion of such DUPs, once outer routines
6930// have determined that everything else is in order.
6931static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6932 // We can handle most types of duplicate, but the lane ones have an extra
6933 // operand saying *which* lane, so we need to know.
6934 bool IsDUPLANE;
6935 switch (N.getOpcode()) {
6936 case AArch64ISD::DUP:
6937 IsDUPLANE = false;
6938 break;
6939 case AArch64ISD::DUPLANE8:
6940 case AArch64ISD::DUPLANE16:
6941 case AArch64ISD::DUPLANE32:
6942 case AArch64ISD::DUPLANE64:
6943 IsDUPLANE = true;
6944 break;
6945 default:
6946 return SDValue();
6947 }
6948
6949 MVT NarrowTy = N.getSimpleValueType();
6950 if (!NarrowTy.is64BitVector())
6951 return SDValue();
6952
6953 MVT ElementTy = NarrowTy.getVectorElementType();
6954 unsigned NumElems = NarrowTy.getVectorNumElements();
6955 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6956
6957 SDValue NewDUP;
6958 if (IsDUPLANE)
6959 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6960 N.getOperand(1));
6961 else
6962 NewDUP = DAG.getNode(AArch64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6963
6964 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6965 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6966}
6967
6968static bool isEssentiallyExtractSubvector(SDValue N) {
6969 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6970 return true;
6971
6972 return N.getOpcode() == ISD::BITCAST &&
6973 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6974}
6975
6976/// \brief Helper structure to keep track of ISD::SET_CC operands.
6977struct GenericSetCCInfo {
6978 const SDValue *Opnd0;
6979 const SDValue *Opnd1;
6980 ISD::CondCode CC;
6981};
6982
6983/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
6984struct AArch64SetCCInfo {
6985 const SDValue *Cmp;
6986 AArch64CC::CondCode CC;
6987};
6988
6989/// \brief Helper structure to keep track of SetCC information.
6990union SetCCInfo {
6991 GenericSetCCInfo Generic;
6992 AArch64SetCCInfo AArch64;
6993};
6994
6995/// \brief Helper structure to be able to read SetCC information. If set to
6996/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
6997/// GenericSetCCInfo.
6998struct SetCCInfoAndKind {
6999 SetCCInfo Info;
7000 bool IsAArch64;
7001};
7002
7003/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7004/// an
7005/// AArch64 lowered one.
7006/// \p SetCCInfo is filled accordingly.
7007/// \post SetCCInfo is meanginfull only when this function returns true.
7008/// \return True when Op is a kind of SET_CC operation.
7009static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7010 // If this is a setcc, this is straight forward.
7011 if (Op.getOpcode() == ISD::SETCC) {
7012 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7013 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7014 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7015 SetCCInfo.IsAArch64 = false;
7016 return true;
7017 }
7018 // Otherwise, check if this is a matching csel instruction.
7019 // In other words:
7020 // - csel 1, 0, cc
7021 // - csel 0, 1, !cc
7022 if (Op.getOpcode() != AArch64ISD::CSEL)
7023 return false;
7024 // Set the information about the operands.
7025 // TODO: we want the operands of the Cmp not the csel
7026 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7027 SetCCInfo.IsAArch64 = true;
7028 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7029 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7030
7031 // Check that the operands matches the constraints:
7032 // (1) Both operands must be constants.
7033 // (2) One must be 1 and the other must be 0.
7034 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7035 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7036
7037 // Check (1).
7038 if (!TValue || !FValue)
7039 return false;
7040
7041 // Check (2).
7042 if (!TValue->isOne()) {
7043 // Update the comparison when we are interested in !cc.
7044 std::swap(TValue, FValue);
7045 SetCCInfo.Info.AArch64.CC =
7046 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7047 }
7048 return TValue->isOne() && FValue->isNullValue();
7049}
7050
7051// Returns true if Op is setcc or zext of setcc.
7052static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7053 if (isSetCC(Op, Info))
7054 return true;
7055 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7056 isSetCC(Op->getOperand(0), Info));
7057}
7058
7059// The folding we want to perform is:
7060// (add x, [zext] (setcc cc ...) )
7061// -->
7062// (csel x, (add x, 1), !cc ...)
7063//
7064// The latter will get matched to a CSINC instruction.
7065static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7066 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7067 SDValue LHS = Op->getOperand(0);
7068 SDValue RHS = Op->getOperand(1);
7069 SetCCInfoAndKind InfoAndKind;
7070
7071 // If neither operand is a SET_CC, give up.
7072 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7073 std::swap(LHS, RHS);
7074 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7075 return SDValue();
7076 }
7077
7078 // FIXME: This could be generatized to work for FP comparisons.
7079 EVT CmpVT = InfoAndKind.IsAArch64
7080 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7081 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7082 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7083 return SDValue();
7084
7085 SDValue CCVal;
7086 SDValue Cmp;
7087 SDLoc dl(Op);
7088 if (InfoAndKind.IsAArch64) {
7089 CCVal = DAG.getConstant(
7090 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), MVT::i32);
7091 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7092 } else
7093 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7094 *InfoAndKind.Info.Generic.Opnd1,
7095 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7096 CCVal, DAG, dl);
7097
7098 EVT VT = Op->getValueType(0);
7099 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
7100 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7101}
7102
7103// The basic add/sub long vector instructions have variants with "2" on the end
7104// which act on the high-half of their inputs. They are normally matched by
7105// patterns like:
7106//
7107// (add (zeroext (extract_high LHS)),
7108// (zeroext (extract_high RHS)))
7109// -> uaddl2 vD, vN, vM
7110//
7111// However, if one of the extracts is something like a duplicate, this
7112// instruction can still be used profitably. This function puts the DAG into a
7113// more appropriate form for those patterns to trigger.
7114static SDValue performAddSubLongCombine(SDNode *N,
7115 TargetLowering::DAGCombinerInfo &DCI,
7116 SelectionDAG &DAG) {
7117 if (DCI.isBeforeLegalizeOps())
7118 return SDValue();
7119
7120 MVT VT = N->getSimpleValueType(0);
7121 if (!VT.is128BitVector()) {
7122 if (N->getOpcode() == ISD::ADD)
7123 return performSetccAddFolding(N, DAG);
7124 return SDValue();
7125 }
7126
7127 // Make sure both branches are extended in the same way.
7128 SDValue LHS = N->getOperand(0);
7129 SDValue RHS = N->getOperand(1);
7130 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7131 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7132 LHS.getOpcode() != RHS.getOpcode())
7133 return SDValue();
7134
7135 unsigned ExtType = LHS.getOpcode();
7136
7137 // It's not worth doing if at least one of the inputs isn't already an
7138 // extract, but we don't know which it'll be so we have to try both.
7139 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7140 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7141 if (!RHS.getNode())
7142 return SDValue();
7143
7144 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7145 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7146 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7147 if (!LHS.getNode())
7148 return SDValue();
7149
7150 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7151 }
7152
7153 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7154}
7155
7156// Massage DAGs which we can use the high-half "long" operations on into
7157// something isel will recognize better. E.g.
7158//
7159// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7160// (aarch64_neon_umull (extract_high (v2i64 vec)))
7161// (extract_high (v2i64 (dup128 scalar)))))
7162//
7163static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7164 TargetLowering::DAGCombinerInfo &DCI,
7165 SelectionDAG &DAG) {
7166 if (DCI.isBeforeLegalizeOps())
7167 return SDValue();
7168
7169 SDValue LHS = N->getOperand(1);
7170 SDValue RHS = N->getOperand(2);
7171 assert(LHS.getValueType().is64BitVector() &&
7172 RHS.getValueType().is64BitVector() &&
7173 "unexpected shape for long operation");
7174
7175 // Either node could be a DUP, but it's not worth doing both of them (you'd
7176 // just as well use the non-high version) so look for a corresponding extract
7177 // operation on the other "wing".
7178 if (isEssentiallyExtractSubvector(LHS)) {
7179 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7180 if (!RHS.getNode())
7181 return SDValue();
7182 } else if (isEssentiallyExtractSubvector(RHS)) {
7183 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7184 if (!LHS.getNode())
7185 return SDValue();
7186 }
7187
7188 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7189 N->getOperand(0), LHS, RHS);
7190}
7191
7192static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7193 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7194 unsigned ElemBits = ElemTy.getSizeInBits();
7195
7196 int64_t ShiftAmount;
7197 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7198 APInt SplatValue, SplatUndef;
7199 unsigned SplatBitSize;
7200 bool HasAnyUndefs;
7201 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7202 HasAnyUndefs, ElemBits) ||
7203 SplatBitSize != ElemBits)
7204 return SDValue();
7205
7206 ShiftAmount = SplatValue.getSExtValue();
7207 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7208 ShiftAmount = CVN->getSExtValue();
7209 } else
7210 return SDValue();
7211
7212 unsigned Opcode;
7213 bool IsRightShift;
7214 switch (IID) {
7215 default:
7216 llvm_unreachable("Unknown shift intrinsic");
7217 case Intrinsic::aarch64_neon_sqshl:
7218 Opcode = AArch64ISD::SQSHL_I;
7219 IsRightShift = false;
7220 break;
7221 case Intrinsic::aarch64_neon_uqshl:
7222 Opcode = AArch64ISD::UQSHL_I;
7223 IsRightShift = false;
7224 break;
7225 case Intrinsic::aarch64_neon_srshl:
7226 Opcode = AArch64ISD::SRSHR_I;
7227 IsRightShift = true;
7228 break;
7229 case Intrinsic::aarch64_neon_urshl:
7230 Opcode = AArch64ISD::URSHR_I;
7231 IsRightShift = true;
7232 break;
7233 case Intrinsic::aarch64_neon_sqshlu:
7234 Opcode = AArch64ISD::SQSHLU_I;
7235 IsRightShift = false;
7236 break;
7237 }
7238
7239 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
7240 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7241 DAG.getConstant(-ShiftAmount, MVT::i32));
James Molloy1e3b5a42014-06-16 10:39:21 +00007242 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits)
Tim Northover3b0846e2014-05-24 12:50:23 +00007243 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7244 DAG.getConstant(ShiftAmount, MVT::i32));
7245
7246 return SDValue();
7247}
7248
7249// The CRC32[BH] instructions ignore the high bits of their data operand. Since
7250// the intrinsics must be legal and take an i32, this means there's almost
7251// certainly going to be a zext in the DAG which we can eliminate.
7252static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7253 SDValue AndN = N->getOperand(2);
7254 if (AndN.getOpcode() != ISD::AND)
7255 return SDValue();
7256
7257 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7258 if (!CMask || CMask->getZExtValue() != Mask)
7259 return SDValue();
7260
7261 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7262 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7263}
7264
7265static SDValue performIntrinsicCombine(SDNode *N,
7266 TargetLowering::DAGCombinerInfo &DCI,
7267 const AArch64Subtarget *Subtarget) {
7268 SelectionDAG &DAG = DCI.DAG;
7269 unsigned IID = getIntrinsicID(N);
7270 switch (IID) {
7271 default:
7272 break;
7273 case Intrinsic::aarch64_neon_vcvtfxs2fp:
7274 case Intrinsic::aarch64_neon_vcvtfxu2fp:
7275 return tryCombineFixedPointConvert(N, DCI, DAG);
7276 break;
7277 case Intrinsic::aarch64_neon_fmax:
7278 return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7279 N->getOperand(1), N->getOperand(2));
7280 case Intrinsic::aarch64_neon_fmin:
7281 return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7282 N->getOperand(1), N->getOperand(2));
7283 case Intrinsic::aarch64_neon_smull:
7284 case Intrinsic::aarch64_neon_umull:
7285 case Intrinsic::aarch64_neon_pmull:
7286 case Intrinsic::aarch64_neon_sqdmull:
7287 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7288 case Intrinsic::aarch64_neon_sqshl:
7289 case Intrinsic::aarch64_neon_uqshl:
7290 case Intrinsic::aarch64_neon_sqshlu:
7291 case Intrinsic::aarch64_neon_srshl:
7292 case Intrinsic::aarch64_neon_urshl:
7293 return tryCombineShiftImm(IID, N, DAG);
7294 case Intrinsic::aarch64_crc32b:
7295 case Intrinsic::aarch64_crc32cb:
7296 return tryCombineCRC32(0xff, N, DAG);
7297 case Intrinsic::aarch64_crc32h:
7298 case Intrinsic::aarch64_crc32ch:
7299 return tryCombineCRC32(0xffff, N, DAG);
7300 }
7301 return SDValue();
7302}
7303
7304static SDValue performExtendCombine(SDNode *N,
7305 TargetLowering::DAGCombinerInfo &DCI,
7306 SelectionDAG &DAG) {
7307 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7308 // we can convert that DUP into another extract_high (of a bigger DUP), which
7309 // helps the backend to decide that an sabdl2 would be useful, saving a real
7310 // extract_high operation.
7311 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7312 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7313 SDNode *ABDNode = N->getOperand(0).getNode();
7314 unsigned IID = getIntrinsicID(ABDNode);
7315 if (IID == Intrinsic::aarch64_neon_sabd ||
7316 IID == Intrinsic::aarch64_neon_uabd) {
7317 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7318 if (!NewABD.getNode())
7319 return SDValue();
7320
7321 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7322 NewABD);
7323 }
7324 }
7325
7326 // This is effectively a custom type legalization for AArch64.
7327 //
7328 // Type legalization will split an extend of a small, legal, type to a larger
7329 // illegal type by first splitting the destination type, often creating
7330 // illegal source types, which then get legalized in isel-confusing ways,
7331 // leading to really terrible codegen. E.g.,
7332 // %result = v8i32 sext v8i8 %value
7333 // becomes
7334 // %losrc = extract_subreg %value, ...
7335 // %hisrc = extract_subreg %value, ...
7336 // %lo = v4i32 sext v4i8 %losrc
7337 // %hi = v4i32 sext v4i8 %hisrc
7338 // Things go rapidly downhill from there.
7339 //
7340 // For AArch64, the [sz]ext vector instructions can only go up one element
7341 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7342 // take two instructions.
7343 //
7344 // This implies that the most efficient way to do the extend from v8i8
7345 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7346 // the normal splitting to happen for the v8i16->v8i32.
7347
7348 // This is pre-legalization to catch some cases where the default
7349 // type legalization will create ill-tempered code.
7350 if (!DCI.isBeforeLegalizeOps())
7351 return SDValue();
7352
7353 // We're only interested in cleaning things up for non-legal vector types
7354 // here. If both the source and destination are legal, things will just
7355 // work naturally without any fiddling.
7356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7357 EVT ResVT = N->getValueType(0);
7358 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7359 return SDValue();
7360 // If the vector type isn't a simple VT, it's beyond the scope of what
7361 // we're worried about here. Let legalization do its thing and hope for
7362 // the best.
7363 if (!ResVT.isSimple())
7364 return SDValue();
7365
7366 SDValue Src = N->getOperand(0);
7367 MVT SrcVT = Src->getValueType(0).getSimpleVT();
7368 // If the source VT is a 64-bit vector, we can play games and get the
7369 // better results we want.
7370 if (SrcVT.getSizeInBits() != 64)
7371 return SDValue();
7372
7373 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7374 unsigned ElementCount = SrcVT.getVectorNumElements();
7375 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7376 SDLoc DL(N);
7377 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7378
7379 // Now split the rest of the operation into two halves, each with a 64
7380 // bit source.
7381 EVT LoVT, HiVT;
7382 SDValue Lo, Hi;
7383 unsigned NumElements = ResVT.getVectorNumElements();
7384 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7385 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7386 ResVT.getVectorElementType(), NumElements / 2);
7387
7388 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7389 LoVT.getVectorNumElements());
7390 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7391 DAG.getIntPtrConstant(0));
7392 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7393 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
7394 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7395 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7396
7397 // Now combine the parts back together so we still have a single result
7398 // like the combiner expects.
7399 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7400}
7401
7402/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7403/// value. The load store optimizer pass will merge them to store pair stores.
7404/// This has better performance than a splat of the scalar followed by a split
7405/// vector store. Even if the stores are not merged it is four stores vs a dup,
7406/// followed by an ext.b and two stores.
7407static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7408 SDValue StVal = St->getValue();
7409 EVT VT = StVal.getValueType();
7410
7411 // Don't replace floating point stores, they possibly won't be transformed to
7412 // stp because of the store pair suppress pass.
7413 if (VT.isFloatingPoint())
7414 return SDValue();
7415
7416 // Check for insert vector elements.
7417 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7418 return SDValue();
7419
7420 // We can express a splat as store pair(s) for 2 or 4 elements.
7421 unsigned NumVecElts = VT.getVectorNumElements();
7422 if (NumVecElts != 4 && NumVecElts != 2)
7423 return SDValue();
7424 SDValue SplatVal = StVal.getOperand(1);
7425 unsigned RemainInsertElts = NumVecElts - 1;
7426
7427 // Check that this is a splat.
7428 while (--RemainInsertElts) {
7429 SDValue NextInsertElt = StVal.getOperand(0);
7430 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7431 return SDValue();
7432 if (NextInsertElt.getOperand(1) != SplatVal)
7433 return SDValue();
7434 StVal = NextInsertElt;
7435 }
7436 unsigned OrigAlignment = St->getAlignment();
7437 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7438 unsigned Alignment = std::min(OrigAlignment, EltOffset);
7439
7440 // Create scalar stores. This is at least as good as the code sequence for a
7441 // split unaligned store wich is a dup.s, ext.b, and two stores.
7442 // Most of the time the three stores should be replaced by store pair
7443 // instructions (stp).
7444 SDLoc DL(St);
7445 SDValue BasePtr = St->getBasePtr();
7446 SDValue NewST1 =
7447 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7448 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7449
7450 unsigned Offset = EltOffset;
7451 while (--NumVecElts) {
7452 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7453 DAG.getConstant(Offset, MVT::i64));
7454 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7455 St->getPointerInfo(), St->isVolatile(),
7456 St->isNonTemporal(), Alignment);
7457 Offset += EltOffset;
7458 }
7459 return NewST1;
7460}
7461
7462static SDValue performSTORECombine(SDNode *N,
7463 TargetLowering::DAGCombinerInfo &DCI,
7464 SelectionDAG &DAG,
7465 const AArch64Subtarget *Subtarget) {
7466 if (!DCI.isBeforeLegalize())
7467 return SDValue();
7468
7469 StoreSDNode *S = cast<StoreSDNode>(N);
7470 if (S->isVolatile())
7471 return SDValue();
7472
7473 // Cyclone has bad performance on unaligned 16B stores when crossing line and
7474 // page boundries. We want to split such stores.
7475 if (!Subtarget->isCyclone())
7476 return SDValue();
7477
7478 // Don't split at Oz.
7479 MachineFunction &MF = DAG.getMachineFunction();
7480 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7481 AttributeSet::FunctionIndex, Attribute::MinSize);
7482 if (IsMinSize)
7483 return SDValue();
7484
7485 SDValue StVal = S->getValue();
7486 EVT VT = StVal.getValueType();
7487
7488 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7489 // those up regresses performance on micro-benchmarks and olden/bh.
7490 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7491 return SDValue();
7492
7493 // Split unaligned 16B stores. They are terrible for performance.
7494 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7495 // extensions can use this to mark that it does not want splitting to happen
7496 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7497 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7498 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7499 S->getAlignment() <= 2)
7500 return SDValue();
7501
7502 // If we get a splat of a scalar convert this vector store to a store of
7503 // scalars. They will be merged into store pairs thereby removing two
7504 // instructions.
7505 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7506 if (ReplacedSplat != SDValue())
7507 return ReplacedSplat;
7508
7509 SDLoc DL(S);
7510 unsigned NumElts = VT.getVectorNumElements() / 2;
7511 // Split VT into two.
7512 EVT HalfVT =
7513 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7514 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7515 DAG.getIntPtrConstant(0));
7516 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7517 DAG.getIntPtrConstant(NumElts));
7518 SDValue BasePtr = S->getBasePtr();
7519 SDValue NewST1 =
7520 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7521 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7522 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7523 DAG.getConstant(8, MVT::i64));
7524 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7525 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7526 S->getAlignment());
7527}
7528
7529/// Target-specific DAG combine function for post-increment LD1 (lane) and
7530/// post-increment LD1R.
7531static SDValue performPostLD1Combine(SDNode *N,
7532 TargetLowering::DAGCombinerInfo &DCI,
7533 bool IsLaneOp) {
7534 if (DCI.isBeforeLegalizeOps())
7535 return SDValue();
7536
7537 SelectionDAG &DAG = DCI.DAG;
7538 EVT VT = N->getValueType(0);
7539
7540 unsigned LoadIdx = IsLaneOp ? 1 : 0;
7541 SDNode *LD = N->getOperand(LoadIdx).getNode();
7542 // If it is not LOAD, can not do such combine.
7543 if (LD->getOpcode() != ISD::LOAD)
7544 return SDValue();
7545
7546 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
7547 EVT MemVT = LoadSDN->getMemoryVT();
7548 // Check if memory operand is the same type as the vector element.
7549 if (MemVT != VT.getVectorElementType())
7550 return SDValue();
7551
7552 // Check if there are other uses. If so, do not combine as it will introduce
7553 // an extra load.
7554 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
7555 ++UI) {
7556 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
7557 continue;
7558 if (*UI != N)
7559 return SDValue();
7560 }
7561
7562 SDValue Addr = LD->getOperand(1);
7563 SDValue Vector = N->getOperand(0);
7564 // Search for a use of the address operand that is an increment.
7565 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
7566 Addr.getNode()->use_end(); UI != UE; ++UI) {
7567 SDNode *User = *UI;
7568 if (User->getOpcode() != ISD::ADD
7569 || UI.getUse().getResNo() != Addr.getResNo())
7570 continue;
7571
7572 // Check that the add is independent of the load. Otherwise, folding it
7573 // would create a cycle.
7574 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
7575 continue;
7576 // Also check that add is not used in the vector operand. This would also
7577 // create a cycle.
7578 if (User->isPredecessorOf(Vector.getNode()))
7579 continue;
7580
7581 // If the increment is a constant, it must match the memory ref size.
7582 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7583 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7584 uint32_t IncVal = CInc->getZExtValue();
7585 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
7586 if (IncVal != NumBytes)
7587 continue;
7588 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7589 }
7590
7591 SmallVector<SDValue, 8> Ops;
7592 Ops.push_back(LD->getOperand(0)); // Chain
7593 if (IsLaneOp) {
7594 Ops.push_back(Vector); // The vector to be inserted
7595 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
7596 }
7597 Ops.push_back(Addr);
7598 Ops.push_back(Inc);
7599
7600 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
7601 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, 3));
7602 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
7603 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
7604 MemVT,
7605 LoadSDN->getMemOperand());
7606
7607 // Update the uses.
7608 std::vector<SDValue> NewResults;
7609 NewResults.push_back(SDValue(LD, 0)); // The result of load
7610 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
7611 DCI.CombineTo(LD, NewResults);
7612 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
7613 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
7614
7615 break;
7616 }
7617 return SDValue();
7618}
7619
7620/// Target-specific DAG combine function for NEON load/store intrinsics
7621/// to merge base address updates.
7622static SDValue performNEONPostLDSTCombine(SDNode *N,
7623 TargetLowering::DAGCombinerInfo &DCI,
7624 SelectionDAG &DAG) {
7625 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7626 return SDValue();
7627
7628 unsigned AddrOpIdx = N->getNumOperands() - 1;
7629 SDValue Addr = N->getOperand(AddrOpIdx);
7630
7631 // Search for a use of the address operand that is an increment.
7632 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7633 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7634 SDNode *User = *UI;
7635 if (User->getOpcode() != ISD::ADD ||
7636 UI.getUse().getResNo() != Addr.getResNo())
7637 continue;
7638
7639 // Check that the add is independent of the load/store. Otherwise, folding
7640 // it would create a cycle.
7641 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7642 continue;
7643
7644 // Find the new opcode for the updating load/store.
7645 bool IsStore = false;
7646 bool IsLaneOp = false;
7647 bool IsDupOp = false;
7648 unsigned NewOpc = 0;
7649 unsigned NumVecs = 0;
7650 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7651 switch (IntNo) {
7652 default: llvm_unreachable("unexpected intrinsic for Neon base update");
7653 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
7654 NumVecs = 2; break;
7655 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
7656 NumVecs = 3; break;
7657 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
7658 NumVecs = 4; break;
7659 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
7660 NumVecs = 2; IsStore = true; break;
7661 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
7662 NumVecs = 3; IsStore = true; break;
7663 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
7664 NumVecs = 4; IsStore = true; break;
7665 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
7666 NumVecs = 2; break;
7667 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
7668 NumVecs = 3; break;
7669 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
7670 NumVecs = 4; break;
7671 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
7672 NumVecs = 2; IsStore = true; break;
7673 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
7674 NumVecs = 3; IsStore = true; break;
7675 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
7676 NumVecs = 4; IsStore = true; break;
7677 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
7678 NumVecs = 2; IsDupOp = true; break;
7679 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
7680 NumVecs = 3; IsDupOp = true; break;
7681 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
7682 NumVecs = 4; IsDupOp = true; break;
7683 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
7684 NumVecs = 2; IsLaneOp = true; break;
7685 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
7686 NumVecs = 3; IsLaneOp = true; break;
7687 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
7688 NumVecs = 4; IsLaneOp = true; break;
7689 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
7690 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
7691 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
7692 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
7693 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
7694 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
7695 }
7696
7697 EVT VecTy;
7698 if (IsStore)
7699 VecTy = N->getOperand(2).getValueType();
7700 else
7701 VecTy = N->getValueType(0);
7702
7703 // If the increment is a constant, it must match the memory ref size.
7704 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7705 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7706 uint32_t IncVal = CInc->getZExtValue();
7707 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7708 if (IsLaneOp || IsDupOp)
7709 NumBytes /= VecTy.getVectorNumElements();
7710 if (IncVal != NumBytes)
7711 continue;
7712 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7713 }
7714 SmallVector<SDValue, 8> Ops;
7715 Ops.push_back(N->getOperand(0)); // Incoming chain
7716 // Load lane and store have vector list as input.
7717 if (IsLaneOp || IsStore)
7718 for (unsigned i = 2; i < AddrOpIdx; ++i)
7719 Ops.push_back(N->getOperand(i));
7720 Ops.push_back(Addr); // Base register
7721 Ops.push_back(Inc);
7722
7723 // Return Types.
7724 EVT Tys[6];
7725 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
7726 unsigned n;
7727 for (n = 0; n < NumResultVecs; ++n)
7728 Tys[n] = VecTy;
7729 Tys[n++] = MVT::i64; // Type of write back register
7730 Tys[n] = MVT::Other; // Type of the chain
7731 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs + 2));
7732
7733 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7734 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
7735 MemInt->getMemoryVT(),
7736 MemInt->getMemOperand());
7737
7738 // Update the uses.
7739 std::vector<SDValue> NewResults;
7740 for (unsigned i = 0; i < NumResultVecs; ++i) {
7741 NewResults.push_back(SDValue(UpdN.getNode(), i));
7742 }
7743 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
7744 DCI.CombineTo(N, NewResults);
7745 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7746
7747 break;
7748 }
7749 return SDValue();
7750}
7751
7752// Optimize compare with zero and branch.
7753static SDValue performBRCONDCombine(SDNode *N,
7754 TargetLowering::DAGCombinerInfo &DCI,
7755 SelectionDAG &DAG) {
7756 SDValue Chain = N->getOperand(0);
7757 SDValue Dest = N->getOperand(1);
7758 SDValue CCVal = N->getOperand(2);
7759 SDValue Cmp = N->getOperand(3);
7760
7761 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7762 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7763 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
7764 return SDValue();
7765
7766 unsigned CmpOpc = Cmp.getOpcode();
7767 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
7768 return SDValue();
7769
7770 // Only attempt folding if there is only one use of the flag and no use of the
7771 // value.
7772 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7773 return SDValue();
7774
7775 SDValue LHS = Cmp.getOperand(0);
7776 SDValue RHS = Cmp.getOperand(1);
7777
7778 assert(LHS.getValueType() == RHS.getValueType() &&
7779 "Expected the value type to be the same for both operands!");
7780 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7781 return SDValue();
7782
7783 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7784 std::swap(LHS, RHS);
7785
7786 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7787 return SDValue();
7788
7789 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7790 LHS.getOpcode() == ISD::SRL)
7791 return SDValue();
7792
7793 // Fold the compare into the branch instruction.
7794 SDValue BR;
7795 if (CC == AArch64CC::EQ)
7796 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7797 else
7798 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7799
7800 // Do not add new nodes to DAG combiner worklist.
7801 DCI.CombineTo(N, BR, false);
7802
7803 return SDValue();
7804}
7805
7806// vselect (v1i1 setcc) ->
7807// vselect (v1iXX setcc) (XX is the size of the compared operand type)
7808// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7809// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7810// such VSELECT.
7811static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7812 SDValue N0 = N->getOperand(0);
7813 EVT CCVT = N0.getValueType();
7814
7815 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7816 CCVT.getVectorElementType() != MVT::i1)
7817 return SDValue();
7818
7819 EVT ResVT = N->getValueType(0);
7820 EVT CmpVT = N0.getOperand(0).getValueType();
7821 // Only combine when the result type is of the same size as the compared
7822 // operands.
7823 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7824 return SDValue();
7825
7826 SDValue IfTrue = N->getOperand(1);
7827 SDValue IfFalse = N->getOperand(2);
7828 SDValue SetCC =
7829 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7830 N0.getOperand(0), N0.getOperand(1),
7831 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7832 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7833 IfTrue, IfFalse);
7834}
7835
7836/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
7837/// the compare-mask instructions rather than going via NZCV, even if LHS and
7838/// RHS are really scalar. This replaces any scalar setcc in the above pattern
7839/// with a vector one followed by a DUP shuffle on the result.
7840static SDValue performSelectCombine(SDNode *N, SelectionDAG &DAG) {
7841 SDValue N0 = N->getOperand(0);
7842 EVT ResVT = N->getValueType(0);
7843
7844 if (!N->getOperand(1).getValueType().isVector())
7845 return SDValue();
7846
7847 if (N0.getOpcode() != ISD::SETCC || N0.getValueType() != MVT::i1)
7848 return SDValue();
7849
7850 SDLoc DL(N0);
7851
7852 EVT SrcVT = N0.getOperand(0).getValueType();
7853 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT,
7854 ResVT.getSizeInBits() / SrcVT.getSizeInBits());
7855 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
7856
7857 // First perform a vector comparison, where lane 0 is the one we're interested
7858 // in.
7859 SDValue LHS =
7860 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
7861 SDValue RHS =
7862 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
7863 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
7864
7865 // Now duplicate the comparison mask we want across all other lanes.
7866 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
7867 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
7868 Mask = DAG.getNode(ISD::BITCAST, DL, ResVT.changeVectorElementTypeToInteger(),
7869 Mask);
7870
7871 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
7872}
7873
7874SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
7875 DAGCombinerInfo &DCI) const {
7876 SelectionDAG &DAG = DCI.DAG;
7877 switch (N->getOpcode()) {
7878 default:
7879 break;
7880 case ISD::ADD:
7881 case ISD::SUB:
7882 return performAddSubLongCombine(N, DCI, DAG);
7883 case ISD::XOR:
7884 return performXorCombine(N, DAG, DCI, Subtarget);
7885 case ISD::MUL:
7886 return performMulCombine(N, DAG, DCI, Subtarget);
7887 case ISD::SINT_TO_FP:
7888 case ISD::UINT_TO_FP:
7889 return performIntToFpCombine(N, DAG);
7890 case ISD::OR:
7891 return performORCombine(N, DCI, Subtarget);
7892 case ISD::INTRINSIC_WO_CHAIN:
7893 return performIntrinsicCombine(N, DCI, Subtarget);
7894 case ISD::ANY_EXTEND:
7895 case ISD::ZERO_EXTEND:
7896 case ISD::SIGN_EXTEND:
7897 return performExtendCombine(N, DCI, DAG);
7898 case ISD::BITCAST:
7899 return performBitcastCombine(N, DCI, DAG);
7900 case ISD::CONCAT_VECTORS:
7901 return performConcatVectorsCombine(N, DCI, DAG);
7902 case ISD::SELECT:
7903 return performSelectCombine(N, DAG);
7904 case ISD::VSELECT:
7905 return performVSelectCombine(N, DCI.DAG);
7906 case ISD::STORE:
7907 return performSTORECombine(N, DCI, DAG, Subtarget);
7908 case AArch64ISD::BRCOND:
7909 return performBRCONDCombine(N, DCI, DAG);
7910 case AArch64ISD::DUP:
7911 return performPostLD1Combine(N, DCI, false);
7912 case ISD::INSERT_VECTOR_ELT:
7913 return performPostLD1Combine(N, DCI, true);
7914 case ISD::INTRINSIC_VOID:
7915 case ISD::INTRINSIC_W_CHAIN:
7916 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7917 case Intrinsic::aarch64_neon_ld2:
7918 case Intrinsic::aarch64_neon_ld3:
7919 case Intrinsic::aarch64_neon_ld4:
7920 case Intrinsic::aarch64_neon_ld1x2:
7921 case Intrinsic::aarch64_neon_ld1x3:
7922 case Intrinsic::aarch64_neon_ld1x4:
7923 case Intrinsic::aarch64_neon_ld2lane:
7924 case Intrinsic::aarch64_neon_ld3lane:
7925 case Intrinsic::aarch64_neon_ld4lane:
7926 case Intrinsic::aarch64_neon_ld2r:
7927 case Intrinsic::aarch64_neon_ld3r:
7928 case Intrinsic::aarch64_neon_ld4r:
7929 case Intrinsic::aarch64_neon_st2:
7930 case Intrinsic::aarch64_neon_st3:
7931 case Intrinsic::aarch64_neon_st4:
7932 case Intrinsic::aarch64_neon_st1x2:
7933 case Intrinsic::aarch64_neon_st1x3:
7934 case Intrinsic::aarch64_neon_st1x4:
7935 case Intrinsic::aarch64_neon_st2lane:
7936 case Intrinsic::aarch64_neon_st3lane:
7937 case Intrinsic::aarch64_neon_st4lane:
7938 return performNEONPostLDSTCombine(N, DCI, DAG);
7939 default:
7940 break;
7941 }
7942 }
7943 return SDValue();
7944}
7945
7946// Check if the return value is used as only a return value, as otherwise
7947// we can't perform a tail-call. In particular, we need to check for
7948// target ISD nodes that are returns and any other "odd" constructs
7949// that the generic analysis code won't necessarily catch.
7950bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
7951 SDValue &Chain) const {
7952 if (N->getNumValues() != 1)
7953 return false;
7954 if (!N->hasNUsesOfValue(1, 0))
7955 return false;
7956
7957 SDValue TCChain = Chain;
7958 SDNode *Copy = *N->use_begin();
7959 if (Copy->getOpcode() == ISD::CopyToReg) {
7960 // If the copy has a glue operand, we conservatively assume it isn't safe to
7961 // perform a tail call.
7962 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7963 MVT::Glue)
7964 return false;
7965 TCChain = Copy->getOperand(0);
7966 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7967 return false;
7968
7969 bool HasRet = false;
7970 for (SDNode *Node : Copy->uses()) {
7971 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
7972 return false;
7973 HasRet = true;
7974 }
7975
7976 if (!HasRet)
7977 return false;
7978
7979 Chain = TCChain;
7980 return true;
7981}
7982
7983// Return whether the an instruction can potentially be optimized to a tail
7984// call. This will cause the optimizers to attempt to move, or duplicate,
7985// return instructions to help enable tail call optimizations for this
7986// instruction.
7987bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7988 if (!CI->isTailCall())
7989 return false;
7990
7991 return true;
7992}
7993
7994bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7995 SDValue &Offset,
7996 ISD::MemIndexedMode &AM,
7997 bool &IsInc,
7998 SelectionDAG &DAG) const {
7999 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8000 return false;
8001
8002 Base = Op->getOperand(0);
8003 // All of the indexed addressing mode instructions take a signed
8004 // 9 bit immediate offset.
8005 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8006 int64_t RHSC = (int64_t)RHS->getZExtValue();
8007 if (RHSC >= 256 || RHSC <= -256)
8008 return false;
8009 IsInc = (Op->getOpcode() == ISD::ADD);
8010 Offset = Op->getOperand(1);
8011 return true;
8012 }
8013 return false;
8014}
8015
8016bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8017 SDValue &Offset,
8018 ISD::MemIndexedMode &AM,
8019 SelectionDAG &DAG) const {
8020 EVT VT;
8021 SDValue Ptr;
8022 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8023 VT = LD->getMemoryVT();
8024 Ptr = LD->getBasePtr();
8025 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8026 VT = ST->getMemoryVT();
8027 Ptr = ST->getBasePtr();
8028 } else
8029 return false;
8030
8031 bool IsInc;
8032 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8033 return false;
8034 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8035 return true;
8036}
8037
8038bool AArch64TargetLowering::getPostIndexedAddressParts(
8039 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8040 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8041 EVT VT;
8042 SDValue Ptr;
8043 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8044 VT = LD->getMemoryVT();
8045 Ptr = LD->getBasePtr();
8046 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8047 VT = ST->getMemoryVT();
8048 Ptr = ST->getBasePtr();
8049 } else
8050 return false;
8051
8052 bool IsInc;
8053 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8054 return false;
8055 // Post-indexing updates the base, so it's not a valid transform
8056 // if that's not the same as the load's pointer.
8057 if (Ptr != Base)
8058 return false;
8059 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8060 return true;
8061}
8062
Tim Northoverf8bfe212014-07-18 13:07:05 +00008063static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8064 SelectionDAG &DAG) {
8065 if (N->getValueType(0) != MVT::i16)
8066 return;
8067
8068 SDLoc DL(N);
8069 SDValue Op = N->getOperand(0);
8070 assert(Op.getValueType() == MVT::f16 &&
8071 "Inconsistent bitcast? Only 16-bit types should be i16 or f16");
8072 Op = SDValue(
8073 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8074 DAG.getUNDEF(MVT::i32), Op,
8075 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
8076 0);
8077 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8078 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8079}
8080
Tim Northover3b0846e2014-05-24 12:50:23 +00008081void AArch64TargetLowering::ReplaceNodeResults(
8082 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8083 switch (N->getOpcode()) {
8084 default:
8085 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00008086 case ISD::BITCAST:
8087 ReplaceBITCASTResults(N, Results, DAG);
8088 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00008089 case ISD::FP_TO_UINT:
8090 case ISD::FP_TO_SINT:
8091 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8092 // Let normal code take care of it by not adding anything to Results.
8093 return;
8094 }
8095}
8096
8097bool AArch64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
8098 // Loads and stores less than 128-bits are already atomic; ones above that
8099 // are doomed anyway, so defer to the default libcall and blame the OS when
8100 // things go wrong:
8101 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
8102 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
8103 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
8104 return LI->getType()->getPrimitiveSizeInBits() == 128;
8105
8106 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
8107 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
8108}
8109
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00008110bool AArch64TargetLowering::useLoadStackGuardNode() const {
8111 return true;
8112}
8113
Chandler Carruth9d010ff2014-07-03 00:23:43 +00008114TargetLoweringBase::LegalizeTypeAction
8115AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8116 MVT SVT = VT.getSimpleVT();
8117 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
8118 // v4i16, v2i32 instead of to promote.
8119 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8120 || SVT == MVT::v1f32)
8121 return TypeWidenVector;
8122
8123 return TargetLoweringBase::getPreferredVectorAction(VT);
8124}
8125
Tim Northover3b0846e2014-05-24 12:50:23 +00008126Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
8127 AtomicOrdering Ord) const {
8128 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8129 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
8130 bool IsAcquire =
8131 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
8132
8133 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
8134 // intrinsic must return {i64, i64} and we have to recombine them into a
8135 // single i128 here.
8136 if (ValTy->getPrimitiveSizeInBits() == 128) {
8137 Intrinsic::ID Int =
8138 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
8139 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
8140
8141 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8142 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
8143
8144 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
8145 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
8146 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
8147 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
8148 return Builder.CreateOr(
8149 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
8150 }
8151
8152 Type *Tys[] = { Addr->getType() };
8153 Intrinsic::ID Int =
8154 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
8155 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
8156
8157 return Builder.CreateTruncOrBitCast(
8158 Builder.CreateCall(Ldxr, Addr),
8159 cast<PointerType>(Addr->getType())->getElementType());
8160}
8161
8162Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
8163 Value *Val, Value *Addr,
8164 AtomicOrdering Ord) const {
8165 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8166 bool IsRelease =
8167 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
8168
8169 // Since the intrinsics must have legal type, the i128 intrinsics take two
8170 // parameters: "i64, i64". We must marshal Val into the appropriate form
8171 // before the call.
8172 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
8173 Intrinsic::ID Int =
8174 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
8175 Function *Stxr = Intrinsic::getDeclaration(M, Int);
8176 Type *Int64Ty = Type::getInt64Ty(M->getContext());
8177
8178 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
8179 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
8180 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8181 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
8182 }
8183
8184 Intrinsic::ID Int =
8185 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
8186 Type *Tys[] = { Addr->getType() };
8187 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
8188
8189 return Builder.CreateCall2(
8190 Stxr, Builder.CreateZExtOrBitCast(
8191 Val, Stxr->getFunctionType()->getParamType(0)),
8192 Addr);
8193}