blob: f0fb03451b2a6f72dbdd7ff7a65f42c41f02091c [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"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
18#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64TargetMachine.h"
20#include "AArch64TargetObjectFile.h"
21#include "MCTargetDesc/AArch64AddressingModes.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "aarch64-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls");
41STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043// Place holder until extr generation is tested fully.
44static cl::opt<bool>
45EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47 cl::init(true));
48
49static cl::opt<bool>
50EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000051 cl::desc("Allow AArch64 SLI/SRI formation"),
52 cl::init(false));
53
54// FIXME: The necessary dtprel relocations don't seem to be supported
55// well in the GNU bfd and gold linkers at the moment. Therefore, by
56// default, for now, fall back to GeneralDynamic code generation.
57cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Matthias Braunaf7d7702015-07-16 20:02:37 +000062/// Value type used for condition codes.
63static const MVT MVT_CC = MVT::i32;
64
Eric Christopher905f12d2015-01-29 00:19:42 +000065AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000068
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85 }
86
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000097 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000098
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000105 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000106 }
107
108 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000109 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000110
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147 // Virtually no operation on f128 is legal, but LLVM can't expand them when
148 // there's a valid register class, so we need custom operations in most cases.
149 setOperationAction(ISD::FABS, MVT::f128, Expand);
150 setOperationAction(ISD::FADD, MVT::f128, Custom);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152 setOperationAction(ISD::FCOS, MVT::f128, Expand);
153 setOperationAction(ISD::FDIV, MVT::f128, Custom);
154 setOperationAction(ISD::FMA, MVT::f128, Expand);
155 setOperationAction(ISD::FMUL, MVT::f128, Custom);
156 setOperationAction(ISD::FNEG, MVT::f128, Expand);
157 setOperationAction(ISD::FPOW, MVT::f128, Expand);
158 setOperationAction(ISD::FREM, MVT::f128, Expand);
159 setOperationAction(ISD::FRINT, MVT::f128, Expand);
160 setOperationAction(ISD::FSIN, MVT::f128, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163 setOperationAction(ISD::FSUB, MVT::f128, Custom);
164 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165 setOperationAction(ISD::SETCC, MVT::f128, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167 setOperationAction(ISD::SELECT, MVT::f128, Custom);
168 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171 // Lowering for many of the conversions is actually specified by the non-f128
172 // type. The LowerXXX function will be trivial when f128 isn't involved.
173 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188 // Variable arguments.
189 setOperationAction(ISD::VASTART, MVT::Other, Custom);
190 setOperationAction(ISD::VAARG, MVT::Other, Custom);
191 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194 // Variable-sized objects.
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
Tim Northover3b0846e2014-05-24 12:50:23 +0000199 // Constant pool entries
200 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
201
202 // BlockAddress
203 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
204
205 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
206 setOperationAction(ISD::ADDC, MVT::i32, Custom);
207 setOperationAction(ISD::ADDE, MVT::i32, Custom);
208 setOperationAction(ISD::SUBC, MVT::i32, Custom);
209 setOperationAction(ISD::SUBE, MVT::i32, Custom);
210 setOperationAction(ISD::ADDC, MVT::i64, Custom);
211 setOperationAction(ISD::ADDE, MVT::i64, Custom);
212 setOperationAction(ISD::SUBC, MVT::i64, Custom);
213 setOperationAction(ISD::SUBE, MVT::i64, Custom);
214
215 // AArch64 lacks both left-rotate and popcount instructions.
216 setOperationAction(ISD::ROTL, MVT::i32, Expand);
217 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000218 for (MVT VT : MVT::vector_valuetypes()) {
219 setOperationAction(ISD::ROTL, VT, Expand);
220 setOperationAction(ISD::ROTR, VT, Expand);
221 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000222
223 // AArch64 doesn't have {U|S}MUL_LOHI.
224 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
225 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
226
227
228 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
229 // counterparts, which AArch64 supports directly.
230 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
231 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
232 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
233 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
234
235 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
236 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
237
238 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
239 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
240 setOperationAction(ISD::SREM, MVT::i32, Expand);
241 setOperationAction(ISD::SREM, MVT::i64, Expand);
242 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
243 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
244 setOperationAction(ISD::UREM, MVT::i32, Expand);
245 setOperationAction(ISD::UREM, MVT::i64, Expand);
246
247 // Custom lower Add/Sub/Mul with overflow.
248 setOperationAction(ISD::SADDO, MVT::i32, Custom);
249 setOperationAction(ISD::SADDO, MVT::i64, Custom);
250 setOperationAction(ISD::UADDO, MVT::i32, Custom);
251 setOperationAction(ISD::UADDO, MVT::i64, Custom);
252 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
253 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
254 setOperationAction(ISD::USUBO, MVT::i32, Custom);
255 setOperationAction(ISD::USUBO, MVT::i64, Custom);
256 setOperationAction(ISD::SMULO, MVT::i32, Custom);
257 setOperationAction(ISD::SMULO, MVT::i64, Custom);
258 setOperationAction(ISD::UMULO, MVT::i32, Custom);
259 setOperationAction(ISD::UMULO, MVT::i64, Custom);
260
261 setOperationAction(ISD::FSIN, MVT::f32, Expand);
262 setOperationAction(ISD::FSIN, MVT::f64, Expand);
263 setOperationAction(ISD::FCOS, MVT::f32, Expand);
264 setOperationAction(ISD::FCOS, MVT::f64, Expand);
265 setOperationAction(ISD::FPOW, MVT::f32, Expand);
266 setOperationAction(ISD::FPOW, MVT::f64, Expand);
267 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
268 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
269
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000270 // f16 is a storage-only type, always promote it to f32.
271 setOperationAction(ISD::SETCC, MVT::f16, Promote);
272 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
273 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
274 setOperationAction(ISD::SELECT, MVT::f16, Promote);
275 setOperationAction(ISD::FADD, MVT::f16, Promote);
276 setOperationAction(ISD::FSUB, MVT::f16, Promote);
277 setOperationAction(ISD::FMUL, MVT::f16, Promote);
278 setOperationAction(ISD::FDIV, MVT::f16, Promote);
279 setOperationAction(ISD::FREM, MVT::f16, Promote);
280 setOperationAction(ISD::FMA, MVT::f16, Promote);
281 setOperationAction(ISD::FNEG, MVT::f16, Promote);
282 setOperationAction(ISD::FABS, MVT::f16, Promote);
283 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
284 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
285 setOperationAction(ISD::FCOS, MVT::f16, Promote);
286 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
287 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
288 setOperationAction(ISD::FPOW, MVT::f16, Promote);
289 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
290 setOperationAction(ISD::FRINT, MVT::f16, Promote);
291 setOperationAction(ISD::FSIN, MVT::f16, Promote);
292 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
293 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
294 setOperationAction(ISD::FEXP, MVT::f16, Promote);
295 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
296 setOperationAction(ISD::FLOG, MVT::f16, Promote);
297 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
298 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
299 setOperationAction(ISD::FROUND, MVT::f16, Promote);
300 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
301 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
302 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000303 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
304 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000305
Oliver Stannard89d15422014-08-27 16:16:04 +0000306 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
307 // known to be safe.
308 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
309 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
310 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
311 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
312 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
313 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
314 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
315 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
316 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
317 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
318 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
320
321 // Expand all other v4f16 operations.
322 // FIXME: We could generate better code by promoting some operations to
323 // a pair of v4f32s
324 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
325 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
326 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
327 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
328 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
329 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
330 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
331 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
332 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
333 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
334 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
335 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
336 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
337 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
338 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
339 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
340 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
341 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
342 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
343 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
344 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
345 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
346 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
347 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
348 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
349 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
350
351
352 // v8f16 is also a storage-only type, so expand it.
353 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
354 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
355 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
356 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
357 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
358 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
359 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
360 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
361 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
362 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
363 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
364 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
365 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
366 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
367 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
368 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
369 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
370 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
371 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
372 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
373 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
374 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
375 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
376 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
377 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
378 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
379 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
380 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
381 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
382 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
383 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
384
Tim Northover3b0846e2014-05-24 12:50:23 +0000385 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000386 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000387 setOperationAction(ISD::FFLOOR, Ty, Legal);
388 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
389 setOperationAction(ISD::FCEIL, Ty, Legal);
390 setOperationAction(ISD::FRINT, Ty, Legal);
391 setOperationAction(ISD::FTRUNC, Ty, Legal);
392 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000393 setOperationAction(ISD::FMINNUM, Ty, Legal);
394 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000395 setOperationAction(ISD::FMINNAN, Ty, Legal);
396 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000397 }
398
399 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
400
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000401 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
402 // This requires the Performance Monitors extension.
403 if (Subtarget->hasPerfMon())
404 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
405
Tim Northover3b0846e2014-05-24 12:50:23 +0000406 if (Subtarget->isTargetMachO()) {
407 // For iOS, we don't want to the normal expansion of a libcall to
408 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
409 // traffic.
410 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
411 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
412 } else {
413 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
414 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
415 }
416
Juergen Ributzka23266502014-12-10 19:43:32 +0000417 // Make floating-point constants legal for the large code model, so they don't
418 // become loads from the constant pool.
419 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
420 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
421 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
422 }
423
Tim Northover3b0846e2014-05-24 12:50:23 +0000424 // AArch64 does not have floating-point extending loads, i1 sign-extending
425 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000426 for (MVT VT : MVT::fp_valuetypes()) {
427 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
428 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
429 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
430 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
431 }
432 for (MVT VT : MVT::integer_valuetypes())
433 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
434
Tim Northover3b0846e2014-05-24 12:50:23 +0000435 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
436 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
437 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
438 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
439 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
440 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
441 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000442
443 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
444 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
445
Tim Northover3b0846e2014-05-24 12:50:23 +0000446 // Indexed loads and stores are supported.
447 for (unsigned im = (unsigned)ISD::PRE_INC;
448 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
449 setIndexedLoadAction(im, MVT::i8, Legal);
450 setIndexedLoadAction(im, MVT::i16, Legal);
451 setIndexedLoadAction(im, MVT::i32, Legal);
452 setIndexedLoadAction(im, MVT::i64, Legal);
453 setIndexedLoadAction(im, MVT::f64, Legal);
454 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000455 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000456 setIndexedStoreAction(im, MVT::i8, Legal);
457 setIndexedStoreAction(im, MVT::i16, Legal);
458 setIndexedStoreAction(im, MVT::i32, Legal);
459 setIndexedStoreAction(im, MVT::i64, Legal);
460 setIndexedStoreAction(im, MVT::f64, Legal);
461 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000462 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000463 }
464
465 // Trap.
466 setOperationAction(ISD::TRAP, MVT::Other, Legal);
467
468 // We combine OR nodes for bitfield operations.
469 setTargetDAGCombine(ISD::OR);
470
471 // Vector add and sub nodes may conceal a high-half opportunity.
472 // Also, try to fold ADD into CSINC/CSINV..
473 setTargetDAGCombine(ISD::ADD);
474 setTargetDAGCombine(ISD::SUB);
475
476 setTargetDAGCombine(ISD::XOR);
477 setTargetDAGCombine(ISD::SINT_TO_FP);
478 setTargetDAGCombine(ISD::UINT_TO_FP);
479
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000480 setTargetDAGCombine(ISD::FP_TO_SINT);
481 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000482 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000483
Tim Northover3b0846e2014-05-24 12:50:23 +0000484 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
485
486 setTargetDAGCombine(ISD::ANY_EXTEND);
487 setTargetDAGCombine(ISD::ZERO_EXTEND);
488 setTargetDAGCombine(ISD::SIGN_EXTEND);
489 setTargetDAGCombine(ISD::BITCAST);
490 setTargetDAGCombine(ISD::CONCAT_VECTORS);
491 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000492 if (Subtarget->supportsAddressTopByteIgnored())
493 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000494
495 setTargetDAGCombine(ISD::MUL);
496
497 setTargetDAGCombine(ISD::SELECT);
498 setTargetDAGCombine(ISD::VSELECT);
499
500 setTargetDAGCombine(ISD::INTRINSIC_VOID);
501 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
502 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000503 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000504
505 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
506 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
507 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
508
509 setStackPointerRegisterToSaveRestore(AArch64::SP);
510
511 setSchedulingPreference(Sched::Hybrid);
512
513 // Enable TBZ/TBNZ
514 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000515 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000516
517 setMinFunctionAlignment(2);
518
Tim Northover3b0846e2014-05-24 12:50:23 +0000519 setHasExtractBitsInsn(true);
520
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000521 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
522
Tim Northover3b0846e2014-05-24 12:50:23 +0000523 if (Subtarget->hasNEON()) {
524 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
525 // silliness like this:
526 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
527 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
528 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
529 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
530 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
531 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
532 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
533 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
534 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
535 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
536 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
537 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
538 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
539 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
540 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
541 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
542 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
543 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
544 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
545 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
546 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
547 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
548 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
549 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
550 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
551
552 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
553 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
554 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
555 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
556 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
557
558 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
559
560 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
561 // elements smaller than i32, so promote the input to i32 first.
562 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
563 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
564 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
565 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000566 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
567 // -> v8f16 conversions.
568 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
569 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
570 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
571 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000572 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
573 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
574 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
575 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
576 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000577 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
578 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
579 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
580 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000581
582 // AArch64 doesn't have MUL.2d:
583 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000584 // Custom handling for some quad-vector types to detect MULL.
585 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
586 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
587 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
588
Tim Northover3b0846e2014-05-24 12:50:23 +0000589 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
590 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
591 // Likewise, narrowing and extending vector loads/stores aren't handled
592 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000593 for (MVT VT : MVT::vector_valuetypes()) {
594 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000595
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000596 setOperationAction(ISD::MULHS, VT, Expand);
597 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
598 setOperationAction(ISD::MULHU, VT, Expand);
599 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000600
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000601 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000602
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000603 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000604 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000605 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
606 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
607 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
608 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000609 }
610
611 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000612 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000613 setOperationAction(ISD::FFLOOR, Ty, Legal);
614 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
615 setOperationAction(ISD::FCEIL, Ty, Legal);
616 setOperationAction(ISD::FRINT, Ty, Legal);
617 setOperationAction(ISD::FTRUNC, Ty, Legal);
618 setOperationAction(ISD::FROUND, Ty, Legal);
619 }
620 }
James Molloyf089ab72014-08-06 10:42:18 +0000621
622 // Prefer likely predicted branches to selects on out-of-order cores.
623 if (Subtarget->isCortexA57())
624 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000625}
626
627void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000628 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000629 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
630 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
631
632 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
633 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000634 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000635 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
636 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
637
638 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
639 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
640 }
641
642 // Mark vector float intrinsics as expand.
643 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
644 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
645 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
646 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
647 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
648 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
649 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
650 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
651 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
652 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000653
654 // But we do support custom-lowering for FCOPYSIGN.
655 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000656 }
657
658 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
659 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
660 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
661 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
662 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
663 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
664 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
665 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
666 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
667 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
668 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
669 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
670
671 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
672 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
673 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000674 for (MVT InnerVT : MVT::all_valuetypes())
675 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000676
677 // CNT supports only B element sizes.
678 if (VT != MVT::v8i8 && VT != MVT::v16i8)
679 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
680
681 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
682 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
683 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
684 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
685 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
686
687 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
688 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
689
James Molloyfaf4e3c2015-07-17 17:10:45 +0000690 // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
691 // i64.
James Molloycfb04432015-05-15 16:15:57 +0000692 if (!VT.isFloatingPoint() &&
693 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
James Molloyfaf4e3c2015-07-17 17:10:45 +0000694 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
695 ISD::SABSDIFF, ISD::UABSDIFF})
James Molloycfb04432015-05-15 16:15:57 +0000696 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
697
James Molloy63be1982015-08-14 09:08:50 +0000698 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
699 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000700 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
701 ISD::FMINNUM, ISD::FMAXNUM})
James Molloyedf38f02015-08-11 12:06:33 +0000702 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
703
Tim Northover3b0846e2014-05-24 12:50:23 +0000704 if (Subtarget->isLittleEndian()) {
705 for (unsigned im = (unsigned)ISD::PRE_INC;
706 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
707 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
708 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
709 }
710 }
711}
712
713void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
714 addRegisterClass(VT, &AArch64::FPR64RegClass);
715 addTypeForNEON(VT, MVT::v2i32);
716}
717
718void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
719 addRegisterClass(VT, &AArch64::FPR128RegClass);
720 addTypeForNEON(VT, MVT::v4i32);
721}
722
Mehdi Amini44ede332015-07-09 02:09:04 +0000723EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
724 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000725 if (!VT.isVector())
726 return MVT::i32;
727 return VT.changeVectorElementTypeToInteger();
728}
729
730/// computeKnownBitsForTargetNode - Determine which of the bits specified in
731/// Mask are known to be either zero or one and return them in the
732/// KnownZero/KnownOne bitsets.
733void AArch64TargetLowering::computeKnownBitsForTargetNode(
734 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
735 const SelectionDAG &DAG, unsigned Depth) const {
736 switch (Op.getOpcode()) {
737 default:
738 break;
739 case AArch64ISD::CSEL: {
740 APInt KnownZero2, KnownOne2;
741 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
742 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
743 KnownZero &= KnownZero2;
744 KnownOne &= KnownOne2;
745 break;
746 }
747 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000748 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000749 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
750 switch (IntID) {
751 default: return;
752 case Intrinsic::aarch64_ldaxr:
753 case Intrinsic::aarch64_ldxr: {
754 unsigned BitWidth = KnownOne.getBitWidth();
755 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
756 unsigned MemBits = VT.getScalarType().getSizeInBits();
757 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
758 return;
759 }
760 }
761 break;
762 }
763 case ISD::INTRINSIC_WO_CHAIN:
764 case ISD::INTRINSIC_VOID: {
765 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
766 switch (IntNo) {
767 default:
768 break;
769 case Intrinsic::aarch64_neon_umaxv:
770 case Intrinsic::aarch64_neon_uminv: {
771 // Figure out the datatype of the vector operand. The UMINV instruction
772 // will zero extend the result, so we can mark as known zero all the
773 // bits larger than the element datatype. 32-bit or larget doesn't need
774 // this as those are legal types and will be handled by isel directly.
775 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
776 unsigned BitWidth = KnownZero.getBitWidth();
777 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
778 assert(BitWidth >= 8 && "Unexpected width!");
779 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
780 KnownZero |= Mask;
781 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
782 assert(BitWidth >= 16 && "Unexpected width!");
783 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
784 KnownZero |= Mask;
785 }
786 break;
787 } break;
788 }
789 }
790 }
791}
792
Mehdi Aminieaabc512015-07-09 15:12:23 +0000793MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
794 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000795 return MVT::i64;
796}
797
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000798bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
799 unsigned AddrSpace,
800 unsigned Align,
801 bool *Fast) const {
802 if (Subtarget->requiresStrictAlign())
803 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000804
805 // FIXME: This is mostly true for Cyclone, but not necessarily others.
806 if (Fast) {
807 // FIXME: Define an attribute for slow unaligned accesses instead of
808 // relying on the CPU type as a proxy.
809 // On Cyclone, unaligned 128-bit stores are slow.
810 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
811 // See comments in performSTORECombine() for more details about
812 // these conditions.
813
814 // Code that uses clang vector extensions can mark that it
815 // wants unaligned accesses to be treated as fast by
816 // underspecifying alignment to be 1 or 2.
817 Align <= 2 ||
818
819 // Disregard v2i64. Memcpy lowering produces those and splitting
820 // them regresses performance on micro-benchmarks and olden/bh.
821 VT == MVT::v2i64;
822 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000823 return true;
824}
825
Tim Northover3b0846e2014-05-24 12:50:23 +0000826FastISel *
827AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
828 const TargetLibraryInfo *libInfo) const {
829 return AArch64::createFastISel(funcInfo, libInfo);
830}
831
832const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000833 switch ((AArch64ISD::NodeType)Opcode) {
834 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000835 case AArch64ISD::CALL: return "AArch64ISD::CALL";
836 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
837 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
838 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
839 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
840 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
841 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
842 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
843 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
844 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
845 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
846 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000847 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000848 case AArch64ISD::ADC: return "AArch64ISD::ADC";
849 case AArch64ISD::SBC: return "AArch64ISD::SBC";
850 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
851 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
852 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
853 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
854 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000855 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
856 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
857 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000858 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000859 case AArch64ISD::DUP: return "AArch64ISD::DUP";
860 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
861 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
862 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
863 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
864 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
865 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
866 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
867 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
868 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
869 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
870 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
871 case AArch64ISD::BICi: return "AArch64ISD::BICi";
872 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
873 case AArch64ISD::BSL: return "AArch64ISD::BSL";
874 case AArch64ISD::NEG: return "AArch64ISD::NEG";
875 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
876 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
877 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
878 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
879 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
880 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
881 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
882 case AArch64ISD::REV16: return "AArch64ISD::REV16";
883 case AArch64ISD::REV32: return "AArch64ISD::REV32";
884 case AArch64ISD::REV64: return "AArch64ISD::REV64";
885 case AArch64ISD::EXT: return "AArch64ISD::EXT";
886 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
887 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
888 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
889 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
890 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
891 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
892 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
893 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
894 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
895 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
896 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
897 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
898 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
899 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
900 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
901 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
902 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
903 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
904 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
905 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
906 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000907 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
908 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
909 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
910 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
911 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
912 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000913 case AArch64ISD::NOT: return "AArch64ISD::NOT";
914 case AArch64ISD::BIT: return "AArch64ISD::BIT";
915 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
916 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
917 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
918 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
919 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000920 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000921 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
922 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000923 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000924 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
925 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
926 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
927 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
928 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
929 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
930 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
931 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
932 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
933 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
934 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
935 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
936 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
937 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
938 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
939 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
940 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
941 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
942 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
943 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
944 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
945 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
946 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
947 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
948 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
949 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
950 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
951 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
952 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000953 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
954 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000955 }
Matthias Braund04893f2015-05-07 21:33:59 +0000956 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000957}
958
959MachineBasicBlock *
960AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
961 MachineBasicBlock *MBB) const {
962 // We materialise the F128CSEL pseudo-instruction as some control flow and a
963 // phi node:
964
965 // OrigBB:
966 // [... previous instrs leading to comparison ...]
967 // b.ne TrueBB
968 // b EndBB
969 // TrueBB:
970 // ; Fallthrough
971 // EndBB:
972 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
973
Tim Northover3b0846e2014-05-24 12:50:23 +0000974 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000975 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000976 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
977 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000978 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000979
980 unsigned DestReg = MI->getOperand(0).getReg();
981 unsigned IfTrueReg = MI->getOperand(1).getReg();
982 unsigned IfFalseReg = MI->getOperand(2).getReg();
983 unsigned CondCode = MI->getOperand(3).getImm();
984 bool NZCVKilled = MI->getOperand(4).isKill();
985
986 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
987 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
988 MF->insert(It, TrueBB);
989 MF->insert(It, EndBB);
990
991 // Transfer rest of current basic-block to EndBB
992 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
993 MBB->end());
994 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
995
996 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
997 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
998 MBB->addSuccessor(TrueBB);
999 MBB->addSuccessor(EndBB);
1000
1001 // TrueBB falls through to the end.
1002 TrueBB->addSuccessor(EndBB);
1003
1004 if (!NZCVKilled) {
1005 TrueBB->addLiveIn(AArch64::NZCV);
1006 EndBB->addLiveIn(AArch64::NZCV);
1007 }
1008
1009 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1010 .addReg(IfTrueReg)
1011 .addMBB(TrueBB)
1012 .addReg(IfFalseReg)
1013 .addMBB(MBB);
1014
1015 MI->eraseFromParent();
1016 return EndBB;
1017}
1018
1019MachineBasicBlock *
1020AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1021 MachineBasicBlock *BB) const {
1022 switch (MI->getOpcode()) {
1023 default:
1024#ifndef NDEBUG
1025 MI->dump();
1026#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001027 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001028
1029 case AArch64::F128CSEL:
1030 return EmitF128CSEL(MI, BB);
1031
1032 case TargetOpcode::STACKMAP:
1033 case TargetOpcode::PATCHPOINT:
1034 return emitPatchPoint(MI, BB);
1035 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001036}
1037
1038//===----------------------------------------------------------------------===//
1039// AArch64 Lowering private implementation.
1040//===----------------------------------------------------------------------===//
1041
1042//===----------------------------------------------------------------------===//
1043// Lowering Code
1044//===----------------------------------------------------------------------===//
1045
1046/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1047/// CC
1048static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1049 switch (CC) {
1050 default:
1051 llvm_unreachable("Unknown condition code!");
1052 case ISD::SETNE:
1053 return AArch64CC::NE;
1054 case ISD::SETEQ:
1055 return AArch64CC::EQ;
1056 case ISD::SETGT:
1057 return AArch64CC::GT;
1058 case ISD::SETGE:
1059 return AArch64CC::GE;
1060 case ISD::SETLT:
1061 return AArch64CC::LT;
1062 case ISD::SETLE:
1063 return AArch64CC::LE;
1064 case ISD::SETUGT:
1065 return AArch64CC::HI;
1066 case ISD::SETUGE:
1067 return AArch64CC::HS;
1068 case ISD::SETULT:
1069 return AArch64CC::LO;
1070 case ISD::SETULE:
1071 return AArch64CC::LS;
1072 }
1073}
1074
1075/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1076static void changeFPCCToAArch64CC(ISD::CondCode CC,
1077 AArch64CC::CondCode &CondCode,
1078 AArch64CC::CondCode &CondCode2) {
1079 CondCode2 = AArch64CC::AL;
1080 switch (CC) {
1081 default:
1082 llvm_unreachable("Unknown FP condition!");
1083 case ISD::SETEQ:
1084 case ISD::SETOEQ:
1085 CondCode = AArch64CC::EQ;
1086 break;
1087 case ISD::SETGT:
1088 case ISD::SETOGT:
1089 CondCode = AArch64CC::GT;
1090 break;
1091 case ISD::SETGE:
1092 case ISD::SETOGE:
1093 CondCode = AArch64CC::GE;
1094 break;
1095 case ISD::SETOLT:
1096 CondCode = AArch64CC::MI;
1097 break;
1098 case ISD::SETOLE:
1099 CondCode = AArch64CC::LS;
1100 break;
1101 case ISD::SETONE:
1102 CondCode = AArch64CC::MI;
1103 CondCode2 = AArch64CC::GT;
1104 break;
1105 case ISD::SETO:
1106 CondCode = AArch64CC::VC;
1107 break;
1108 case ISD::SETUO:
1109 CondCode = AArch64CC::VS;
1110 break;
1111 case ISD::SETUEQ:
1112 CondCode = AArch64CC::EQ;
1113 CondCode2 = AArch64CC::VS;
1114 break;
1115 case ISD::SETUGT:
1116 CondCode = AArch64CC::HI;
1117 break;
1118 case ISD::SETUGE:
1119 CondCode = AArch64CC::PL;
1120 break;
1121 case ISD::SETLT:
1122 case ISD::SETULT:
1123 CondCode = AArch64CC::LT;
1124 break;
1125 case ISD::SETLE:
1126 case ISD::SETULE:
1127 CondCode = AArch64CC::LE;
1128 break;
1129 case ISD::SETNE:
1130 case ISD::SETUNE:
1131 CondCode = AArch64CC::NE;
1132 break;
1133 }
1134}
1135
1136/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1137/// CC usable with the vector instructions. Fewer operations are available
1138/// without a real NZCV register, so we have to use less efficient combinations
1139/// to get the same effect.
1140static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1141 AArch64CC::CondCode &CondCode,
1142 AArch64CC::CondCode &CondCode2,
1143 bool &Invert) {
1144 Invert = false;
1145 switch (CC) {
1146 default:
1147 // Mostly the scalar mappings work fine.
1148 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1149 break;
1150 case ISD::SETUO:
1151 Invert = true; // Fallthrough
1152 case ISD::SETO:
1153 CondCode = AArch64CC::MI;
1154 CondCode2 = AArch64CC::GE;
1155 break;
1156 case ISD::SETUEQ:
1157 case ISD::SETULT:
1158 case ISD::SETULE:
1159 case ISD::SETUGT:
1160 case ISD::SETUGE:
1161 // All of the compare-mask comparisons are ordered, but we can switch
1162 // between the two by a double inversion. E.g. ULE == !OGT.
1163 Invert = true;
1164 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1165 break;
1166 }
1167}
1168
1169static bool isLegalArithImmed(uint64_t C) {
1170 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1171 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1172}
1173
1174static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1175 SDLoc dl, SelectionDAG &DAG) {
1176 EVT VT = LHS.getValueType();
1177
1178 if (VT.isFloatingPoint())
1179 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1180
1181 // The CMP instruction is just an alias for SUBS, and representing it as
1182 // SUBS means that it's possible to get CSE with subtract operations.
1183 // A later phase can perform the optimization of setting the destination
1184 // register to WZR/XZR if it ends up being unused.
1185 unsigned Opcode = AArch64ISD::SUBS;
1186
Artyom Skrobov314ee042015-11-25 19:41:11 +00001187 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001188 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1189 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1190 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1191 // can be set differently by this operation. It comes down to whether
1192 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1193 // everything is fine. If not then the optimization is wrong. Thus general
1194 // comparisons are only valid if op2 != 0.
1195
1196 // So, finally, the only LLVM-native comparisons that don't mention C and V
1197 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1198 // the absence of information about op2.
1199 Opcode = AArch64ISD::ADDS;
1200 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001201 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001202 !isUnsignedIntSetCC(CC)) {
1203 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1204 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1205 // of the signed comparisons.
1206 Opcode = AArch64ISD::ANDS;
1207 RHS = LHS.getOperand(1);
1208 LHS = LHS.getOperand(0);
1209 }
1210
Matthias Braunaf7d7702015-07-16 20:02:37 +00001211 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001212 .getValue(1);
1213}
1214
Matthias Braunaf7d7702015-07-16 20:02:37 +00001215/// \defgroup AArch64CCMP CMP;CCMP matching
1216///
1217/// These functions deal with the formation of CMP;CCMP;... sequences.
1218/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1219/// a comparison. They set the NZCV flags to a predefined value if their
1220/// predicate is false. This allows to express arbitrary conjunctions, for
1221/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1222/// expressed as:
1223/// cmp A
1224/// ccmp B, inv(CB), CA
1225/// check for CB flags
1226///
1227/// In general we can create code for arbitrary "... (and (and A B) C)"
1228/// sequences. We can also implement some "or" expressions, because "(or A B)"
1229/// is equivalent to "not (and (not A) (not B))" and we can implement some
1230/// negation operations:
1231/// We can negate the results of a single comparison by inverting the flags
1232/// used when the predicate fails and inverting the flags tested in the next
1233/// instruction; We can also negate the results of the whole previous
1234/// conditional compare sequence by inverting the flags tested in the next
1235/// instruction. However there is no way to negate the result of a partial
1236/// sequence.
1237///
1238/// Therefore on encountering an "or" expression we can negate the subtree on
1239/// one side and have to be able to push the negate to the leafs of the subtree
1240/// on the other side (see also the comments in code). As complete example:
1241/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1242/// (and (setCC (cmp C)) (setCD (cmp D)))"
1243/// is transformed to
1244/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1245/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1246/// and implemented as:
1247/// cmp C
1248/// ccmp D, inv(CD), CC
1249/// ccmp A, CA, inv(CD)
1250/// ccmp B, CB, inv(CA)
1251/// check for CB flags
1252/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1253/// by conditional compare sequences.
1254/// @{
1255
Geoff Berrye41c2df2015-07-20 22:03:52 +00001256/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001257static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1258 ISD::CondCode CC, SDValue CCOp,
1259 SDValue Condition, unsigned NZCV,
1260 SDLoc DL, SelectionDAG &DAG) {
1261 unsigned Opcode = 0;
1262 if (LHS.getValueType().isFloatingPoint())
1263 Opcode = AArch64ISD::FCCMP;
1264 else if (RHS.getOpcode() == ISD::SUB) {
1265 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001266 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001267 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1268 Opcode = AArch64ISD::CCMN;
1269 RHS = RHS.getOperand(1);
1270 }
1271 }
1272 if (Opcode == 0)
1273 Opcode = AArch64ISD::CCMP;
1274
1275 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1276 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1277}
1278
1279/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1280/// CanPushNegate is set to true if we can push a negate operation through
1281/// the tree in a was that we are left with AND operations and negate operations
1282/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1283/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1284/// brought into such a form.
1285static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1286 unsigned Depth = 0) {
1287 if (!Val.hasOneUse())
1288 return false;
1289 unsigned Opcode = Val->getOpcode();
1290 if (Opcode == ISD::SETCC) {
1291 CanPushNegate = true;
1292 return true;
1293 }
1294 // Protect against stack overflow.
1295 if (Depth > 15)
1296 return false;
1297 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1298 SDValue O0 = Val->getOperand(0);
1299 SDValue O1 = Val->getOperand(1);
1300 bool CanPushNegateL;
1301 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1302 return false;
1303 bool CanPushNegateR;
1304 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1305 return false;
1306 // We cannot push a negate through an AND operation (it would become an OR),
1307 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1308 // push the negate through the x/y subtrees.
1309 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1310 return true;
1311 }
1312 return false;
1313}
1314
1315/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1316/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1317/// Tries to transform the given i1 producing node @p Val to a series compare
1318/// and conditional compare operations. @returns an NZCV flags producing node
1319/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1320/// transformation was not possible.
1321/// On recursive invocations @p PushNegate may be set to true to have negation
1322/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1323/// for the comparisons in the current subtree; @p Depth limits the search
1324/// depth to avoid stack overflow.
1325static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1326 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1327 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1328 unsigned Depth = 0) {
1329 // We're at a tree leaf, produce a conditional comparison operation.
1330 unsigned Opcode = Val->getOpcode();
1331 if (Opcode == ISD::SETCC) {
1332 SDValue LHS = Val->getOperand(0);
1333 SDValue RHS = Val->getOperand(1);
1334 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1335 bool isInteger = LHS.getValueType().isInteger();
1336 if (PushNegate)
1337 CC = getSetCCInverse(CC, isInteger);
1338 SDLoc DL(Val);
1339 // Determine OutCC and handle FP special case.
1340 if (isInteger) {
1341 OutCC = changeIntCCToAArch64CC(CC);
1342 } else {
1343 assert(LHS.getValueType().isFloatingPoint());
1344 AArch64CC::CondCode ExtraCC;
1345 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1346 // Surpisingly some floating point conditions can't be tested with a
1347 // single condition code. Construct an additional comparison in this case.
1348 // See comment below on how we deal with OR conditions.
1349 if (ExtraCC != AArch64CC::AL) {
1350 SDValue ExtraCmp;
1351 if (!CCOp.getNode())
1352 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1353 else {
1354 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1355 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1356 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1357 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1358 NZCV, DL, DAG);
1359 }
1360 CCOp = ExtraCmp;
1361 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1362 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1363 }
1364 }
1365
1366 // Produce a normal comparison if we are first in the chain
1367 if (!CCOp.getNode())
1368 return emitComparison(LHS, RHS, CC, DL, DAG);
1369 // Otherwise produce a ccmp.
1370 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1371 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1372 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1373 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1374 DAG);
Matthias Braun266204b2015-08-20 23:33:31 +00001375 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
Matthias Braunaf7d7702015-07-16 20:02:37 +00001376 return SDValue();
1377
1378 assert((Opcode == ISD::OR || !PushNegate)
1379 && "Can only push negate through OR operation");
1380
1381 // Check if both sides can be transformed.
1382 SDValue LHS = Val->getOperand(0);
1383 SDValue RHS = Val->getOperand(1);
1384 bool CanPushNegateL;
1385 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1386 return SDValue();
1387 bool CanPushNegateR;
1388 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1389 return SDValue();
1390
1391 // Do we need to negate our operands?
1392 bool NegateOperands = Opcode == ISD::OR;
1393 // We can negate the results of all previous operations by inverting the
1394 // predicate flags giving us a free negation for one side. For the other side
1395 // we need to be able to push the negation to the leafs of the tree.
1396 if (NegateOperands) {
1397 if (!CanPushNegateL && !CanPushNegateR)
1398 return SDValue();
1399 // Order the side where we can push the negate through to LHS.
Matthias Braun46e56392015-08-20 23:33:34 +00001400 if (!CanPushNegateL && CanPushNegateR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001401 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001402 } else {
1403 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1404 bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1405 if (NeedsNegOutL && NeedsNegOutR)
1406 return SDValue();
1407 // Order the side where we need to negate the output flags to RHS so it
1408 // gets emitted first.
1409 if (NeedsNegOutL)
1410 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001411 }
1412
1413 // Emit RHS. If we want to negate the tree we only need to push a negate
1414 // through if we are already in a PushNegate case, otherwise we can negate
1415 // the "flags to test" afterwards.
1416 AArch64CC::CondCode RHSCC;
1417 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1418 CCOp, Predicate, Depth+1);
1419 if (NegateOperands && !PushNegate)
1420 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1421 // Emit LHS. We must push the negate through if we need to negate it.
1422 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1423 CmpR, RHSCC, Depth+1);
1424 // If we transformed an OR to and AND then we have to negate the result
1425 // (or absorb a PushNegate resulting in a double negation).
1426 if (Opcode == ISD::OR && !PushNegate)
1427 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1428 return CmpL;
1429}
1430
1431/// @}
1432
Tim Northover3b0846e2014-05-24 12:50:23 +00001433static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1434 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1435 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1436 EVT VT = RHS.getValueType();
1437 uint64_t C = RHSC->getZExtValue();
1438 if (!isLegalArithImmed(C)) {
1439 // Constant does not fit, try adjusting it by one?
1440 switch (CC) {
1441 default:
1442 break;
1443 case ISD::SETLT:
1444 case ISD::SETGE:
1445 if ((VT == MVT::i32 && C != 0x80000000 &&
1446 isLegalArithImmed((uint32_t)(C - 1))) ||
1447 (VT == MVT::i64 && C != 0x80000000ULL &&
1448 isLegalArithImmed(C - 1ULL))) {
1449 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1450 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001451 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001452 }
1453 break;
1454 case ISD::SETULT:
1455 case ISD::SETUGE:
1456 if ((VT == MVT::i32 && C != 0 &&
1457 isLegalArithImmed((uint32_t)(C - 1))) ||
1458 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1459 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1460 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001461 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001462 }
1463 break;
1464 case ISD::SETLE:
1465 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001466 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001467 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001468 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001469 isLegalArithImmed(C + 1ULL))) {
1470 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1471 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001472 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001473 }
1474 break;
1475 case ISD::SETULE:
1476 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001477 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001478 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001479 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001480 isLegalArithImmed(C + 1ULL))) {
1481 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1482 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001483 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001484 }
1485 break;
1486 }
1487 }
1488 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001489 SDValue Cmp;
1490 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001491 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001492 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1493
1494 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1495 // For the i8 operand, the largest immediate is 255, so this can be easily
1496 // encoded in the compare instruction. For the i16 operand, however, the
1497 // largest immediate cannot be encoded in the compare.
1498 // Therefore, use a sign extending load and cmn to avoid materializing the
1499 // -1 constant. For example,
1500 // movz w1, #65535
1501 // ldrh w0, [x0, #0]
1502 // cmp w0, w1
1503 // >
1504 // ldrsh w0, [x0, #0]
1505 // cmn w0, #1
1506 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1507 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001508 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001509 // transformation is profitable.
1510 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1511 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1512 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1513 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1514 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1515 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1516 SDValue SExt =
1517 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1518 DAG.getValueType(MVT::i16));
1519 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1520 RHS.getValueType()),
1521 CC, dl, DAG);
1522 AArch64CC = changeIntCCToAArch64CC(CC);
1523 }
1524 }
1525
1526 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1527 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1528 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1529 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001530 }
1531 }
1532 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001533
1534 if (!Cmp) {
1535 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1536 AArch64CC = changeIntCCToAArch64CC(CC);
1537 }
1538 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001539 return Cmp;
1540}
1541
1542static std::pair<SDValue, SDValue>
1543getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1544 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1545 "Unsupported value type");
1546 SDValue Value, Overflow;
1547 SDLoc DL(Op);
1548 SDValue LHS = Op.getOperand(0);
1549 SDValue RHS = Op.getOperand(1);
1550 unsigned Opc = 0;
1551 switch (Op.getOpcode()) {
1552 default:
1553 llvm_unreachable("Unknown overflow instruction!");
1554 case ISD::SADDO:
1555 Opc = AArch64ISD::ADDS;
1556 CC = AArch64CC::VS;
1557 break;
1558 case ISD::UADDO:
1559 Opc = AArch64ISD::ADDS;
1560 CC = AArch64CC::HS;
1561 break;
1562 case ISD::SSUBO:
1563 Opc = AArch64ISD::SUBS;
1564 CC = AArch64CC::VS;
1565 break;
1566 case ISD::USUBO:
1567 Opc = AArch64ISD::SUBS;
1568 CC = AArch64CC::LO;
1569 break;
1570 // Multiply needs a little bit extra work.
1571 case ISD::SMULO:
1572 case ISD::UMULO: {
1573 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001574 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001575 if (Op.getValueType() == MVT::i32) {
1576 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1577 // For a 32 bit multiply with overflow check we want the instruction
1578 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1579 // need to generate the following pattern:
1580 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1581 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1582 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1583 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1584 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001585 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001586 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1587 // operation. We need to clear out the upper 32 bits, because we used a
1588 // widening multiply that wrote all 64 bits. In the end this should be a
1589 // noop.
1590 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1591 if (IsSigned) {
1592 // The signed overflow check requires more than just a simple check for
1593 // any bit set in the upper 32 bits of the result. These bits could be
1594 // just the sign bits of a negative number. To perform the overflow
1595 // check we have to arithmetic shift right the 32nd bit of the result by
1596 // 31 bits. Then we compare the result to the upper 32 bits.
1597 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001598 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001599 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1600 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001601 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001602 // It is important that LowerBits is last, otherwise the arithmetic
1603 // shift will not be folded into the compare (SUBS).
1604 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1605 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1606 .getValue(1);
1607 } else {
1608 // The overflow check for unsigned multiply is easy. We only need to
1609 // check if any of the upper 32 bits are set. This can be done with a
1610 // CMP (shifted register). For that we need to generate the following
1611 // pattern:
1612 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1613 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001614 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001615 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1616 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001617 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1618 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001619 UpperBits).getValue(1);
1620 }
1621 break;
1622 }
1623 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1624 // For the 64 bit multiply
1625 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1626 if (IsSigned) {
1627 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1628 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001629 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001630 // It is important that LowerBits is last, otherwise the arithmetic
1631 // shift will not be folded into the compare (SUBS).
1632 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1633 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1634 .getValue(1);
1635 } else {
1636 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1637 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1638 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001639 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1640 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001641 UpperBits).getValue(1);
1642 }
1643 break;
1644 }
1645 } // switch (...)
1646
1647 if (Opc) {
1648 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1649
1650 // Emit the AArch64 operation with overflow check.
1651 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1652 Overflow = Value.getValue(1);
1653 }
1654 return std::make_pair(Value, Overflow);
1655}
1656
1657SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1658 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001659 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001660 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001661}
1662
1663static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1664 SDValue Sel = Op.getOperand(0);
1665 SDValue Other = Op.getOperand(1);
1666
1667 // If neither operand is a SELECT_CC, give up.
1668 if (Sel.getOpcode() != ISD::SELECT_CC)
1669 std::swap(Sel, Other);
1670 if (Sel.getOpcode() != ISD::SELECT_CC)
1671 return Op;
1672
1673 // The folding we want to perform is:
1674 // (xor x, (select_cc a, b, cc, 0, -1) )
1675 // -->
1676 // (csel x, (xor x, -1), cc ...)
1677 //
1678 // The latter will get matched to a CSINV instruction.
1679
1680 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1681 SDValue LHS = Sel.getOperand(0);
1682 SDValue RHS = Sel.getOperand(1);
1683 SDValue TVal = Sel.getOperand(2);
1684 SDValue FVal = Sel.getOperand(3);
1685 SDLoc dl(Sel);
1686
1687 // FIXME: This could be generalized to non-integer comparisons.
1688 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1689 return Op;
1690
1691 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1692 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1693
Eric Christopher572e03a2015-06-19 01:53:21 +00001694 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001695 if (!CFVal || !CTVal)
1696 return Op;
1697
1698 // We can commute the SELECT_CC by inverting the condition. This
1699 // might be needed to make this fit into a CSINV pattern.
1700 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1701 std::swap(TVal, FVal);
1702 std::swap(CTVal, CFVal);
1703 CC = ISD::getSetCCInverse(CC, true);
1704 }
1705
1706 // If the constants line up, perform the transform!
1707 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1708 SDValue CCVal;
1709 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1710
1711 FVal = Other;
1712 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001713 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001714
1715 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1716 CCVal, Cmp);
1717 }
1718
1719 return Op;
1720}
1721
1722static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1723 EVT VT = Op.getValueType();
1724
1725 // Let legalize expand this if it isn't a legal type yet.
1726 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1727 return SDValue();
1728
1729 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1730
1731 unsigned Opc;
1732 bool ExtraOp = false;
1733 switch (Op.getOpcode()) {
1734 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001735 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001736 case ISD::ADDC:
1737 Opc = AArch64ISD::ADDS;
1738 break;
1739 case ISD::SUBC:
1740 Opc = AArch64ISD::SUBS;
1741 break;
1742 case ISD::ADDE:
1743 Opc = AArch64ISD::ADCS;
1744 ExtraOp = true;
1745 break;
1746 case ISD::SUBE:
1747 Opc = AArch64ISD::SBCS;
1748 ExtraOp = true;
1749 break;
1750 }
1751
1752 if (!ExtraOp)
1753 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1754 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1755 Op.getOperand(2));
1756}
1757
1758static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1759 // Let legalize expand this if it isn't a legal type yet.
1760 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1761 return SDValue();
1762
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001763 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001764 AArch64CC::CondCode CC;
1765 // The actual operation that sets the overflow or carry flag.
1766 SDValue Value, Overflow;
1767 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1768
1769 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001770 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1771 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001772
1773 // We use an inverted condition, because the conditional select is inverted
1774 // too. This will allow it to be selected to a single instruction:
1775 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001776 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1777 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001778 CCVal, Overflow);
1779
1780 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001781 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001782}
1783
1784// Prefetch operands are:
1785// 1: Address to prefetch
1786// 2: bool isWrite
1787// 3: int locality (0 = no locality ... 3 = extreme locality)
1788// 4: bool isDataCache
1789static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1790 SDLoc DL(Op);
1791 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1792 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001793 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001794
1795 bool IsStream = !Locality;
1796 // When the locality number is set
1797 if (Locality) {
1798 // The front-end should have filtered out the out-of-range values
1799 assert(Locality <= 3 && "Prefetch locality out-of-range");
1800 // The locality degree is the opposite of the cache speed.
1801 // Put the number the other way around.
1802 // The encoding starts at 0 for level 1
1803 Locality = 3 - Locality;
1804 }
1805
1806 // built the mask value encoding the expected behavior.
1807 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001808 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001809 (Locality << 1) | // Cache level bits
1810 (unsigned)IsStream; // Stream bit
1811 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001812 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001813}
1814
1815SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1816 SelectionDAG &DAG) const {
1817 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1818
1819 RTLIB::Libcall LC;
1820 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1821
1822 return LowerF128Call(Op, DAG, LC);
1823}
1824
1825SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1826 SelectionDAG &DAG) const {
1827 if (Op.getOperand(0).getValueType() != MVT::f128) {
1828 // It's legal except when f128 is involved
1829 return Op;
1830 }
1831
1832 RTLIB::Libcall LC;
1833 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1834
1835 // FP_ROUND node has a second operand indicating whether it is known to be
1836 // precise. That doesn't take part in the LibCall so we can't directly use
1837 // LowerF128Call.
1838 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001839 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1840 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001841}
1842
1843static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1844 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1845 // Any additional optimization in this function should be recorded
1846 // in the cost tables.
1847 EVT InVT = Op.getOperand(0).getValueType();
1848 EVT VT = Op.getValueType();
1849
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001850 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001851 SDLoc dl(Op);
1852 SDValue Cv =
1853 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1854 Op.getOperand(0));
1855 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001856 }
1857
1858 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001859 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001860 MVT ExtVT =
1861 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1862 VT.getVectorNumElements());
1863 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001864 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1865 }
1866
1867 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001868 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001869}
1870
1871SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1872 SelectionDAG &DAG) const {
1873 if (Op.getOperand(0).getValueType().isVector())
1874 return LowerVectorFP_TO_INT(Op, DAG);
1875
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001876 // f16 conversions are promoted to f32.
1877 if (Op.getOperand(0).getValueType() == MVT::f16) {
1878 SDLoc dl(Op);
1879 return DAG.getNode(
1880 Op.getOpcode(), dl, Op.getValueType(),
1881 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1882 }
1883
Tim Northover3b0846e2014-05-24 12:50:23 +00001884 if (Op.getOperand(0).getValueType() != MVT::f128) {
1885 // It's legal except when f128 is involved
1886 return Op;
1887 }
1888
1889 RTLIB::Libcall LC;
1890 if (Op.getOpcode() == ISD::FP_TO_SINT)
1891 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1892 else
1893 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1894
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001895 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001896 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001897}
1898
1899static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1900 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1901 // Any additional optimization in this function should be recorded
1902 // in the cost tables.
1903 EVT VT = Op.getValueType();
1904 SDLoc dl(Op);
1905 SDValue In = Op.getOperand(0);
1906 EVT InVT = In.getValueType();
1907
Tim Northoveref0d7602014-06-15 09:27:06 +00001908 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1909 MVT CastVT =
1910 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1911 InVT.getVectorNumElements());
1912 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001913 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001914 }
1915
Tim Northoveref0d7602014-06-15 09:27:06 +00001916 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1917 unsigned CastOpc =
1918 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1919 EVT CastVT = VT.changeVectorElementTypeToInteger();
1920 In = DAG.getNode(CastOpc, dl, CastVT, In);
1921 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001922 }
1923
Tim Northoveref0d7602014-06-15 09:27:06 +00001924 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001925}
1926
1927SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1928 SelectionDAG &DAG) const {
1929 if (Op.getValueType().isVector())
1930 return LowerVectorINT_TO_FP(Op, DAG);
1931
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001932 // f16 conversions are promoted to f32.
1933 if (Op.getValueType() == MVT::f16) {
1934 SDLoc dl(Op);
1935 return DAG.getNode(
1936 ISD::FP_ROUND, dl, MVT::f16,
1937 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001938 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001939 }
1940
Tim Northover3b0846e2014-05-24 12:50:23 +00001941 // i128 conversions are libcalls.
1942 if (Op.getOperand(0).getValueType() == MVT::i128)
1943 return SDValue();
1944
1945 // Other conversions are legal, unless it's to the completely software-based
1946 // fp128.
1947 if (Op.getValueType() != MVT::f128)
1948 return Op;
1949
1950 RTLIB::Libcall LC;
1951 if (Op.getOpcode() == ISD::SINT_TO_FP)
1952 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1953 else
1954 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1955
1956 return LowerF128Call(Op, DAG, LC);
1957}
1958
1959SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1960 SelectionDAG &DAG) const {
1961 // For iOS, we want to call an alternative entry point: __sincos_stret,
1962 // which returns the values in two S / D registers.
1963 SDLoc dl(Op);
1964 SDValue Arg = Op.getOperand(0);
1965 EVT ArgVT = Arg.getValueType();
1966 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1967
1968 ArgListTy Args;
1969 ArgListEntry Entry;
1970
1971 Entry.Node = Arg;
1972 Entry.Ty = ArgTy;
1973 Entry.isSExt = false;
1974 Entry.isZExt = false;
1975 Args.push_back(Entry);
1976
1977 const char *LibcallName =
1978 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00001979 SDValue Callee =
1980 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001981
Reid Kleckner343c3952014-11-20 23:51:47 +00001982 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00001983 TargetLowering::CallLoweringInfo CLI(DAG);
1984 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00001985 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00001986
1987 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1988 return CallResult.first;
1989}
1990
Tim Northoverf8bfe212014-07-18 13:07:05 +00001991static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1992 if (Op.getValueType() != MVT::f16)
1993 return SDValue();
1994
1995 assert(Op.getOperand(0).getValueType() == MVT::i16);
1996 SDLoc DL(Op);
1997
1998 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1999 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2000 return SDValue(
2001 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002002 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002003 0);
2004}
2005
Chad Rosierd9d0f862014-10-08 02:31:24 +00002006static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2007 if (OrigVT.getSizeInBits() >= 64)
2008 return OrigVT;
2009
2010 assert(OrigVT.isSimple() && "Expecting a simple value type");
2011
2012 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2013 switch (OrigSimpleTy) {
2014 default: llvm_unreachable("Unexpected Vector Type");
2015 case MVT::v2i8:
2016 case MVT::v2i16:
2017 return MVT::v2i32;
2018 case MVT::v4i8:
2019 return MVT::v4i16;
2020 }
2021}
2022
2023static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2024 const EVT &OrigTy,
2025 const EVT &ExtTy,
2026 unsigned ExtOpcode) {
2027 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2028 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2029 // 64-bits we need to insert a new extension so that it will be 64-bits.
2030 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2031 if (OrigTy.getSizeInBits() >= 64)
2032 return N;
2033
2034 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2035 EVT NewVT = getExtensionTo64Bits(OrigTy);
2036
2037 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2038}
2039
2040static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2041 bool isSigned) {
2042 EVT VT = N->getValueType(0);
2043
2044 if (N->getOpcode() != ISD::BUILD_VECTOR)
2045 return false;
2046
Pete Cooper3af9a252015-06-26 18:17:36 +00002047 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2049 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2050 unsigned HalfSize = EltSize / 2;
2051 if (isSigned) {
2052 if (!isIntN(HalfSize, C->getSExtValue()))
2053 return false;
2054 } else {
2055 if (!isUIntN(HalfSize, C->getZExtValue()))
2056 return false;
2057 }
2058 continue;
2059 }
2060 return false;
2061 }
2062
2063 return true;
2064}
2065
2066static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2067 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2068 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2069 N->getOperand(0)->getValueType(0),
2070 N->getValueType(0),
2071 N->getOpcode());
2072
2073 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2074 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002075 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002076 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2077 unsigned NumElts = VT.getVectorNumElements();
2078 MVT TruncVT = MVT::getIntegerVT(EltSize);
2079 SmallVector<SDValue, 8> Ops;
2080 for (unsigned i = 0; i != NumElts; ++i) {
2081 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2082 const APInt &CInt = C->getAPIntValue();
2083 // Element types smaller than 32 bits are not legal, so use i32 elements.
2084 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002085 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002086 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002087 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002088 MVT::getVectorVT(TruncVT, NumElts), Ops);
2089}
2090
2091static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2092 if (N->getOpcode() == ISD::SIGN_EXTEND)
2093 return true;
2094 if (isExtendedBUILD_VECTOR(N, DAG, true))
2095 return true;
2096 return false;
2097}
2098
2099static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2100 if (N->getOpcode() == ISD::ZERO_EXTEND)
2101 return true;
2102 if (isExtendedBUILD_VECTOR(N, DAG, false))
2103 return true;
2104 return false;
2105}
2106
2107static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2108 unsigned Opcode = N->getOpcode();
2109 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2110 SDNode *N0 = N->getOperand(0).getNode();
2111 SDNode *N1 = N->getOperand(1).getNode();
2112 return N0->hasOneUse() && N1->hasOneUse() &&
2113 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2114 }
2115 return false;
2116}
2117
2118static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2119 unsigned Opcode = N->getOpcode();
2120 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2121 SDNode *N0 = N->getOperand(0).getNode();
2122 SDNode *N1 = N->getOperand(1).getNode();
2123 return N0->hasOneUse() && N1->hasOneUse() &&
2124 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2125 }
2126 return false;
2127}
2128
2129static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2130 // Multiplications are only custom-lowered for 128-bit vectors so that
2131 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2132 EVT VT = Op.getValueType();
2133 assert(VT.is128BitVector() && VT.isInteger() &&
2134 "unexpected type for custom-lowering ISD::MUL");
2135 SDNode *N0 = Op.getOperand(0).getNode();
2136 SDNode *N1 = Op.getOperand(1).getNode();
2137 unsigned NewOpc = 0;
2138 bool isMLA = false;
2139 bool isN0SExt = isSignExtended(N0, DAG);
2140 bool isN1SExt = isSignExtended(N1, DAG);
2141 if (isN0SExt && isN1SExt)
2142 NewOpc = AArch64ISD::SMULL;
2143 else {
2144 bool isN0ZExt = isZeroExtended(N0, DAG);
2145 bool isN1ZExt = isZeroExtended(N1, DAG);
2146 if (isN0ZExt && isN1ZExt)
2147 NewOpc = AArch64ISD::UMULL;
2148 else if (isN1SExt || isN1ZExt) {
2149 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2150 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2151 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2152 NewOpc = AArch64ISD::SMULL;
2153 isMLA = true;
2154 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2155 NewOpc = AArch64ISD::UMULL;
2156 isMLA = true;
2157 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2158 std::swap(N0, N1);
2159 NewOpc = AArch64ISD::UMULL;
2160 isMLA = true;
2161 }
2162 }
2163
2164 if (!NewOpc) {
2165 if (VT == MVT::v2i64)
2166 // Fall through to expand this. It is not legal.
2167 return SDValue();
2168 else
2169 // Other vector multiplications are legal.
2170 return Op;
2171 }
2172 }
2173
2174 // Legalize to a S/UMULL instruction
2175 SDLoc DL(Op);
2176 SDValue Op0;
2177 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2178 if (!isMLA) {
2179 Op0 = skipExtensionForVectorMULL(N0, DAG);
2180 assert(Op0.getValueType().is64BitVector() &&
2181 Op1.getValueType().is64BitVector() &&
2182 "unexpected types for extended operands to VMULL");
2183 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2184 }
2185 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2186 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2187 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2188 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2189 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2190 EVT Op1VT = Op1.getValueType();
2191 return DAG.getNode(N0->getOpcode(), DL, VT,
2192 DAG.getNode(NewOpc, DL, VT,
2193 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2194 DAG.getNode(NewOpc, DL, VT,
2195 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2196}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002197
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002198SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2199 SelectionDAG &DAG) const {
2200 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2201 SDLoc dl(Op);
2202 switch (IntNo) {
2203 default: return SDValue(); // Don't custom lower most intrinsics.
2204 case Intrinsic::aarch64_thread_pointer: {
2205 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2206 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2207 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002208 case Intrinsic::aarch64_neon_smax:
2209 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2210 Op.getOperand(1), Op.getOperand(2));
2211 case Intrinsic::aarch64_neon_umax:
2212 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2213 Op.getOperand(1), Op.getOperand(2));
2214 case Intrinsic::aarch64_neon_smin:
2215 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2216 Op.getOperand(1), Op.getOperand(2));
2217 case Intrinsic::aarch64_neon_umin:
2218 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2219 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002220 }
2221}
2222
Tim Northover3b0846e2014-05-24 12:50:23 +00002223SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2224 SelectionDAG &DAG) const {
2225 switch (Op.getOpcode()) {
2226 default:
2227 llvm_unreachable("unimplemented operand");
2228 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002229 case ISD::BITCAST:
2230 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002231 case ISD::GlobalAddress:
2232 return LowerGlobalAddress(Op, DAG);
2233 case ISD::GlobalTLSAddress:
2234 return LowerGlobalTLSAddress(Op, DAG);
2235 case ISD::SETCC:
2236 return LowerSETCC(Op, DAG);
2237 case ISD::BR_CC:
2238 return LowerBR_CC(Op, DAG);
2239 case ISD::SELECT:
2240 return LowerSELECT(Op, DAG);
2241 case ISD::SELECT_CC:
2242 return LowerSELECT_CC(Op, DAG);
2243 case ISD::JumpTable:
2244 return LowerJumpTable(Op, DAG);
2245 case ISD::ConstantPool:
2246 return LowerConstantPool(Op, DAG);
2247 case ISD::BlockAddress:
2248 return LowerBlockAddress(Op, DAG);
2249 case ISD::VASTART:
2250 return LowerVASTART(Op, DAG);
2251 case ISD::VACOPY:
2252 return LowerVACOPY(Op, DAG);
2253 case ISD::VAARG:
2254 return LowerVAARG(Op, DAG);
2255 case ISD::ADDC:
2256 case ISD::ADDE:
2257 case ISD::SUBC:
2258 case ISD::SUBE:
2259 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2260 case ISD::SADDO:
2261 case ISD::UADDO:
2262 case ISD::SSUBO:
2263 case ISD::USUBO:
2264 case ISD::SMULO:
2265 case ISD::UMULO:
2266 return LowerXALUO(Op, DAG);
2267 case ISD::FADD:
2268 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2269 case ISD::FSUB:
2270 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2271 case ISD::FMUL:
2272 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2273 case ISD::FDIV:
2274 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2275 case ISD::FP_ROUND:
2276 return LowerFP_ROUND(Op, DAG);
2277 case ISD::FP_EXTEND:
2278 return LowerFP_EXTEND(Op, DAG);
2279 case ISD::FRAMEADDR:
2280 return LowerFRAMEADDR(Op, DAG);
2281 case ISD::RETURNADDR:
2282 return LowerRETURNADDR(Op, DAG);
2283 case ISD::INSERT_VECTOR_ELT:
2284 return LowerINSERT_VECTOR_ELT(Op, DAG);
2285 case ISD::EXTRACT_VECTOR_ELT:
2286 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2287 case ISD::BUILD_VECTOR:
2288 return LowerBUILD_VECTOR(Op, DAG);
2289 case ISD::VECTOR_SHUFFLE:
2290 return LowerVECTOR_SHUFFLE(Op, DAG);
2291 case ISD::EXTRACT_SUBVECTOR:
2292 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2293 case ISD::SRA:
2294 case ISD::SRL:
2295 case ISD::SHL:
2296 return LowerVectorSRA_SRL_SHL(Op, DAG);
2297 case ISD::SHL_PARTS:
2298 return LowerShiftLeftParts(Op, DAG);
2299 case ISD::SRL_PARTS:
2300 case ISD::SRA_PARTS:
2301 return LowerShiftRightParts(Op, DAG);
2302 case ISD::CTPOP:
2303 return LowerCTPOP(Op, DAG);
2304 case ISD::FCOPYSIGN:
2305 return LowerFCOPYSIGN(Op, DAG);
2306 case ISD::AND:
2307 return LowerVectorAND(Op, DAG);
2308 case ISD::OR:
2309 return LowerVectorOR(Op, DAG);
2310 case ISD::XOR:
2311 return LowerXOR(Op, DAG);
2312 case ISD::PREFETCH:
2313 return LowerPREFETCH(Op, DAG);
2314 case ISD::SINT_TO_FP:
2315 case ISD::UINT_TO_FP:
2316 return LowerINT_TO_FP(Op, DAG);
2317 case ISD::FP_TO_SINT:
2318 case ISD::FP_TO_UINT:
2319 return LowerFP_TO_INT(Op, DAG);
2320 case ISD::FSINCOS:
2321 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002322 case ISD::MUL:
2323 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002324 case ISD::INTRINSIC_WO_CHAIN:
2325 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002326 }
2327}
2328
2329/// getFunctionAlignment - Return the Log2 alignment of this function.
2330unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2331 return 2;
2332}
2333
2334//===----------------------------------------------------------------------===//
2335// Calling Convention Implementation
2336//===----------------------------------------------------------------------===//
2337
2338#include "AArch64GenCallingConv.inc"
2339
Robin Morisset039781e2014-08-29 21:53:01 +00002340/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002341CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2342 bool IsVarArg) const {
2343 switch (CC) {
2344 default:
2345 llvm_unreachable("Unsupported calling convention.");
2346 case CallingConv::WebKit_JS:
2347 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002348 case CallingConv::GHC:
2349 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002350 case CallingConv::C:
2351 case CallingConv::Fast:
2352 if (!Subtarget->isTargetDarwin())
2353 return CC_AArch64_AAPCS;
2354 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2355 }
2356}
2357
2358SDValue AArch64TargetLowering::LowerFormalArguments(
2359 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2360 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2361 SmallVectorImpl<SDValue> &InVals) const {
2362 MachineFunction &MF = DAG.getMachineFunction();
2363 MachineFrameInfo *MFI = MF.getFrameInfo();
2364
2365 // Assign locations to all of the incoming arguments.
2366 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002367 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2368 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002369
2370 // At this point, Ins[].VT may already be promoted to i32. To correctly
2371 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2372 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2373 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2374 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2375 // LocVT.
2376 unsigned NumArgs = Ins.size();
2377 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2378 unsigned CurArgIdx = 0;
2379 for (unsigned i = 0; i != NumArgs; ++i) {
2380 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002381 if (Ins[i].isOrigArg()) {
2382 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2383 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002384
Andrew Trick05938a52015-02-16 18:10:47 +00002385 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002386 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2387 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002388 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2389 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2390 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2391 ValVT = MVT::i8;
2392 else if (ActualMVT == MVT::i16)
2393 ValVT = MVT::i16;
2394 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002395 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2396 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002397 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002398 assert(!Res && "Call operand has unhandled type");
2399 (void)Res;
2400 }
2401 assert(ArgLocs.size() == Ins.size());
2402 SmallVector<SDValue, 16> ArgValues;
2403 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2404 CCValAssign &VA = ArgLocs[i];
2405
2406 if (Ins[i].Flags.isByVal()) {
2407 // Byval is used for HFAs in the PCS, but the system should work in a
2408 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002409 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002410 int Size = Ins[i].Flags.getByValSize();
2411 unsigned NumRegs = (Size + 7) / 8;
2412
2413 // FIXME: This works on big-endian for composite byvals, which are the common
2414 // case. It should also work for fundamental types too.
2415 unsigned FrameIdx =
2416 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002417 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002418 InVals.push_back(FrameIdxN);
2419
2420 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002421 }
2422
2423 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002424 // Arguments stored in registers.
2425 EVT RegVT = VA.getLocVT();
2426
2427 SDValue ArgValue;
2428 const TargetRegisterClass *RC;
2429
2430 if (RegVT == MVT::i32)
2431 RC = &AArch64::GPR32RegClass;
2432 else if (RegVT == MVT::i64)
2433 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002434 else if (RegVT == MVT::f16)
2435 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002436 else if (RegVT == MVT::f32)
2437 RC = &AArch64::FPR32RegClass;
2438 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2439 RC = &AArch64::FPR64RegClass;
2440 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2441 RC = &AArch64::FPR128RegClass;
2442 else
2443 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2444
2445 // Transform the arguments in physical registers into virtual ones.
2446 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2447 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2448
2449 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2450 // to 64 bits. Insert an assert[sz]ext to capture this, then
2451 // truncate to the right size.
2452 switch (VA.getLocInfo()) {
2453 default:
2454 llvm_unreachable("Unknown loc info!");
2455 case CCValAssign::Full:
2456 break;
2457 case CCValAssign::BCvt:
2458 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2459 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002460 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002461 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002462 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002463 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2464 // nodes after our lowering.
2465 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002466 break;
2467 }
2468
2469 InVals.push_back(ArgValue);
2470
2471 } else { // VA.isRegLoc()
2472 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2473 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002474 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002475
2476 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002477 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2478 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002479 BEAlign = 8 - ArgSize;
2480
2481 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2482
2483 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002484 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002485 SDValue ArgValue;
2486
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002487 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002488 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002489 MVT MemVT = VA.getValVT();
2490
Tim Northover47e003c2014-05-26 17:21:53 +00002491 switch (VA.getLocInfo()) {
2492 default:
2493 break;
Tim Northover6890add2014-06-03 13:54:53 +00002494 case CCValAssign::BCvt:
2495 MemVT = VA.getLocVT();
2496 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002497 case CCValAssign::SExt:
2498 ExtType = ISD::SEXTLOAD;
2499 break;
2500 case CCValAssign::ZExt:
2501 ExtType = ISD::ZEXTLOAD;
2502 break;
2503 case CCValAssign::AExt:
2504 ExtType = ISD::EXTLOAD;
2505 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002506 }
2507
Alex Lorenze40c8a22015-08-11 23:09:45 +00002508 ArgValue = DAG.getExtLoad(
2509 ExtType, DL, VA.getLocVT(), Chain, FIN,
2510 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2511 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002512
Tim Northover3b0846e2014-05-24 12:50:23 +00002513 InVals.push_back(ArgValue);
2514 }
2515 }
2516
2517 // varargs
2518 if (isVarArg) {
2519 if (!Subtarget->isTargetDarwin()) {
2520 // The AAPCS variadic function ABI is identical to the non-variadic
2521 // one. As a result there may be more arguments in registers and we should
2522 // save them for future reference.
2523 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2524 }
2525
2526 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2527 // This will point to the next argument passed via stack.
2528 unsigned StackOffset = CCInfo.getNextStackOffset();
2529 // We currently pass all varargs at 8-byte alignment.
2530 StackOffset = ((StackOffset + 7) & ~7);
2531 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2532 }
2533
2534 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2535 unsigned StackArgSize = CCInfo.getNextStackOffset();
2536 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2537 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2538 // This is a non-standard ABI so by fiat I say we're allowed to make full
2539 // use of the stack area to be popped, which must be aligned to 16 bytes in
2540 // any case:
2541 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2542
2543 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2544 // a multiple of 16.
2545 FuncInfo->setArgumentStackToRestore(StackArgSize);
2546
2547 // This realignment carries over to the available bytes below. Our own
2548 // callers will guarantee the space is free by giving an aligned value to
2549 // CALLSEQ_START.
2550 }
2551 // Even if we're not expected to free up the space, it's useful to know how
2552 // much is there while considering tail calls (because we can reuse it).
2553 FuncInfo->setBytesInStackArgArea(StackArgSize);
2554
2555 return Chain;
2556}
2557
2558void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2559 SelectionDAG &DAG, SDLoc DL,
2560 SDValue &Chain) const {
2561 MachineFunction &MF = DAG.getMachineFunction();
2562 MachineFrameInfo *MFI = MF.getFrameInfo();
2563 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002564 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002565
2566 SmallVector<SDValue, 8> MemOps;
2567
2568 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2569 AArch64::X3, AArch64::X4, AArch64::X5,
2570 AArch64::X6, AArch64::X7 };
2571 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002572 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002573
2574 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2575 int GPRIdx = 0;
2576 if (GPRSaveSize != 0) {
2577 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2578
Mehdi Amini44ede332015-07-09 02:09:04 +00002579 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002580
2581 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2582 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2583 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002584 SDValue Store = DAG.getStore(
2585 Val.getValue(1), DL, Val, FIN,
2586 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2587 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002588 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002589 FIN =
2590 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002591 }
2592 }
2593 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2594 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2595
2596 if (Subtarget->hasFPARMv8()) {
2597 static const MCPhysReg FPRArgRegs[] = {
2598 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2599 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2600 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002601 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002602
2603 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2604 int FPRIdx = 0;
2605 if (FPRSaveSize != 0) {
2606 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2607
Mehdi Amini44ede332015-07-09 02:09:04 +00002608 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002609
2610 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2611 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2612 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2613
Alex Lorenze40c8a22015-08-11 23:09:45 +00002614 SDValue Store = DAG.getStore(
2615 Val.getValue(1), DL, Val, FIN,
2616 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2617 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002618 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002619 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2620 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002621 }
2622 }
2623 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2624 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2625 }
2626
2627 if (!MemOps.empty()) {
2628 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2629 }
2630}
2631
2632/// LowerCallResult - Lower the result values of a call into the
2633/// appropriate copies out of appropriate physical registers.
2634SDValue AArch64TargetLowering::LowerCallResult(
2635 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2636 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2637 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2638 SDValue ThisVal) const {
2639 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2640 ? RetCC_AArch64_WebKit_JS
2641 : RetCC_AArch64_AAPCS;
2642 // Assign locations to each value returned by this call.
2643 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002644 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2645 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002646 CCInfo.AnalyzeCallResult(Ins, RetCC);
2647
2648 // Copy all of the result registers out of their specified physreg.
2649 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2650 CCValAssign VA = RVLocs[i];
2651
2652 // Pass 'this' value directly from the argument to return value, to avoid
2653 // reg unit interference
2654 if (i == 0 && isThisReturn) {
2655 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2656 "unexpected return calling convention register assignment");
2657 InVals.push_back(ThisVal);
2658 continue;
2659 }
2660
2661 SDValue Val =
2662 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2663 Chain = Val.getValue(1);
2664 InFlag = Val.getValue(2);
2665
2666 switch (VA.getLocInfo()) {
2667 default:
2668 llvm_unreachable("Unknown loc info!");
2669 case CCValAssign::Full:
2670 break;
2671 case CCValAssign::BCvt:
2672 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2673 break;
2674 }
2675
2676 InVals.push_back(Val);
2677 }
2678
2679 return Chain;
2680}
2681
2682bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2683 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2684 bool isCalleeStructRet, bool isCallerStructRet,
2685 const SmallVectorImpl<ISD::OutputArg> &Outs,
2686 const SmallVectorImpl<SDValue> &OutVals,
2687 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2688 // For CallingConv::C this function knows whether the ABI needs
2689 // changing. That's not true for other conventions so they will have to opt in
2690 // manually.
2691 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2692 return false;
2693
2694 const MachineFunction &MF = DAG.getMachineFunction();
2695 const Function *CallerF = MF.getFunction();
2696 CallingConv::ID CallerCC = CallerF->getCallingConv();
2697 bool CCMatch = CallerCC == CalleeCC;
2698
2699 // Byval parameters hand the function a pointer directly into the stack area
2700 // we want to reuse during a tail call. Working around this *is* possible (see
2701 // X86) but less efficient and uglier in LowerCall.
2702 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2703 e = CallerF->arg_end();
2704 i != e; ++i)
2705 if (i->hasByValAttr())
2706 return false;
2707
2708 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2709 if (IsTailCallConvention(CalleeCC) && CCMatch)
2710 return true;
2711 return false;
2712 }
2713
Oliver Stannard12993dd2014-08-18 12:42:15 +00002714 // Externally-defined functions with weak linkage should not be
2715 // tail-called on AArch64 when the OS does not support dynamic
2716 // pre-emption of symbols, as the AAELF spec requires normal calls
2717 // to undefined weak functions to be replaced with a NOP or jump to the
2718 // next instruction. The behaviour of branch instructions in this
2719 // situation (as used for tail calls) is implementation-defined, so we
2720 // cannot rely on the linker replacing the tail call with a return.
2721 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2722 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002723 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002724 if (GV->hasExternalWeakLinkage() &&
2725 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002726 return false;
2727 }
2728
Tim Northover3b0846e2014-05-24 12:50:23 +00002729 // Now we search for cases where we can use a tail call without changing the
2730 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2731 // concept.
2732
2733 // I want anyone implementing a new calling convention to think long and hard
2734 // about this assert.
2735 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2736 "Unexpected variadic calling convention");
2737
2738 if (isVarArg && !Outs.empty()) {
2739 // At least two cases here: if caller is fastcc then we can't have any
2740 // memory arguments (we'd be expected to clean up the stack afterwards). If
2741 // caller is C then we could potentially use its argument area.
2742
2743 // FIXME: for now we take the most conservative of these in both cases:
2744 // disallow all variadic memory operands.
2745 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002746 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2747 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002748
2749 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002750 for (const CCValAssign &ArgLoc : ArgLocs)
2751 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002752 return false;
2753 }
2754
2755 // If the calling conventions do not match, then we'd better make sure the
2756 // results are returned in the same way as what the caller expects.
2757 if (!CCMatch) {
2758 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002759 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2760 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002761 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2762
2763 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002764 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2765 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002766 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2767
2768 if (RVLocs1.size() != RVLocs2.size())
2769 return false;
2770 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2771 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2772 return false;
2773 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2774 return false;
2775 if (RVLocs1[i].isRegLoc()) {
2776 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2777 return false;
2778 } else {
2779 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2780 return false;
2781 }
2782 }
2783 }
2784
2785 // Nothing more to check if the callee is taking no arguments
2786 if (Outs.empty())
2787 return true;
2788
2789 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002790 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2791 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002792
2793 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2794
2795 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2796
2797 // If the stack arguments for this call would fit into our own save area then
2798 // the call can be made tail.
2799 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2800}
2801
2802SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2803 SelectionDAG &DAG,
2804 MachineFrameInfo *MFI,
2805 int ClobberedFI) const {
2806 SmallVector<SDValue, 8> ArgChains;
2807 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2808 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2809
2810 // Include the original chain at the beginning of the list. When this is
2811 // used by target LowerCall hooks, this helps legalize find the
2812 // CALLSEQ_BEGIN node.
2813 ArgChains.push_back(Chain);
2814
2815 // Add a chain value for each stack argument corresponding
2816 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2817 UE = DAG.getEntryNode().getNode()->use_end();
2818 U != UE; ++U)
2819 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2820 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2821 if (FI->getIndex() < 0) {
2822 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2823 int64_t InLastByte = InFirstByte;
2824 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2825
2826 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2827 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2828 ArgChains.push_back(SDValue(L, 1));
2829 }
2830
2831 // Build a tokenfactor for all the chains.
2832 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2833}
2834
2835bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2836 bool TailCallOpt) const {
2837 return CallCC == CallingConv::Fast && TailCallOpt;
2838}
2839
2840bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2841 return CallCC == CallingConv::Fast;
2842}
2843
2844/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2845/// and add input and output parameter nodes.
2846SDValue
2847AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2848 SmallVectorImpl<SDValue> &InVals) const {
2849 SelectionDAG &DAG = CLI.DAG;
2850 SDLoc &DL = CLI.DL;
2851 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2852 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2853 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2854 SDValue Chain = CLI.Chain;
2855 SDValue Callee = CLI.Callee;
2856 bool &IsTailCall = CLI.IsTailCall;
2857 CallingConv::ID CallConv = CLI.CallConv;
2858 bool IsVarArg = CLI.IsVarArg;
2859
2860 MachineFunction &MF = DAG.getMachineFunction();
2861 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2862 bool IsThisReturn = false;
2863
2864 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2865 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2866 bool IsSibCall = false;
2867
2868 if (IsTailCall) {
2869 // Check if it's really possible to do a tail call.
2870 IsTailCall = isEligibleForTailCallOptimization(
2871 Callee, CallConv, IsVarArg, IsStructRet,
2872 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2873 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2874 report_fatal_error("failed to perform tail call elimination on a call "
2875 "site marked musttail");
2876
2877 // A sibling call is one where we're under the usual C ABI and not planning
2878 // to change that but can still do a tail call:
2879 if (!TailCallOpt && IsTailCall)
2880 IsSibCall = true;
2881
2882 if (IsTailCall)
2883 ++NumTailCalls;
2884 }
2885
2886 // Analyze operands of the call, assigning locations to each operand.
2887 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002888 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2889 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002890
2891 if (IsVarArg) {
2892 // Handle fixed and variable vector arguments differently.
2893 // Variable vector arguments always go into memory.
2894 unsigned NumArgs = Outs.size();
2895
2896 for (unsigned i = 0; i != NumArgs; ++i) {
2897 MVT ArgVT = Outs[i].VT;
2898 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2899 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2900 /*IsVarArg=*/ !Outs[i].IsFixed);
2901 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2902 assert(!Res && "Call operand has unhandled type");
2903 (void)Res;
2904 }
2905 } else {
2906 // At this point, Outs[].VT may already be promoted to i32. To correctly
2907 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2908 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2909 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2910 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2911 // LocVT.
2912 unsigned NumArgs = Outs.size();
2913 for (unsigned i = 0; i != NumArgs; ++i) {
2914 MVT ValVT = Outs[i].VT;
2915 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002916 EVT ActualVT = getValueType(DAG.getDataLayout(),
2917 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002918 /*AllowUnknown*/ true);
2919 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2920 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2921 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002922 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002923 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002924 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002925 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002926
2927 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002928 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002929 assert(!Res && "Call operand has unhandled type");
2930 (void)Res;
2931 }
2932 }
2933
2934 // Get a count of how many bytes are to be pushed on the stack.
2935 unsigned NumBytes = CCInfo.getNextStackOffset();
2936
2937 if (IsSibCall) {
2938 // Since we're not changing the ABI to make this a tail call, the memory
2939 // operands are already available in the caller's incoming argument space.
2940 NumBytes = 0;
2941 }
2942
2943 // FPDiff is the byte offset of the call's argument area from the callee's.
2944 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2945 // by this amount for a tail call. In a sibling call it must be 0 because the
2946 // caller will deallocate the entire stack and the callee still expects its
2947 // arguments to begin at SP+0. Completely unused for non-tail calls.
2948 int FPDiff = 0;
2949
2950 if (IsTailCall && !IsSibCall) {
2951 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2952
2953 // Since callee will pop argument stack as a tail call, we must keep the
2954 // popped size 16-byte aligned.
2955 NumBytes = RoundUpToAlignment(NumBytes, 16);
2956
2957 // FPDiff will be negative if this tail call requires more space than we
2958 // would automatically have in our incoming argument space. Positive if we
2959 // can actually shrink the stack.
2960 FPDiff = NumReusableBytes - NumBytes;
2961
2962 // The stack pointer must be 16-byte aligned at all times it's used for a
2963 // memory operation, which in practice means at *all* times and in
2964 // particular across call boundaries. Therefore our own arguments started at
2965 // a 16-byte aligned SP and the delta applied for the tail call should
2966 // satisfy the same constraint.
2967 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2968 }
2969
2970 // Adjust the stack pointer for the new arguments...
2971 // These operations are automatically eliminated by the prolog/epilog pass
2972 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002973 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2974 true),
2975 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002976
Mehdi Amini44ede332015-07-09 02:09:04 +00002977 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2978 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002979
2980 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2981 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00002982 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002983
2984 // Walk the register/memloc assignments, inserting copies/loads.
2985 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2986 ++i, ++realArgIdx) {
2987 CCValAssign &VA = ArgLocs[i];
2988 SDValue Arg = OutVals[realArgIdx];
2989 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2990
2991 // Promote the value if needed.
2992 switch (VA.getLocInfo()) {
2993 default:
2994 llvm_unreachable("Unknown loc info!");
2995 case CCValAssign::Full:
2996 break;
2997 case CCValAssign::SExt:
2998 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2999 break;
3000 case CCValAssign::ZExt:
3001 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3002 break;
3003 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003004 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3005 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3006 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3007 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3008 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003009 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3010 break;
3011 case CCValAssign::BCvt:
3012 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3013 break;
3014 case CCValAssign::FPExt:
3015 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3016 break;
3017 }
3018
3019 if (VA.isRegLoc()) {
3020 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3021 assert(VA.getLocVT() == MVT::i64 &&
3022 "unexpected calling convention register assignment");
3023 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3024 "unexpected use of 'returned'");
3025 IsThisReturn = true;
3026 }
3027 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3028 } else {
3029 assert(VA.isMemLoc());
3030
3031 SDValue DstAddr;
3032 MachinePointerInfo DstInfo;
3033
3034 // FIXME: This works on big-endian for composite byvals, which are the
3035 // common case. It should also work for fundamental types too.
3036 uint32_t BEAlign = 0;
3037 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003038 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003039 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003040 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3041 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003042 if (OpSize < 8)
3043 BEAlign = 8 - OpSize;
3044 }
3045 unsigned LocMemOffset = VA.getLocMemOffset();
3046 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003047 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003048 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003049
3050 if (IsTailCall) {
3051 Offset = Offset + FPDiff;
3052 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3053
Mehdi Amini44ede332015-07-09 02:09:04 +00003054 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003055 DstInfo =
3056 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003057
3058 // Make sure any stack arguments overlapping with where we're storing
3059 // are loaded before this eventual operation. Otherwise they'll be
3060 // clobbered.
3061 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3062 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003063 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003064
Mehdi Amini44ede332015-07-09 02:09:04 +00003065 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003066 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3067 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003068 }
3069
3070 if (Outs[i].Flags.isByVal()) {
3071 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003072 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003073 SDValue Cpy = DAG.getMemcpy(
3074 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003075 /*isVol = */ false, /*AlwaysInline = */ false,
3076 /*isTailCall = */ false,
3077 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003078
3079 MemOpChains.push_back(Cpy);
3080 } else {
3081 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3082 // promoted to a legal register type i32, we should truncate Arg back to
3083 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003084 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3085 VA.getValVT() == MVT::i16)
3086 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003087
3088 SDValue Store =
3089 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3090 MemOpChains.push_back(Store);
3091 }
3092 }
3093 }
3094
3095 if (!MemOpChains.empty())
3096 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3097
3098 // Build a sequence of copy-to-reg nodes chained together with token chain
3099 // and flag operands which copy the outgoing args into the appropriate regs.
3100 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003101 for (auto &RegToPass : RegsToPass) {
3102 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3103 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003104 InFlag = Chain.getValue(1);
3105 }
3106
3107 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3108 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3109 // node so that legalize doesn't hack it.
3110 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3111 Subtarget->isTargetMachO()) {
3112 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3113 const GlobalValue *GV = G->getGlobal();
3114 bool InternalLinkage = GV->hasInternalLinkage();
3115 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003116 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003117 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003118 Callee =
3119 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3120 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003121 }
3122 } else if (ExternalSymbolSDNode *S =
3123 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3124 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003125 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3126 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003127 }
3128 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3129 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003130 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003131 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3132 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003133 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003134 }
3135
3136 // We don't usually want to end the call-sequence here because we would tidy
3137 // the frame up *after* the call, however in the ABI-changing tail-call case
3138 // we've carefully laid out the parameters so that when sp is reset they'll be
3139 // in the correct location.
3140 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003141 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3142 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003143 InFlag = Chain.getValue(1);
3144 }
3145
3146 std::vector<SDValue> Ops;
3147 Ops.push_back(Chain);
3148 Ops.push_back(Callee);
3149
3150 if (IsTailCall) {
3151 // Each tail call may have to adjust the stack by a different amount, so
3152 // this information must travel along with the operation for eventual
3153 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003154 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003155 }
3156
3157 // Add argument registers to the end of the list so that they are known live
3158 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003159 for (auto &RegToPass : RegsToPass)
3160 Ops.push_back(DAG.getRegister(RegToPass.first,
3161 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003162
3163 // Add a register mask operand representing the call-preserved registers.
3164 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003165 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003166 if (IsThisReturn) {
3167 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003168 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003169 if (!Mask) {
3170 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003171 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003172 }
3173 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003174 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003175
3176 assert(Mask && "Missing call preserved mask for calling convention");
3177 Ops.push_back(DAG.getRegisterMask(Mask));
3178
3179 if (InFlag.getNode())
3180 Ops.push_back(InFlag);
3181
3182 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3183
3184 // If we're doing a tall call, use a TC_RETURN here rather than an
3185 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003186 if (IsTailCall) {
3187 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003188 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003189 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003190
3191 // Returns a chain and a flag for retval copy to use.
3192 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3193 InFlag = Chain.getValue(1);
3194
3195 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3196 ? RoundUpToAlignment(NumBytes, 16)
3197 : 0;
3198
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003199 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3200 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003201 InFlag, DL);
3202 if (!Ins.empty())
3203 InFlag = Chain.getValue(1);
3204
3205 // Handle result values, copying them out of physregs into vregs that we
3206 // return.
3207 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3208 InVals, IsThisReturn,
3209 IsThisReturn ? OutVals[0] : SDValue());
3210}
3211
3212bool AArch64TargetLowering::CanLowerReturn(
3213 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3214 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3215 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3216 ? RetCC_AArch64_WebKit_JS
3217 : RetCC_AArch64_AAPCS;
3218 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003219 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003220 return CCInfo.CheckReturn(Outs, RetCC);
3221}
3222
3223SDValue
3224AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3225 bool isVarArg,
3226 const SmallVectorImpl<ISD::OutputArg> &Outs,
3227 const SmallVectorImpl<SDValue> &OutVals,
3228 SDLoc DL, SelectionDAG &DAG) const {
3229 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3230 ? RetCC_AArch64_WebKit_JS
3231 : RetCC_AArch64_AAPCS;
3232 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003233 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3234 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003235 CCInfo.AnalyzeReturn(Outs, RetCC);
3236
3237 // Copy the result values into the output registers.
3238 SDValue Flag;
3239 SmallVector<SDValue, 4> RetOps(1, Chain);
3240 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3241 ++i, ++realRVLocIdx) {
3242 CCValAssign &VA = RVLocs[i];
3243 assert(VA.isRegLoc() && "Can only return in registers!");
3244 SDValue Arg = OutVals[realRVLocIdx];
3245
3246 switch (VA.getLocInfo()) {
3247 default:
3248 llvm_unreachable("Unknown loc info!");
3249 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003250 if (Outs[i].ArgVT == MVT::i1) {
3251 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3252 // value. This is strictly redundant on Darwin (which uses "zeroext
3253 // i1"), but will be optimised out before ISel.
3254 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3255 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3256 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003257 break;
3258 case CCValAssign::BCvt:
3259 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3260 break;
3261 }
3262
3263 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3264 Flag = Chain.getValue(1);
3265 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3266 }
3267
3268 RetOps[0] = Chain; // Update chain.
3269
3270 // Add the flag if we have it.
3271 if (Flag.getNode())
3272 RetOps.push_back(Flag);
3273
3274 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3275}
3276
3277//===----------------------------------------------------------------------===//
3278// Other Lowering Code
3279//===----------------------------------------------------------------------===//
3280
3281SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3282 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003283 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003284 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003285 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3286 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003287 unsigned char OpFlags =
3288 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3289
3290 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3291 "unexpected offset in global node");
3292
3293 // This also catched the large code model case for Darwin.
3294 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3295 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3296 // FIXME: Once remat is capable of dealing with instructions with register
3297 // operands, expand this into two nodes instead of using a wrapper node.
3298 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3299 }
3300
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003301 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3302 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3303 "use of MO_CONSTPOOL only supported on small model");
3304 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3305 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3306 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3307 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3308 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003309 SDValue GlobalAddr = DAG.getLoad(
3310 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3311 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3312 /*isVolatile=*/false,
3313 /*isNonTemporal=*/true,
3314 /*isInvariant=*/true, 8);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003315 if (GN->getOffset() != 0)
3316 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003317 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003318 return GlobalAddr;
3319 }
3320
Tim Northover3b0846e2014-05-24 12:50:23 +00003321 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3322 const unsigned char MO_NC = AArch64II::MO_NC;
3323 return DAG.getNode(
3324 AArch64ISD::WrapperLarge, DL, PtrVT,
3325 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3326 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3327 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3328 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3329 } else {
3330 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3331 // the only correct model on Darwin.
3332 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3333 OpFlags | AArch64II::MO_PAGE);
3334 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3335 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3336
3337 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3338 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3339 }
3340}
3341
3342/// \brief Convert a TLS address reference into the correct sequence of loads
3343/// and calls to compute the variable's address (for Darwin, currently) and
3344/// return an SDValue containing the final node.
3345
3346/// Darwin only has one TLS scheme which must be capable of dealing with the
3347/// fully general situation, in the worst case. This means:
3348/// + "extern __thread" declaration.
3349/// + Defined in a possibly unknown dynamic library.
3350///
3351/// The general system is that each __thread variable has a [3 x i64] descriptor
3352/// which contains information used by the runtime to calculate the address. The
3353/// only part of this the compiler needs to know about is the first xword, which
3354/// contains a function pointer that must be called with the address of the
3355/// entire descriptor in "x0".
3356///
3357/// Since this descriptor may be in a different unit, in general even the
3358/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3359/// is:
3360/// adrp x0, _var@TLVPPAGE
3361/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3362/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3363/// ; the function pointer
3364/// blr x1 ; Uses descriptor address in x0
3365/// ; Address of _var is now in x0.
3366///
3367/// If the address of _var's descriptor *is* known to the linker, then it can
3368/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3369/// a slight efficiency gain.
3370SDValue
3371AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3372 SelectionDAG &DAG) const {
3373 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3374
3375 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003376 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003377 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3378
3379 SDValue TLVPAddr =
3380 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3381 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3382
3383 // The first entry in the descriptor is a function pointer that we must call
3384 // to obtain the address of the variable.
3385 SDValue Chain = DAG.getEntryNode();
3386 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003387 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3388 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3389 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003390 Chain = FuncTLVGet.getValue(1);
3391
3392 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3393 MFI->setAdjustsStack(true);
3394
3395 // TLS calls preserve all registers except those that absolutely must be
3396 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3397 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003398 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003399 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003400
3401 // Finally, we can make the call. This is just a degenerate version of a
3402 // normal AArch64 call node: x0 takes the address of the descriptor, and
3403 // returns the address of the variable in this thread.
3404 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3405 Chain =
3406 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3407 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3408 DAG.getRegisterMask(Mask), Chain.getValue(1));
3409 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3410}
3411
3412/// When accessing thread-local variables under either the general-dynamic or
3413/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3414/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003415/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003416///
Kristof Beylsaea84612015-03-04 09:12:08 +00003417/// The sequence is:
3418/// adrp x0, :tlsdesc:var
3419/// ldr x1, [x0, #:tlsdesc_lo12:var]
3420/// add x0, x0, #:tlsdesc_lo12:var
3421/// .tlsdesccall var
3422/// blr x1
3423/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003424///
Kristof Beylsaea84612015-03-04 09:12:08 +00003425/// The above sequence must be produced unscheduled, to enable the linker to
3426/// optimize/relax this sequence.
3427/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3428/// above sequence, and expanded really late in the compilation flow, to ensure
3429/// the sequence is produced as per above.
3430SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3431 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003432 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003433
Kristof Beylsaea84612015-03-04 09:12:08 +00003434 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003435 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003436
3437 SmallVector<SDValue, 2> Ops;
3438 Ops.push_back(Chain);
3439 Ops.push_back(SymAddr);
3440
3441 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3442 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003443
3444 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3445}
3446
3447SDValue
3448AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3449 SelectionDAG &DAG) const {
3450 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3451 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3452 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003453 // Different choices can be made for the maximum size of the TLS area for a
3454 // module. For the small address model, the default TLS size is 16MiB and the
3455 // maximum TLS size is 4GiB.
3456 // FIXME: add -mtls-size command line option and make it control the 16MiB
3457 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003458 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3459
3460 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003461
3462 if (DAG.getTarget().Options.EmulatedTLS)
3463 return LowerToTLSEmulatedModel(GA, DAG);
3464
Kristof Beylsaea84612015-03-04 09:12:08 +00003465 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3466 if (Model == TLSModel::LocalDynamic)
3467 Model = TLSModel::GeneralDynamic;
3468 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003469
3470 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003471 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003472 SDLoc DL(Op);
3473 const GlobalValue *GV = GA->getGlobal();
3474
3475 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3476
3477 if (Model == TLSModel::LocalExec) {
3478 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003479 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003480 SDValue LoVar = DAG.getTargetGlobalAddress(
3481 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003482 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003483
Kristof Beylsaea84612015-03-04 09:12:08 +00003484 SDValue TPWithOff_lo =
3485 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003486 HiVar,
3487 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003488 0);
3489 SDValue TPWithOff =
3490 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003491 LoVar,
3492 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003493 0);
3494 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003495 } else if (Model == TLSModel::InitialExec) {
3496 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3497 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3498 } else if (Model == TLSModel::LocalDynamic) {
3499 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3500 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3501 // the beginning of the module's TLS region, followed by a DTPREL offset
3502 // calculation.
3503
3504 // These accesses will need deduplicating if there's more than one.
3505 AArch64FunctionInfo *MFI =
3506 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3507 MFI->incNumLocalDynamicTLSAccesses();
3508
Tim Northover3b0846e2014-05-24 12:50:23 +00003509 // The call needs a relocation too for linker relaxation. It doesn't make
3510 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3511 // the address.
3512 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3513 AArch64II::MO_TLS);
3514
3515 // Now we can calculate the offset from TPIDR_EL0 to this module's
3516 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003517 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003518
3519 // Now use :dtprel_whatever: operations to calculate this variable's offset
3520 // in its thread-storage area.
3521 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003522 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003523 SDValue LoVar = DAG.getTargetGlobalAddress(
3524 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003525 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3526
Kristof Beylsaea84612015-03-04 09:12:08 +00003527 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003528 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003529 0);
3530 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003531 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003532 0);
3533 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003534 // The call needs a relocation too for linker relaxation. It doesn't make
3535 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3536 // the address.
3537 SDValue SymAddr =
3538 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3539
3540 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003541 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003542 } else
3543 llvm_unreachable("Unsupported ELF TLS access model");
3544
3545 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3546}
3547
3548SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3549 SelectionDAG &DAG) const {
3550 if (Subtarget->isTargetDarwin())
3551 return LowerDarwinGlobalTLSAddress(Op, DAG);
3552 else if (Subtarget->isTargetELF())
3553 return LowerELFGlobalTLSAddress(Op, DAG);
3554
3555 llvm_unreachable("Unexpected platform trying to use TLS");
3556}
3557SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3558 SDValue Chain = Op.getOperand(0);
3559 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3560 SDValue LHS = Op.getOperand(2);
3561 SDValue RHS = Op.getOperand(3);
3562 SDValue Dest = Op.getOperand(4);
3563 SDLoc dl(Op);
3564
3565 // Handle f128 first, since lowering it will result in comparing the return
3566 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3567 // is expecting to deal with.
3568 if (LHS.getValueType() == MVT::f128) {
3569 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3570
3571 // If softenSetCCOperands returned a scalar, we need to compare the result
3572 // against zero to select between true and false values.
3573 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003574 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003575 CC = ISD::SETNE;
3576 }
3577 }
3578
3579 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3580 // instruction.
3581 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003582 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003583 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3584 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3585 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3586 "Unexpected condition code.");
3587 // Only lower legal XALUO ops.
3588 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3589 return SDValue();
3590
3591 // The actual operation with overflow check.
3592 AArch64CC::CondCode OFCC;
3593 SDValue Value, Overflow;
3594 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3595
3596 if (CC == ISD::SETNE)
3597 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003598 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003599
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003600 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3601 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003602 }
3603
3604 if (LHS.getValueType().isInteger()) {
3605 assert((LHS.getValueType() == RHS.getValueType()) &&
3606 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3607
3608 // If the RHS of the comparison is zero, we can potentially fold this
3609 // to a specialized branch.
3610 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3611 if (RHSC && RHSC->getZExtValue() == 0) {
3612 if (CC == ISD::SETEQ) {
3613 // See if we can use a TBZ to fold in an AND as well.
3614 // TBZ has a smaller branch displacement than CBZ. If the offset is
3615 // out of bounds, a late MI-layer pass rewrites branches.
3616 // 403.gcc is an example that hits this case.
3617 if (LHS.getOpcode() == ISD::AND &&
3618 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3619 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3620 SDValue Test = LHS.getOperand(0);
3621 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003622 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003623 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3624 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003625 }
3626
3627 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3628 } else if (CC == ISD::SETNE) {
3629 // See if we can use a TBZ to fold in an AND as well.
3630 // TBZ has a smaller branch displacement than CBZ. If the offset is
3631 // out of bounds, a late MI-layer pass rewrites branches.
3632 // 403.gcc is an example that hits this case.
3633 if (LHS.getOpcode() == ISD::AND &&
3634 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3635 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3636 SDValue Test = LHS.getOperand(0);
3637 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003638 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003639 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3640 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003641 }
3642
3643 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003644 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3645 // Don't combine AND since emitComparison converts the AND to an ANDS
3646 // (a.k.a. TST) and the test in the test bit and branch instruction
3647 // becomes redundant. This would also increase register pressure.
3648 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3649 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003650 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003651 }
3652 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003653 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3654 LHS.getOpcode() != ISD::AND) {
3655 // Don't combine AND since emitComparison converts the AND to an ANDS
3656 // (a.k.a. TST) and the test in the test bit and branch instruction
3657 // becomes redundant. This would also increase register pressure.
3658 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3659 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003660 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003661 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003662
3663 SDValue CCVal;
3664 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3665 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3666 Cmp);
3667 }
3668
3669 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3670
3671 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3672 // clean. Some of them require two branches to implement.
3673 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3674 AArch64CC::CondCode CC1, CC2;
3675 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003676 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003677 SDValue BR1 =
3678 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3679 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003680 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003681 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3682 Cmp);
3683 }
3684
3685 return BR1;
3686}
3687
3688SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3689 SelectionDAG &DAG) const {
3690 EVT VT = Op.getValueType();
3691 SDLoc DL(Op);
3692
3693 SDValue In1 = Op.getOperand(0);
3694 SDValue In2 = Op.getOperand(1);
3695 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003696
3697 if (SrcVT.bitsLT(VT))
3698 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3699 else if (SrcVT.bitsGT(VT))
3700 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003701
3702 EVT VecVT;
3703 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003704 uint64_t EltMask;
3705 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003706 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3707 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003708 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003709 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003710
3711 if (!VT.isVector()) {
3712 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3713 DAG.getUNDEF(VecVT), In1);
3714 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3715 DAG.getUNDEF(VecVT), In2);
3716 } else {
3717 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3718 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3719 }
3720 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3721 EltVT = MVT::i64;
3722 VecVT = MVT::v2i64;
3723
Eric Christopher572e03a2015-06-19 01:53:21 +00003724 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003725 // immediate moves cannot materialize that in a single instruction for
3726 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003727 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003728
3729 if (!VT.isVector()) {
3730 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3731 DAG.getUNDEF(VecVT), In1);
3732 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3733 DAG.getUNDEF(VecVT), In2);
3734 } else {
3735 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3736 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3737 }
3738 } else {
3739 llvm_unreachable("Invalid type for copysign!");
3740 }
3741
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003742 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003743
3744 // If we couldn't materialize the mask above, then the mask vector will be
3745 // the zero vector, and we need to negate it here.
3746 if (VT == MVT::f64 || VT == MVT::v2f64) {
3747 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3748 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3749 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3750 }
3751
3752 SDValue Sel =
3753 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3754
3755 if (VT == MVT::f32)
3756 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3757 else if (VT == MVT::f64)
3758 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3759 else
3760 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3761}
3762
3763SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003764 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3765 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003766 return SDValue();
3767
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003768 if (!Subtarget->hasNEON())
3769 return SDValue();
3770
Tim Northover3b0846e2014-05-24 12:50:23 +00003771 // While there is no integer popcount instruction, it can
3772 // be more efficiently lowered to the following sequence that uses
3773 // AdvSIMD registers/instructions as long as the copies to/from
3774 // the AdvSIMD registers are cheap.
3775 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3776 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3777 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3778 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3779 SDValue Val = Op.getOperand(0);
3780 SDLoc DL(Op);
3781 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003782
Hao Liue0335d72015-01-30 02:13:53 +00003783 if (VT == MVT::i32)
3784 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3785 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003786
Hao Liue0335d72015-01-30 02:13:53 +00003787 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003788 SDValue UaddLV = DAG.getNode(
3789 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003790 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003791
3792 if (VT == MVT::i64)
3793 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3794 return UaddLV;
3795}
3796
3797SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3798
3799 if (Op.getValueType().isVector())
3800 return LowerVSETCC(Op, DAG);
3801
3802 SDValue LHS = Op.getOperand(0);
3803 SDValue RHS = Op.getOperand(1);
3804 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3805 SDLoc dl(Op);
3806
3807 // We chose ZeroOrOneBooleanContents, so use zero and one.
3808 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003809 SDValue TVal = DAG.getConstant(1, dl, VT);
3810 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003811
3812 // Handle f128 first, since one possible outcome is a normal integer
3813 // comparison which gets picked up by the next if statement.
3814 if (LHS.getValueType() == MVT::f128) {
3815 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3816
3817 // If softenSetCCOperands returned a scalar, use it.
3818 if (!RHS.getNode()) {
3819 assert(LHS.getValueType() == Op.getValueType() &&
3820 "Unexpected setcc expansion!");
3821 return LHS;
3822 }
3823 }
3824
3825 if (LHS.getValueType().isInteger()) {
3826 SDValue CCVal;
3827 SDValue Cmp =
3828 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3829
3830 // Note that we inverted the condition above, so we reverse the order of
3831 // the true and false operands here. This will allow the setcc to be
3832 // matched to a single CSINC instruction.
3833 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3834 }
3835
3836 // Now we know we're dealing with FP values.
3837 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3838
3839 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3840 // and do the comparison.
3841 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3842
3843 AArch64CC::CondCode CC1, CC2;
3844 changeFPCCToAArch64CC(CC, CC1, CC2);
3845 if (CC2 == AArch64CC::AL) {
3846 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003847 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003848
3849 // Note that we inverted the condition above, so we reverse the order of
3850 // the true and false operands here. This will allow the setcc to be
3851 // matched to a single CSINC instruction.
3852 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3853 } else {
3854 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3855 // totally clean. Some of them require two CSELs to implement. As is in
3856 // this case, we emit the first CSEL and then emit a second using the output
3857 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3858
3859 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003860 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003861 SDValue CS1 =
3862 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3863
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003864 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003865 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3866 }
3867}
3868
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003869SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3870 SDValue RHS, SDValue TVal,
3871 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003872 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003873 // Handle f128 first, because it will result in a comparison of some RTLIB
3874 // call result against zero.
3875 if (LHS.getValueType() == MVT::f128) {
3876 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3877
3878 // If softenSetCCOperands returned a scalar, we need to compare the result
3879 // against zero to select between true and false values.
3880 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003881 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003882 CC = ISD::SETNE;
3883 }
3884 }
3885
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003886 // Also handle f16, for which we need to do a f32 comparison.
3887 if (LHS.getValueType() == MVT::f16) {
3888 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3889 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3890 }
3891
3892 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003893 if (LHS.getValueType().isInteger()) {
3894 assert((LHS.getValueType() == RHS.getValueType()) &&
3895 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3896
3897 unsigned Opcode = AArch64ISD::CSEL;
3898
3899 // If both the TVal and the FVal are constants, see if we can swap them in
3900 // order to for a CSINV or CSINC out of them.
3901 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3902 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3903
3904 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3905 std::swap(TVal, FVal);
3906 std::swap(CTVal, CFVal);
3907 CC = ISD::getSetCCInverse(CC, true);
3908 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3909 std::swap(TVal, FVal);
3910 std::swap(CTVal, CFVal);
3911 CC = ISD::getSetCCInverse(CC, true);
3912 } else if (TVal.getOpcode() == ISD::XOR) {
3913 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3914 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003915 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003916 std::swap(TVal, FVal);
3917 std::swap(CTVal, CFVal);
3918 CC = ISD::getSetCCInverse(CC, true);
3919 }
3920 } else if (TVal.getOpcode() == ISD::SUB) {
3921 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3922 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003923 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003924 std::swap(TVal, FVal);
3925 std::swap(CTVal, CFVal);
3926 CC = ISD::getSetCCInverse(CC, true);
3927 }
3928 } else if (CTVal && CFVal) {
3929 const int64_t TrueVal = CTVal->getSExtValue();
3930 const int64_t FalseVal = CFVal->getSExtValue();
3931 bool Swap = false;
3932
3933 // If both TVal and FVal are constants, see if FVal is the
3934 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3935 // instead of a CSEL in that case.
3936 if (TrueVal == ~FalseVal) {
3937 Opcode = AArch64ISD::CSINV;
3938 } else if (TrueVal == -FalseVal) {
3939 Opcode = AArch64ISD::CSNEG;
3940 } else if (TVal.getValueType() == MVT::i32) {
3941 // If our operands are only 32-bit wide, make sure we use 32-bit
3942 // arithmetic for the check whether we can use CSINC. This ensures that
3943 // the addition in the check will wrap around properly in case there is
3944 // an overflow (which would not be the case if we do the check with
3945 // 64-bit arithmetic).
3946 const uint32_t TrueVal32 = CTVal->getZExtValue();
3947 const uint32_t FalseVal32 = CFVal->getZExtValue();
3948
3949 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3950 Opcode = AArch64ISD::CSINC;
3951
3952 if (TrueVal32 > FalseVal32) {
3953 Swap = true;
3954 }
3955 }
3956 // 64-bit check whether we can use CSINC.
3957 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3958 Opcode = AArch64ISD::CSINC;
3959
3960 if (TrueVal > FalseVal) {
3961 Swap = true;
3962 }
3963 }
3964
3965 // Swap TVal and FVal if necessary.
3966 if (Swap) {
3967 std::swap(TVal, FVal);
3968 std::swap(CTVal, CFVal);
3969 CC = ISD::getSetCCInverse(CC, true);
3970 }
3971
3972 if (Opcode != AArch64ISD::CSEL) {
3973 // Drop FVal since we can get its value by simply inverting/negating
3974 // TVal.
3975 FVal = TVal;
3976 }
3977 }
3978
3979 SDValue CCVal;
3980 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3981
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003982 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003983 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3984 }
3985
3986 // Now we know we're dealing with FP values.
3987 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3988 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003989 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003990 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3991
3992 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3993 // clean. Some of them require two CSELs to implement.
3994 AArch64CC::CondCode CC1, CC2;
3995 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003996 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003997 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3998
3999 // If we need a second CSEL, emit it, using the output of the first as the
4000 // RHS. We're effectively OR'ing the two CC's together.
4001 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004002 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004003 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4004 }
4005
4006 // Otherwise, return the output of the first CSEL.
4007 return CS1;
4008}
4009
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004010SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4011 SelectionDAG &DAG) const {
4012 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4013 SDValue LHS = Op.getOperand(0);
4014 SDValue RHS = Op.getOperand(1);
4015 SDValue TVal = Op.getOperand(2);
4016 SDValue FVal = Op.getOperand(3);
4017 SDLoc DL(Op);
4018 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4019}
4020
4021SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4022 SelectionDAG &DAG) const {
4023 SDValue CCVal = Op->getOperand(0);
4024 SDValue TVal = Op->getOperand(1);
4025 SDValue FVal = Op->getOperand(2);
4026 SDLoc DL(Op);
4027
4028 unsigned Opc = CCVal.getOpcode();
4029 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4030 // instruction.
4031 if (CCVal.getResNo() == 1 &&
4032 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4033 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4034 // Only lower legal XALUO ops.
4035 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4036 return SDValue();
4037
4038 AArch64CC::CondCode OFCC;
4039 SDValue Value, Overflow;
4040 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004041 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004042
4043 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4044 CCVal, Overflow);
4045 }
4046
4047 // Lower it the same way as we would lower a SELECT_CC node.
4048 ISD::CondCode CC;
4049 SDValue LHS, RHS;
4050 if (CCVal.getOpcode() == ISD::SETCC) {
4051 LHS = CCVal.getOperand(0);
4052 RHS = CCVal.getOperand(1);
4053 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4054 } else {
4055 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004056 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004057 CC = ISD::SETNE;
4058 }
4059 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4060}
4061
Tim Northover3b0846e2014-05-24 12:50:23 +00004062SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4063 SelectionDAG &DAG) const {
4064 // Jump table entries as PC relative offsets. No additional tweaking
4065 // is necessary here. Just get the address of the jump table.
4066 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004067 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004068 SDLoc DL(Op);
4069
4070 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4071 !Subtarget->isTargetMachO()) {
4072 const unsigned char MO_NC = AArch64II::MO_NC;
4073 return DAG.getNode(
4074 AArch64ISD::WrapperLarge, DL, PtrVT,
4075 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4076 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4077 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4078 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4079 AArch64II::MO_G0 | MO_NC));
4080 }
4081
4082 SDValue Hi =
4083 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4084 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4085 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4086 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4087 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4088}
4089
4090SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4091 SelectionDAG &DAG) const {
4092 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004093 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004094 SDLoc DL(Op);
4095
4096 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4097 // Use the GOT for the large code model on iOS.
4098 if (Subtarget->isTargetMachO()) {
4099 SDValue GotAddr = DAG.getTargetConstantPool(
4100 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4101 AArch64II::MO_GOT);
4102 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4103 }
4104
4105 const unsigned char MO_NC = AArch64II::MO_NC;
4106 return DAG.getNode(
4107 AArch64ISD::WrapperLarge, DL, PtrVT,
4108 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4109 CP->getOffset(), AArch64II::MO_G3),
4110 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4111 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4112 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4113 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4114 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4115 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4116 } else {
4117 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4118 // ELF, the only valid one on Darwin.
4119 SDValue Hi =
4120 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4121 CP->getOffset(), AArch64II::MO_PAGE);
4122 SDValue Lo = DAG.getTargetConstantPool(
4123 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4124 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4125
4126 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4127 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4128 }
4129}
4130
4131SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4132 SelectionDAG &DAG) const {
4133 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004134 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004135 SDLoc DL(Op);
4136 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4137 !Subtarget->isTargetMachO()) {
4138 const unsigned char MO_NC = AArch64II::MO_NC;
4139 return DAG.getNode(
4140 AArch64ISD::WrapperLarge, DL, PtrVT,
4141 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4142 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4143 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4144 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4145 } else {
4146 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4147 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4148 AArch64II::MO_NC);
4149 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4150 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4151 }
4152}
4153
4154SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4155 SelectionDAG &DAG) const {
4156 AArch64FunctionInfo *FuncInfo =
4157 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4158
4159 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004160 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4161 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004162 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4163 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4164 MachinePointerInfo(SV), false, false, 0);
4165}
4166
4167SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4168 SelectionDAG &DAG) const {
4169 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4170 // Standard, section B.3.
4171 MachineFunction &MF = DAG.getMachineFunction();
4172 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004173 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004174 SDLoc DL(Op);
4175
4176 SDValue Chain = Op.getOperand(0);
4177 SDValue VAList = Op.getOperand(1);
4178 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4179 SmallVector<SDValue, 4> MemOps;
4180
4181 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004182 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004183 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4184 MachinePointerInfo(SV), false, false, 8));
4185
4186 // void *__gr_top at offset 8
4187 int GPRSize = FuncInfo->getVarArgsGPRSize();
4188 if (GPRSize > 0) {
4189 SDValue GRTop, GRTopAddr;
4190
Mehdi Amini44ede332015-07-09 02:09:04 +00004191 GRTopAddr =
4192 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004193
Mehdi Amini44ede332015-07-09 02:09:04 +00004194 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4195 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4196 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004197
4198 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4199 MachinePointerInfo(SV, 8), false, false, 8));
4200 }
4201
4202 // void *__vr_top at offset 16
4203 int FPRSize = FuncInfo->getVarArgsFPRSize();
4204 if (FPRSize > 0) {
4205 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004206 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4207 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004208
Mehdi Amini44ede332015-07-09 02:09:04 +00004209 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4210 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4211 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004212
4213 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4214 MachinePointerInfo(SV, 16), false, false, 8));
4215 }
4216
4217 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004218 SDValue GROffsAddr =
4219 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004220 MemOps.push_back(DAG.getStore(Chain, DL,
4221 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004222 GROffsAddr, MachinePointerInfo(SV, 24), false,
4223 false, 4));
4224
4225 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004226 SDValue VROffsAddr =
4227 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004228 MemOps.push_back(DAG.getStore(Chain, DL,
4229 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004230 VROffsAddr, MachinePointerInfo(SV, 28), false,
4231 false, 4));
4232
4233 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4234}
4235
4236SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4237 SelectionDAG &DAG) const {
4238 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4239 : LowerAAPCS_VASTART(Op, DAG);
4240}
4241
4242SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4243 SelectionDAG &DAG) const {
4244 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4245 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004246 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004247 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4248 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4249 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4250
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004251 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4252 Op.getOperand(2),
4253 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004254 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004255 MachinePointerInfo(SrcSV));
4256}
4257
4258SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4259 assert(Subtarget->isTargetDarwin() &&
4260 "automatic va_arg instruction only works on Darwin");
4261
4262 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4263 EVT VT = Op.getValueType();
4264 SDLoc DL(Op);
4265 SDValue Chain = Op.getOperand(0);
4266 SDValue Addr = Op.getOperand(1);
4267 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004268 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004269
Mehdi Amini44ede332015-07-09 02:09:04 +00004270 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4271 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004272 Chain = VAList.getValue(1);
4273
4274 if (Align > 8) {
4275 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004276 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4277 DAG.getConstant(Align - 1, DL, PtrVT));
4278 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4279 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004280 }
4281
4282 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004283 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004284
4285 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4286 // up to 64 bits. At the very least, we have to increase the striding of the
4287 // vaargs list to match this, and for FP values we need to introduce
4288 // FP_ROUND nodes as well.
4289 if (VT.isInteger() && !VT.isVector())
4290 ArgSize = 8;
4291 bool NeedFPTrunc = false;
4292 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4293 ArgSize = 8;
4294 NeedFPTrunc = true;
4295 }
4296
4297 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004298 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4299 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004300 // Store the incremented VAList to the legalized pointer
4301 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4302 false, false, 0);
4303
4304 // Load the actual argument out of the pointer VAList
4305 if (NeedFPTrunc) {
4306 // Load the value as an f64.
4307 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4308 MachinePointerInfo(), false, false, false, 0);
4309 // Round the value down to an f32.
4310 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004311 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004312 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4313 // Merge the rounded value with the chain output of the load.
4314 return DAG.getMergeValues(Ops, DL);
4315 }
4316
4317 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4318 false, false, 0);
4319}
4320
4321SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4322 SelectionDAG &DAG) const {
4323 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4324 MFI->setFrameAddressIsTaken(true);
4325
4326 EVT VT = Op.getValueType();
4327 SDLoc DL(Op);
4328 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4329 SDValue FrameAddr =
4330 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4331 while (Depth--)
4332 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4333 MachinePointerInfo(), false, false, false, 0);
4334 return FrameAddr;
4335}
4336
4337// FIXME? Maybe this could be a TableGen attribute on some registers and
4338// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004339unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4340 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004341 unsigned Reg = StringSwitch<unsigned>(RegName)
4342 .Case("sp", AArch64::SP)
4343 .Default(0);
4344 if (Reg)
4345 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004346 report_fatal_error(Twine("Invalid register name \""
4347 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004348}
4349
4350SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4351 SelectionDAG &DAG) const {
4352 MachineFunction &MF = DAG.getMachineFunction();
4353 MachineFrameInfo *MFI = MF.getFrameInfo();
4354 MFI->setReturnAddressIsTaken(true);
4355
4356 EVT VT = Op.getValueType();
4357 SDLoc DL(Op);
4358 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4359 if (Depth) {
4360 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004361 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004362 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4363 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4364 MachinePointerInfo(), false, false, false, 0);
4365 }
4366
4367 // Return LR, which contains the return address. Mark it an implicit live-in.
4368 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4369 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4370}
4371
4372/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4373/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4374SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4375 SelectionDAG &DAG) const {
4376 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4377 EVT VT = Op.getValueType();
4378 unsigned VTBits = VT.getSizeInBits();
4379 SDLoc dl(Op);
4380 SDValue ShOpLo = Op.getOperand(0);
4381 SDValue ShOpHi = Op.getOperand(1);
4382 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004383 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4384
4385 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4386
4387 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004388 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004389 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4390
4391 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4392 // is "undef". We wanted 0, so CSEL it directly.
4393 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4394 ISD::SETEQ, dl, DAG);
4395 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4396 HiBitsForLo =
4397 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4398 HiBitsForLo, CCVal, Cmp);
4399
Tim Northover3b0846e2014-05-24 12:50:23 +00004400 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004401 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004402
Tim Northoverf3be9d52015-12-02 00:33:54 +00004403 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4404 SDValue LoForNormalShift =
4405 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004406
Tim Northoverf3be9d52015-12-02 00:33:54 +00004407 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4408 dl, DAG);
4409 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4410 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4411 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4412 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004413
4414 // AArch64 shifts larger than the register width are wrapped rather than
4415 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004416 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4417 SDValue HiForBigShift =
4418 Opc == ISD::SRA
4419 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4420 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4421 : DAG.getConstant(0, dl, VT);
4422 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4423 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004424
4425 SDValue Ops[2] = { Lo, Hi };
4426 return DAG.getMergeValues(Ops, dl);
4427}
4428
Tim Northoverf3be9d52015-12-02 00:33:54 +00004429
Tim Northover3b0846e2014-05-24 12:50:23 +00004430/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4431/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4432SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004433 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004434 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4435 EVT VT = Op.getValueType();
4436 unsigned VTBits = VT.getSizeInBits();
4437 SDLoc dl(Op);
4438 SDValue ShOpLo = Op.getOperand(0);
4439 SDValue ShOpHi = Op.getOperand(1);
4440 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004441
4442 assert(Op.getOpcode() == ISD::SHL_PARTS);
4443 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004444 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004445 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4446
4447 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4448 // is "undef". We wanted 0, so CSEL it directly.
4449 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4450 ISD::SETEQ, dl, DAG);
4451 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4452 LoBitsForHi =
4453 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4454 LoBitsForHi, CCVal, Cmp);
4455
Tim Northover3b0846e2014-05-24 12:50:23 +00004456 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004457 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004458 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4459 SDValue HiForNormalShift =
4460 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004461
Tim Northoverf3be9d52015-12-02 00:33:54 +00004462 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004463
Tim Northoverf3be9d52015-12-02 00:33:54 +00004464 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4465 dl, DAG);
4466 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4467 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4468 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004469
4470 // AArch64 shifts of larger than register sizes are wrapped rather than
4471 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004472 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4473 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4474 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4475 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004476
4477 SDValue Ops[2] = { Lo, Hi };
4478 return DAG.getMergeValues(Ops, dl);
4479}
4480
4481bool AArch64TargetLowering::isOffsetFoldingLegal(
4482 const GlobalAddressSDNode *GA) const {
4483 // The AArch64 target doesn't support folding offsets into global addresses.
4484 return false;
4485}
4486
4487bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4488 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4489 // FIXME: We should be able to handle f128 as well with a clever lowering.
4490 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4491 return true;
4492
4493 if (VT == MVT::f64)
4494 return AArch64_AM::getFP64Imm(Imm) != -1;
4495 else if (VT == MVT::f32)
4496 return AArch64_AM::getFP32Imm(Imm) != -1;
4497 return false;
4498}
4499
4500//===----------------------------------------------------------------------===//
4501// AArch64 Optimization Hooks
4502//===----------------------------------------------------------------------===//
4503
4504//===----------------------------------------------------------------------===//
4505// AArch64 Inline Assembly Support
4506//===----------------------------------------------------------------------===//
4507
4508// Table of Constraints
4509// TODO: This is the current set of constraints supported by ARM for the
4510// compiler, not all of them may make sense, e.g. S may be difficult to support.
4511//
4512// r - A general register
4513// w - An FP/SIMD register of some size in the range v0-v31
4514// x - An FP/SIMD register of some size in the range v0-v15
4515// I - Constant that can be used with an ADD instruction
4516// J - Constant that can be used with a SUB instruction
4517// K - Constant that can be used with a 32-bit logical instruction
4518// L - Constant that can be used with a 64-bit logical instruction
4519// M - Constant that can be used as a 32-bit MOV immediate
4520// N - Constant that can be used as a 64-bit MOV immediate
4521// Q - A memory reference with base register and no offset
4522// S - A symbolic address
4523// Y - Floating point constant zero
4524// Z - Integer constant zero
4525//
4526// Note that general register operands will be output using their 64-bit x
4527// register name, whatever the size of the variable, unless the asm operand
4528// is prefixed by the %w modifier. Floating-point and SIMD register operands
4529// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4530// %q modifier.
4531
4532/// getConstraintType - Given a constraint letter, return the type of
4533/// constraint it is for this target.
4534AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004535AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004536 if (Constraint.size() == 1) {
4537 switch (Constraint[0]) {
4538 default:
4539 break;
4540 case 'z':
4541 return C_Other;
4542 case 'x':
4543 case 'w':
4544 return C_RegisterClass;
4545 // An address with a single base register. Due to the way we
4546 // currently handle addresses it is the same as 'r'.
4547 case 'Q':
4548 return C_Memory;
4549 }
4550 }
4551 return TargetLowering::getConstraintType(Constraint);
4552}
4553
4554/// Examine constraint type and operand type and determine a weight value.
4555/// This object must already have been set up with the operand type
4556/// and the current alternative constraint selected.
4557TargetLowering::ConstraintWeight
4558AArch64TargetLowering::getSingleConstraintMatchWeight(
4559 AsmOperandInfo &info, const char *constraint) const {
4560 ConstraintWeight weight = CW_Invalid;
4561 Value *CallOperandVal = info.CallOperandVal;
4562 // If we don't have a value, we can't do a match,
4563 // but allow it at the lowest weight.
4564 if (!CallOperandVal)
4565 return CW_Default;
4566 Type *type = CallOperandVal->getType();
4567 // Look at the constraint type.
4568 switch (*constraint) {
4569 default:
4570 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4571 break;
4572 case 'x':
4573 case 'w':
4574 if (type->isFloatingPointTy() || type->isVectorTy())
4575 weight = CW_Register;
4576 break;
4577 case 'z':
4578 weight = CW_Constant;
4579 break;
4580 }
4581 return weight;
4582}
4583
4584std::pair<unsigned, const TargetRegisterClass *>
4585AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004586 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004587 if (Constraint.size() == 1) {
4588 switch (Constraint[0]) {
4589 case 'r':
4590 if (VT.getSizeInBits() == 64)
4591 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4592 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4593 case 'w':
4594 if (VT == MVT::f32)
4595 return std::make_pair(0U, &AArch64::FPR32RegClass);
4596 if (VT.getSizeInBits() == 64)
4597 return std::make_pair(0U, &AArch64::FPR64RegClass);
4598 if (VT.getSizeInBits() == 128)
4599 return std::make_pair(0U, &AArch64::FPR128RegClass);
4600 break;
4601 // The instructions that this constraint is designed for can
4602 // only take 128-bit registers so just use that regclass.
4603 case 'x':
4604 if (VT.getSizeInBits() == 128)
4605 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4606 break;
4607 }
4608 }
4609 if (StringRef("{cc}").equals_lower(Constraint))
4610 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4611
4612 // Use the default implementation in TargetLowering to convert the register
4613 // constraint into a member of a register class.
4614 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004615 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004616
4617 // Not found as a standard register?
4618 if (!Res.second) {
4619 unsigned Size = Constraint.size();
4620 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4621 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004622 int RegNo;
4623 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4624 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004625 // v0 - v31 are aliases of q0 - q31.
4626 // By default we'll emit v0-v31 for this unless there's a modifier where
4627 // we'll emit the correct register as well.
4628 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4629 Res.second = &AArch64::FPR128RegClass;
4630 }
4631 }
4632 }
4633
4634 return Res;
4635}
4636
4637/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4638/// vector. If it is invalid, don't add anything to Ops.
4639void AArch64TargetLowering::LowerAsmOperandForConstraint(
4640 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4641 SelectionDAG &DAG) const {
4642 SDValue Result;
4643
4644 // Currently only support length 1 constraints.
4645 if (Constraint.length() != 1)
4646 return;
4647
4648 char ConstraintLetter = Constraint[0];
4649 switch (ConstraintLetter) {
4650 default:
4651 break;
4652
4653 // This set of constraints deal with valid constants for various instructions.
4654 // Validate and return a target constant for them if we can.
4655 case 'z': {
4656 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004657 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004658 return;
4659
4660 if (Op.getValueType() == MVT::i64)
4661 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4662 else
4663 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4664 break;
4665 }
4666
4667 case 'I':
4668 case 'J':
4669 case 'K':
4670 case 'L':
4671 case 'M':
4672 case 'N':
4673 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4674 if (!C)
4675 return;
4676
4677 // Grab the value and do some validation.
4678 uint64_t CVal = C->getZExtValue();
4679 switch (ConstraintLetter) {
4680 // The I constraint applies only to simple ADD or SUB immediate operands:
4681 // i.e. 0 to 4095 with optional shift by 12
4682 // The J constraint applies only to ADD or SUB immediates that would be
4683 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4684 // instruction [or vice versa], in other words -1 to -4095 with optional
4685 // left shift by 12.
4686 case 'I':
4687 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4688 break;
4689 return;
4690 case 'J': {
4691 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004692 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4693 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004694 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004695 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004696 return;
4697 }
4698 // The K and L constraints apply *only* to logical immediates, including
4699 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4700 // been removed and MOV should be used). So these constraints have to
4701 // distinguish between bit patterns that are valid 32-bit or 64-bit
4702 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4703 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4704 // versa.
4705 case 'K':
4706 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4707 break;
4708 return;
4709 case 'L':
4710 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4711 break;
4712 return;
4713 // The M and N constraints are a superset of K and L respectively, for use
4714 // with the MOV (immediate) alias. As well as the logical immediates they
4715 // also match 32 or 64-bit immediates that can be loaded either using a
4716 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4717 // (M) or 64-bit 0x1234000000000000 (N) etc.
4718 // As a note some of this code is liberally stolen from the asm parser.
4719 case 'M': {
4720 if (!isUInt<32>(CVal))
4721 return;
4722 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4723 break;
4724 if ((CVal & 0xFFFF) == CVal)
4725 break;
4726 if ((CVal & 0xFFFF0000ULL) == CVal)
4727 break;
4728 uint64_t NCVal = ~(uint32_t)CVal;
4729 if ((NCVal & 0xFFFFULL) == NCVal)
4730 break;
4731 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4732 break;
4733 return;
4734 }
4735 case 'N': {
4736 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4737 break;
4738 if ((CVal & 0xFFFFULL) == CVal)
4739 break;
4740 if ((CVal & 0xFFFF0000ULL) == CVal)
4741 break;
4742 if ((CVal & 0xFFFF00000000ULL) == CVal)
4743 break;
4744 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4745 break;
4746 uint64_t NCVal = ~CVal;
4747 if ((NCVal & 0xFFFFULL) == NCVal)
4748 break;
4749 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4750 break;
4751 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4752 break;
4753 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4754 break;
4755 return;
4756 }
4757 default:
4758 return;
4759 }
4760
4761 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004762 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004763 break;
4764 }
4765
4766 if (Result.getNode()) {
4767 Ops.push_back(Result);
4768 return;
4769 }
4770
4771 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4772}
4773
4774//===----------------------------------------------------------------------===//
4775// AArch64 Advanced SIMD Support
4776//===----------------------------------------------------------------------===//
4777
4778/// WidenVector - Given a value in the V64 register class, produce the
4779/// equivalent value in the V128 register class.
4780static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4781 EVT VT = V64Reg.getValueType();
4782 unsigned NarrowSize = VT.getVectorNumElements();
4783 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4784 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4785 SDLoc DL(V64Reg);
4786
4787 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004788 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004789}
4790
4791/// getExtFactor - Determine the adjustment factor for the position when
4792/// generating an "extract from vector registers" instruction.
4793static unsigned getExtFactor(SDValue &V) {
4794 EVT EltType = V.getValueType().getVectorElementType();
4795 return EltType.getSizeInBits() / 8;
4796}
4797
4798/// NarrowVector - Given a value in the V128 register class, produce the
4799/// equivalent value in the V64 register class.
4800static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4801 EVT VT = V128Reg.getValueType();
4802 unsigned WideSize = VT.getVectorNumElements();
4803 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4804 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4805 SDLoc DL(V128Reg);
4806
4807 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4808}
4809
4810// Gather data to see if the operation can be modelled as a
4811// shuffle in combination with VEXTs.
4812SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4813 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004814 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004815 SDLoc dl(Op);
4816 EVT VT = Op.getValueType();
4817 unsigned NumElts = VT.getVectorNumElements();
4818
Tim Northover7324e842014-07-24 15:39:55 +00004819 struct ShuffleSourceInfo {
4820 SDValue Vec;
4821 unsigned MinElt;
4822 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004823
Tim Northover7324e842014-07-24 15:39:55 +00004824 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4825 // be compatible with the shuffle we intend to construct. As a result
4826 // ShuffleVec will be some sliding window into the original Vec.
4827 SDValue ShuffleVec;
4828
4829 // Code should guarantee that element i in Vec starts at element "WindowBase
4830 // + i * WindowScale in ShuffleVec".
4831 int WindowBase;
4832 int WindowScale;
4833
4834 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4835 ShuffleSourceInfo(SDValue Vec)
4836 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4837 WindowScale(1) {}
4838 };
4839
4840 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4841 // node.
4842 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004843 for (unsigned i = 0; i < NumElts; ++i) {
4844 SDValue V = Op.getOperand(i);
4845 if (V.getOpcode() == ISD::UNDEF)
4846 continue;
4847 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4848 // A shuffle can only come from building a vector from various
4849 // elements of other vectors.
4850 return SDValue();
4851 }
4852
Tim Northover7324e842014-07-24 15:39:55 +00004853 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004854 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004855 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4856 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004857 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004858
Tim Northover7324e842014-07-24 15:39:55 +00004859 // Update the minimum and maximum lane number seen.
4860 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4861 Source->MinElt = std::min(Source->MinElt, EltNo);
4862 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004863 }
4864
4865 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004866 // are involved.
4867 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004868 return SDValue();
4869
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004870 // Find out the smallest element size among result and two sources, and use
4871 // it as element size to build the shuffle_vector.
4872 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004873 for (auto &Source : Sources) {
4874 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004875 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4876 SmallestEltTy = SrcEltTy;
4877 }
4878 }
4879 unsigned ResMultiplier =
4880 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004881 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4882 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004883
Tim Northover7324e842014-07-24 15:39:55 +00004884 // If the source vector is too wide or too narrow, we may nevertheless be able
4885 // to construct a compatible shuffle either by concatenating it with UNDEF or
4886 // extracting a suitable range of elements.
4887 for (auto &Src : Sources) {
4888 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004889
Tim Northover7324e842014-07-24 15:39:55 +00004890 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004891 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004892
4893 // This stage of the search produces a source with the same element type as
4894 // the original, but with a total width matching the BUILD_VECTOR output.
4895 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00004896 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4897 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00004898
4899 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4900 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004901 // We can pad out the smaller vector for free, so if it's part of a
4902 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004903 Src.ShuffleVec =
4904 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4905 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004906 continue;
4907 }
4908
Tim Northover7324e842014-07-24 15:39:55 +00004909 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004910
James Molloyf497d552014-10-17 17:06:31 +00004911 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004912 // Span too large for a VEXT to cope
4913 return SDValue();
4914 }
4915
James Molloyf497d552014-10-17 17:06:31 +00004916 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004917 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004918 Src.ShuffleVec =
4919 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004920 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00004921 Src.WindowBase = -NumSrcElts;
4922 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004923 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00004924 Src.ShuffleVec =
4925 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004926 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004927 } else {
4928 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00004929 SDValue VEXTSrc1 =
4930 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004931 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004932 SDValue VEXTSrc2 =
4933 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004934 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004935 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4936
4937 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004938 VEXTSrc2,
4939 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004940 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004941 }
4942 }
4943
Tim Northover7324e842014-07-24 15:39:55 +00004944 // Another possible incompatibility occurs from the vector element types. We
4945 // can fix this by bitcasting the source vectors to the same type we intend
4946 // for the shuffle.
4947 for (auto &Src : Sources) {
4948 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4949 if (SrcEltTy == SmallestEltTy)
4950 continue;
4951 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4952 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4953 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4954 Src.WindowBase *= Src.WindowScale;
4955 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004956
Tim Northover7324e842014-07-24 15:39:55 +00004957 // Final sanity check before we try to actually produce a shuffle.
4958 DEBUG(
4959 for (auto Src : Sources)
4960 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4961 );
4962
4963 // The stars all align, our next step is to produce the mask for the shuffle.
4964 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4965 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004966 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004967 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00004968 if (Entry.getOpcode() == ISD::UNDEF)
4969 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00004970
Tim Northover7324e842014-07-24 15:39:55 +00004971 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4972 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4973
4974 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4975 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4976 // segment.
4977 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4978 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4979 VT.getVectorElementType().getSizeInBits());
4980 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4981
4982 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4983 // starting at the appropriate offset.
4984 int *LaneMask = &Mask[i * ResMultiplier];
4985
4986 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4987 ExtractBase += NumElts * (Src - Sources.begin());
4988 for (int j = 0; j < LanesDefined; ++j)
4989 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00004990 }
4991
4992 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00004993 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4994 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004995
Tim Northover7324e842014-07-24 15:39:55 +00004996 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4997 for (unsigned i = 0; i < Sources.size(); ++i)
4998 ShuffleOps[i] = Sources[i].ShuffleVec;
4999
5000 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5001 ShuffleOps[1], &Mask[0]);
5002 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005003}
5004
5005// check if an EXT instruction can handle the shuffle mask when the
5006// vector sources of the shuffle are the same.
5007static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5008 unsigned NumElts = VT.getVectorNumElements();
5009
5010 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5011 if (M[0] < 0)
5012 return false;
5013
5014 Imm = M[0];
5015
5016 // If this is a VEXT shuffle, the immediate value is the index of the first
5017 // element. The other shuffle indices must be the successive elements after
5018 // the first one.
5019 unsigned ExpectedElt = Imm;
5020 for (unsigned i = 1; i < NumElts; ++i) {
5021 // Increment the expected index. If it wraps around, just follow it
5022 // back to index zero and keep going.
5023 ++ExpectedElt;
5024 if (ExpectedElt == NumElts)
5025 ExpectedElt = 0;
5026
5027 if (M[i] < 0)
5028 continue; // ignore UNDEF indices
5029 if (ExpectedElt != static_cast<unsigned>(M[i]))
5030 return false;
5031 }
5032
5033 return true;
5034}
5035
5036// check if an EXT instruction can handle the shuffle mask when the
5037// vector sources of the shuffle are different.
5038static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5039 unsigned &Imm) {
5040 // Look for the first non-undef element.
5041 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5042 [](int Elt) {return Elt >= 0;});
5043
5044 // Benefit form APInt to handle overflow when calculating expected element.
5045 unsigned NumElts = VT.getVectorNumElements();
5046 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5047 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5048 // The following shuffle indices must be the successive elements after the
5049 // first real element.
5050 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5051 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5052 if (FirstWrongElt != M.end())
5053 return false;
5054
5055 // The index of an EXT is the first element if it is not UNDEF.
5056 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5057 // value of the first element. E.g.
5058 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5059 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5060 // ExpectedElt is the last mask index plus 1.
5061 Imm = ExpectedElt.getZExtValue();
5062
5063 // There are two difference cases requiring to reverse input vectors.
5064 // For example, for vector <4 x i32> we have the following cases,
5065 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5066 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5067 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5068 // to reverse two input vectors.
5069 if (Imm < NumElts)
5070 ReverseEXT = true;
5071 else
5072 Imm -= NumElts;
5073
5074 return true;
5075}
5076
5077/// isREVMask - Check if a vector shuffle corresponds to a REV
5078/// instruction with the specified blocksize. (The order of the elements
5079/// within each block of the vector is reversed.)
5080static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5081 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5082 "Only possible block sizes for REV are: 16, 32, 64");
5083
5084 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5085 if (EltSz == 64)
5086 return false;
5087
5088 unsigned NumElts = VT.getVectorNumElements();
5089 unsigned BlockElts = M[0] + 1;
5090 // If the first shuffle index is UNDEF, be optimistic.
5091 if (M[0] < 0)
5092 BlockElts = BlockSize / EltSz;
5093
5094 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5095 return false;
5096
5097 for (unsigned i = 0; i < NumElts; ++i) {
5098 if (M[i] < 0)
5099 continue; // ignore UNDEF indices
5100 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5101 return false;
5102 }
5103
5104 return true;
5105}
5106
5107static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5108 unsigned NumElts = VT.getVectorNumElements();
5109 WhichResult = (M[0] == 0 ? 0 : 1);
5110 unsigned Idx = WhichResult * NumElts / 2;
5111 for (unsigned i = 0; i != NumElts; i += 2) {
5112 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5113 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5114 return false;
5115 Idx += 1;
5116 }
5117
5118 return true;
5119}
5120
5121static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5122 unsigned NumElts = VT.getVectorNumElements();
5123 WhichResult = (M[0] == 0 ? 0 : 1);
5124 for (unsigned i = 0; i != NumElts; ++i) {
5125 if (M[i] < 0)
5126 continue; // ignore UNDEF indices
5127 if ((unsigned)M[i] != 2 * i + WhichResult)
5128 return false;
5129 }
5130
5131 return true;
5132}
5133
5134static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5135 unsigned NumElts = VT.getVectorNumElements();
5136 WhichResult = (M[0] == 0 ? 0 : 1);
5137 for (unsigned i = 0; i < NumElts; i += 2) {
5138 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5139 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5140 return false;
5141 }
5142 return true;
5143}
5144
5145/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5146/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5147/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5148static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5149 unsigned NumElts = VT.getVectorNumElements();
5150 WhichResult = (M[0] == 0 ? 0 : 1);
5151 unsigned Idx = WhichResult * NumElts / 2;
5152 for (unsigned i = 0; i != NumElts; i += 2) {
5153 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5154 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5155 return false;
5156 Idx += 1;
5157 }
5158
5159 return true;
5160}
5161
5162/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5163/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5164/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5165static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5166 unsigned Half = VT.getVectorNumElements() / 2;
5167 WhichResult = (M[0] == 0 ? 0 : 1);
5168 for (unsigned j = 0; j != 2; ++j) {
5169 unsigned Idx = WhichResult;
5170 for (unsigned i = 0; i != Half; ++i) {
5171 int MIdx = M[i + j * Half];
5172 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5173 return false;
5174 Idx += 2;
5175 }
5176 }
5177
5178 return true;
5179}
5180
5181/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5182/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5183/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5184static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5185 unsigned NumElts = VT.getVectorNumElements();
5186 WhichResult = (M[0] == 0 ? 0 : 1);
5187 for (unsigned i = 0; i < NumElts; i += 2) {
5188 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5189 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5190 return false;
5191 }
5192 return true;
5193}
5194
5195static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5196 bool &DstIsLeft, int &Anomaly) {
5197 if (M.size() != static_cast<size_t>(NumInputElements))
5198 return false;
5199
5200 int NumLHSMatch = 0, NumRHSMatch = 0;
5201 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5202
5203 for (int i = 0; i < NumInputElements; ++i) {
5204 if (M[i] == -1) {
5205 ++NumLHSMatch;
5206 ++NumRHSMatch;
5207 continue;
5208 }
5209
5210 if (M[i] == i)
5211 ++NumLHSMatch;
5212 else
5213 LastLHSMismatch = i;
5214
5215 if (M[i] == i + NumInputElements)
5216 ++NumRHSMatch;
5217 else
5218 LastRHSMismatch = i;
5219 }
5220
5221 if (NumLHSMatch == NumInputElements - 1) {
5222 DstIsLeft = true;
5223 Anomaly = LastLHSMismatch;
5224 return true;
5225 } else if (NumRHSMatch == NumInputElements - 1) {
5226 DstIsLeft = false;
5227 Anomaly = LastRHSMismatch;
5228 return true;
5229 }
5230
5231 return false;
5232}
5233
5234static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5235 if (VT.getSizeInBits() != 128)
5236 return false;
5237
5238 unsigned NumElts = VT.getVectorNumElements();
5239
5240 for (int I = 0, E = NumElts / 2; I != E; I++) {
5241 if (Mask[I] != I)
5242 return false;
5243 }
5244
5245 int Offset = NumElts / 2;
5246 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5247 if (Mask[I] != I + SplitLHS * Offset)
5248 return false;
5249 }
5250
5251 return true;
5252}
5253
5254static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5255 SDLoc DL(Op);
5256 EVT VT = Op.getValueType();
5257 SDValue V0 = Op.getOperand(0);
5258 SDValue V1 = Op.getOperand(1);
5259 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5260
5261 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5262 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5263 return SDValue();
5264
5265 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5266
5267 if (!isConcatMask(Mask, VT, SplitV0))
5268 return SDValue();
5269
5270 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5271 VT.getVectorNumElements() / 2);
5272 if (SplitV0) {
5273 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005274 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005275 }
5276 if (V1.getValueType().getSizeInBits() == 128) {
5277 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005278 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005279 }
5280 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5281}
5282
5283/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5284/// the specified operations to build the shuffle.
5285static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5286 SDValue RHS, SelectionDAG &DAG,
5287 SDLoc dl) {
5288 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5289 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5290 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5291
5292 enum {
5293 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5294 OP_VREV,
5295 OP_VDUP0,
5296 OP_VDUP1,
5297 OP_VDUP2,
5298 OP_VDUP3,
5299 OP_VEXT1,
5300 OP_VEXT2,
5301 OP_VEXT3,
5302 OP_VUZPL, // VUZP, left result
5303 OP_VUZPR, // VUZP, right result
5304 OP_VZIPL, // VZIP, left result
5305 OP_VZIPR, // VZIP, right result
5306 OP_VTRNL, // VTRN, left result
5307 OP_VTRNR // VTRN, right result
5308 };
5309
5310 if (OpNum == OP_COPY) {
5311 if (LHSID == (1 * 9 + 2) * 9 + 3)
5312 return LHS;
5313 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5314 return RHS;
5315 }
5316
5317 SDValue OpLHS, OpRHS;
5318 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5319 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5320 EVT VT = OpLHS.getValueType();
5321
5322 switch (OpNum) {
5323 default:
5324 llvm_unreachable("Unknown shuffle opcode!");
5325 case OP_VREV:
5326 // VREV divides the vector in half and swaps within the half.
5327 if (VT.getVectorElementType() == MVT::i32 ||
5328 VT.getVectorElementType() == MVT::f32)
5329 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5330 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005331 if (VT.getVectorElementType() == MVT::i16 ||
5332 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005333 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5334 // vrev <4 x i8> -> REV16
5335 assert(VT.getVectorElementType() == MVT::i8);
5336 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5337 case OP_VDUP0:
5338 case OP_VDUP1:
5339 case OP_VDUP2:
5340 case OP_VDUP3: {
5341 EVT EltTy = VT.getVectorElementType();
5342 unsigned Opcode;
5343 if (EltTy == MVT::i8)
5344 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005345 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005346 Opcode = AArch64ISD::DUPLANE16;
5347 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5348 Opcode = AArch64ISD::DUPLANE32;
5349 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5350 Opcode = AArch64ISD::DUPLANE64;
5351 else
5352 llvm_unreachable("Invalid vector element type?");
5353
5354 if (VT.getSizeInBits() == 64)
5355 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005356 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005357 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5358 }
5359 case OP_VEXT1:
5360 case OP_VEXT2:
5361 case OP_VEXT3: {
5362 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5363 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005364 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005365 }
5366 case OP_VUZPL:
5367 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5368 OpRHS);
5369 case OP_VUZPR:
5370 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5371 OpRHS);
5372 case OP_VZIPL:
5373 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5374 OpRHS);
5375 case OP_VZIPR:
5376 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5377 OpRHS);
5378 case OP_VTRNL:
5379 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5380 OpRHS);
5381 case OP_VTRNR:
5382 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5383 OpRHS);
5384 }
5385}
5386
5387static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5388 SelectionDAG &DAG) {
5389 // Check to see if we can use the TBL instruction.
5390 SDValue V1 = Op.getOperand(0);
5391 SDValue V2 = Op.getOperand(1);
5392 SDLoc DL(Op);
5393
5394 EVT EltVT = Op.getValueType().getVectorElementType();
5395 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5396
5397 SmallVector<SDValue, 8> TBLMask;
5398 for (int Val : ShuffleMask) {
5399 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5400 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005401 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005402 }
5403 }
5404
5405 MVT IndexVT = MVT::v8i8;
5406 unsigned IndexLen = 8;
5407 if (Op.getValueType().getSizeInBits() == 128) {
5408 IndexVT = MVT::v16i8;
5409 IndexLen = 16;
5410 }
5411
5412 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5413 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5414
5415 SDValue Shuffle;
5416 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5417 if (IndexLen == 8)
5418 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5419 Shuffle = DAG.getNode(
5420 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005421 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005422 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5423 makeArrayRef(TBLMask.data(), IndexLen)));
5424 } else {
5425 if (IndexLen == 8) {
5426 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5427 Shuffle = DAG.getNode(
5428 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005429 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005430 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5431 makeArrayRef(TBLMask.data(), IndexLen)));
5432 } else {
5433 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5434 // cannot currently represent the register constraints on the input
5435 // table registers.
5436 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5437 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5438 // &TBLMask[0], IndexLen));
5439 Shuffle = DAG.getNode(
5440 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005441 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5442 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005443 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5444 makeArrayRef(TBLMask.data(), IndexLen)));
5445 }
5446 }
5447 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5448}
5449
5450static unsigned getDUPLANEOp(EVT EltType) {
5451 if (EltType == MVT::i8)
5452 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005453 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005454 return AArch64ISD::DUPLANE16;
5455 if (EltType == MVT::i32 || EltType == MVT::f32)
5456 return AArch64ISD::DUPLANE32;
5457 if (EltType == MVT::i64 || EltType == MVT::f64)
5458 return AArch64ISD::DUPLANE64;
5459
5460 llvm_unreachable("Invalid vector element type?");
5461}
5462
5463SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5464 SelectionDAG &DAG) const {
5465 SDLoc dl(Op);
5466 EVT VT = Op.getValueType();
5467
5468 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5469
5470 // Convert shuffles that are directly supported on NEON to target-specific
5471 // DAG nodes, instead of keeping them as shuffles and matching them again
5472 // during code selection. This is more efficient and avoids the possibility
5473 // of inconsistencies between legalization and selection.
5474 ArrayRef<int> ShuffleMask = SVN->getMask();
5475
5476 SDValue V1 = Op.getOperand(0);
5477 SDValue V2 = Op.getOperand(1);
5478
5479 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5480 V1.getValueType().getSimpleVT())) {
5481 int Lane = SVN->getSplatIndex();
5482 // If this is undef splat, generate it via "just" vdup, if possible.
5483 if (Lane == -1)
5484 Lane = 0;
5485
5486 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5487 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5488 V1.getOperand(0));
5489 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5490 // constant. If so, we can just reference the lane's definition directly.
5491 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5492 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5493 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5494
5495 // Otherwise, duplicate from the lane of the input vector.
5496 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5497
5498 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5499 // to make a vector of the same size as this SHUFFLE. We can ignore the
5500 // extract entirely, and canonicalise the concat using WidenVector.
5501 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5502 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5503 V1 = V1.getOperand(0);
5504 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5505 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5506 Lane -= Idx * VT.getVectorNumElements() / 2;
5507 V1 = WidenVector(V1.getOperand(Idx), DAG);
5508 } else if (VT.getSizeInBits() == 64)
5509 V1 = WidenVector(V1, DAG);
5510
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005511 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005512 }
5513
5514 if (isREVMask(ShuffleMask, VT, 64))
5515 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5516 if (isREVMask(ShuffleMask, VT, 32))
5517 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5518 if (isREVMask(ShuffleMask, VT, 16))
5519 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5520
5521 bool ReverseEXT = false;
5522 unsigned Imm;
5523 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5524 if (ReverseEXT)
5525 std::swap(V1, V2);
5526 Imm *= getExtFactor(V1);
5527 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005528 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005529 } else if (V2->getOpcode() == ISD::UNDEF &&
5530 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5531 Imm *= getExtFactor(V1);
5532 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005533 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005534 }
5535
5536 unsigned WhichResult;
5537 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5538 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5539 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5540 }
5541 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5542 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5543 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5544 }
5545 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5546 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5547 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5548 }
5549
5550 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5551 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5552 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5553 }
5554 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5555 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5556 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5557 }
5558 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5559 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5560 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5561 }
5562
5563 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5564 if (Concat.getNode())
5565 return Concat;
5566
5567 bool DstIsLeft;
5568 int Anomaly;
5569 int NumInputElements = V1.getValueType().getVectorNumElements();
5570 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5571 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005572 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005573
5574 SDValue SrcVec = V1;
5575 int SrcLane = ShuffleMask[Anomaly];
5576 if (SrcLane >= NumInputElements) {
5577 SrcVec = V2;
5578 SrcLane -= VT.getVectorNumElements();
5579 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005580 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005581
5582 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005583
5584 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005585 ScalarVT = MVT::i32;
5586
5587 return DAG.getNode(
5588 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5589 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5590 DstLaneV);
5591 }
5592
5593 // If the shuffle is not directly supported and it has 4 elements, use
5594 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5595 unsigned NumElts = VT.getVectorNumElements();
5596 if (NumElts == 4) {
5597 unsigned PFIndexes[4];
5598 for (unsigned i = 0; i != 4; ++i) {
5599 if (ShuffleMask[i] < 0)
5600 PFIndexes[i] = 8;
5601 else
5602 PFIndexes[i] = ShuffleMask[i];
5603 }
5604
5605 // Compute the index in the perfect shuffle table.
5606 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5607 PFIndexes[2] * 9 + PFIndexes[3];
5608 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5609 unsigned Cost = (PFEntry >> 30);
5610
5611 if (Cost <= 4)
5612 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5613 }
5614
5615 return GenerateTBL(Op, ShuffleMask, DAG);
5616}
5617
5618static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5619 APInt &UndefBits) {
5620 EVT VT = BVN->getValueType(0);
5621 APInt SplatBits, SplatUndef;
5622 unsigned SplatBitSize;
5623 bool HasAnyUndefs;
5624 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5625 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5626
5627 for (unsigned i = 0; i < NumSplats; ++i) {
5628 CnstBits <<= SplatBitSize;
5629 UndefBits <<= SplatBitSize;
5630 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5631 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5632 }
5633
5634 return true;
5635 }
5636
5637 return false;
5638}
5639
5640SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5641 SelectionDAG &DAG) const {
5642 BuildVectorSDNode *BVN =
5643 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5644 SDValue LHS = Op.getOperand(0);
5645 SDLoc dl(Op);
5646 EVT VT = Op.getValueType();
5647
5648 if (!BVN)
5649 return Op;
5650
5651 APInt CnstBits(VT.getSizeInBits(), 0);
5652 APInt UndefBits(VT.getSizeInBits(), 0);
5653 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5654 // We only have BIC vector immediate instruction, which is and-not.
5655 CnstBits = ~CnstBits;
5656
5657 // We make use of a little bit of goto ickiness in order to avoid having to
5658 // duplicate the immediate matching logic for the undef toggled case.
5659 bool SecondTry = false;
5660 AttemptModImm:
5661
5662 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5663 CnstBits = CnstBits.zextOrTrunc(64);
5664 uint64_t CnstVal = CnstBits.getZExtValue();
5665
5666 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5667 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5668 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5669 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005670 DAG.getConstant(CnstVal, dl, MVT::i32),
5671 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005672 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005673 }
5674
5675 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5676 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5677 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5678 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005679 DAG.getConstant(CnstVal, dl, MVT::i32),
5680 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005681 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005682 }
5683
5684 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5685 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5686 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5687 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005688 DAG.getConstant(CnstVal, dl, MVT::i32),
5689 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005690 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005691 }
5692
5693 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5694 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5695 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5696 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005697 DAG.getConstant(CnstVal, dl, MVT::i32),
5698 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005699 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005700 }
5701
5702 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5703 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5704 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5705 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005706 DAG.getConstant(CnstVal, dl, MVT::i32),
5707 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005708 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005709 }
5710
5711 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5712 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5713 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5714 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005715 DAG.getConstant(CnstVal, dl, MVT::i32),
5716 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005717 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005718 }
5719 }
5720
5721 if (SecondTry)
5722 goto FailedModImm;
5723 SecondTry = true;
5724 CnstBits = ~UndefBits;
5725 goto AttemptModImm;
5726 }
5727
5728// We can always fall back to a non-immediate AND.
5729FailedModImm:
5730 return Op;
5731}
5732
5733// Specialized code to quickly find if PotentialBVec is a BuildVector that
5734// consists of only the same constant int value, returned in reference arg
5735// ConstVal
5736static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5737 uint64_t &ConstVal) {
5738 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5739 if (!Bvec)
5740 return false;
5741 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5742 if (!FirstElt)
5743 return false;
5744 EVT VT = Bvec->getValueType(0);
5745 unsigned NumElts = VT.getVectorNumElements();
5746 for (unsigned i = 1; i < NumElts; ++i)
5747 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5748 return false;
5749 ConstVal = FirstElt->getZExtValue();
5750 return true;
5751}
5752
5753static unsigned getIntrinsicID(const SDNode *N) {
5754 unsigned Opcode = N->getOpcode();
5755 switch (Opcode) {
5756 default:
5757 return Intrinsic::not_intrinsic;
5758 case ISD::INTRINSIC_WO_CHAIN: {
5759 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5760 if (IID < Intrinsic::num_intrinsics)
5761 return IID;
5762 return Intrinsic::not_intrinsic;
5763 }
5764 }
5765}
5766
5767// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5768// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5769// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5770// Also, logical shift right -> sri, with the same structure.
5771static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5772 EVT VT = N->getValueType(0);
5773
5774 if (!VT.isVector())
5775 return SDValue();
5776
5777 SDLoc DL(N);
5778
5779 // Is the first op an AND?
5780 const SDValue And = N->getOperand(0);
5781 if (And.getOpcode() != ISD::AND)
5782 return SDValue();
5783
5784 // Is the second op an shl or lshr?
5785 SDValue Shift = N->getOperand(1);
5786 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5787 // or AArch64ISD::VLSHR vector, #shift
5788 unsigned ShiftOpc = Shift.getOpcode();
5789 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5790 return SDValue();
5791 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5792
5793 // Is the shift amount constant?
5794 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5795 if (!C2node)
5796 return SDValue();
5797
5798 // Is the and mask vector all constant?
5799 uint64_t C1;
5800 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5801 return SDValue();
5802
5803 // Is C1 == ~C2, taking into account how much one can shift elements of a
5804 // particular size?
5805 uint64_t C2 = C2node->getZExtValue();
5806 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5807 if (C2 > ElemSizeInBits)
5808 return SDValue();
5809 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5810 if ((C1 & ElemMask) != (~C2 & ElemMask))
5811 return SDValue();
5812
5813 SDValue X = And.getOperand(0);
5814 SDValue Y = Shift.getOperand(0);
5815
5816 unsigned Intrin =
5817 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5818 SDValue ResultSLI =
5819 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005820 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5821 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005822
5823 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5824 DEBUG(N->dump(&DAG));
5825 DEBUG(dbgs() << "into: \n");
5826 DEBUG(ResultSLI->dump(&DAG));
5827
5828 ++NumShiftInserts;
5829 return ResultSLI;
5830}
5831
5832SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5833 SelectionDAG &DAG) const {
5834 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5835 if (EnableAArch64SlrGeneration) {
5836 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5837 if (Res.getNode())
5838 return Res;
5839 }
5840
5841 BuildVectorSDNode *BVN =
5842 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5843 SDValue LHS = Op.getOperand(1);
5844 SDLoc dl(Op);
5845 EVT VT = Op.getValueType();
5846
5847 // OR commutes, so try swapping the operands.
5848 if (!BVN) {
5849 LHS = Op.getOperand(0);
5850 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5851 }
5852 if (!BVN)
5853 return Op;
5854
5855 APInt CnstBits(VT.getSizeInBits(), 0);
5856 APInt UndefBits(VT.getSizeInBits(), 0);
5857 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5858 // We make use of a little bit of goto ickiness in order to avoid having to
5859 // duplicate the immediate matching logic for the undef toggled case.
5860 bool SecondTry = false;
5861 AttemptModImm:
5862
5863 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5864 CnstBits = CnstBits.zextOrTrunc(64);
5865 uint64_t CnstVal = CnstBits.getZExtValue();
5866
5867 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5868 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5869 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5870 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005871 DAG.getConstant(CnstVal, dl, MVT::i32),
5872 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005873 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005874 }
5875
5876 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5877 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5878 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5879 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005880 DAG.getConstant(CnstVal, dl, MVT::i32),
5881 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005882 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005883 }
5884
5885 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5886 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5887 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5888 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005889 DAG.getConstant(CnstVal, dl, MVT::i32),
5890 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005891 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005892 }
5893
5894 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5895 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5896 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5897 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005898 DAG.getConstant(CnstVal, dl, MVT::i32),
5899 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005900 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005901 }
5902
5903 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5904 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5905 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5906 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005907 DAG.getConstant(CnstVal, dl, MVT::i32),
5908 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005909 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005910 }
5911
5912 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5913 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5914 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5915 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005916 DAG.getConstant(CnstVal, dl, MVT::i32),
5917 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005918 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005919 }
5920 }
5921
5922 if (SecondTry)
5923 goto FailedModImm;
5924 SecondTry = true;
5925 CnstBits = UndefBits;
5926 goto AttemptModImm;
5927 }
5928
5929// We can always fall back to a non-immediate OR.
5930FailedModImm:
5931 return Op;
5932}
5933
Kevin Qin4473c192014-07-07 02:45:40 +00005934// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5935// be truncated to fit element width.
5936static SDValue NormalizeBuildVector(SDValue Op,
5937 SelectionDAG &DAG) {
5938 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005939 SDLoc dl(Op);
5940 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005941 EVT EltTy= VT.getVectorElementType();
5942
5943 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5944 return Op;
5945
5946 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005947 for (SDValue Lane : Op->ops()) {
5948 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00005949 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005950 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005951 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00005952 }
5953 Ops.push_back(Lane);
5954 }
5955 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5956}
5957
5958SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5959 SelectionDAG &DAG) const {
5960 SDLoc dl(Op);
5961 EVT VT = Op.getValueType();
5962 Op = NormalizeBuildVector(Op, DAG);
5963 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00005964
5965 APInt CnstBits(VT.getSizeInBits(), 0);
5966 APInt UndefBits(VT.getSizeInBits(), 0);
5967 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5968 // We make use of a little bit of goto ickiness in order to avoid having to
5969 // duplicate the immediate matching logic for the undef toggled case.
5970 bool SecondTry = false;
5971 AttemptModImm:
5972
5973 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5974 CnstBits = CnstBits.zextOrTrunc(64);
5975 uint64_t CnstVal = CnstBits.getZExtValue();
5976
5977 // Certain magic vector constants (used to express things like NOT
5978 // and NEG) are passed through unmodified. This allows codegen patterns
5979 // for these operations to match. Special-purpose patterns will lower
5980 // these immediates to MOVIs if it proves necessary.
5981 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5982 return Op;
5983
5984 // The many faces of MOVI...
5985 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5986 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5987 if (VT.getSizeInBits() == 128) {
5988 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005989 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005990 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005991 }
5992
5993 // Support the V64 version via subregister insertion.
5994 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005995 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005996 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005997 }
5998
5999 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6000 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6001 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6002 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006003 DAG.getConstant(CnstVal, dl, MVT::i32),
6004 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006005 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006006 }
6007
6008 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6009 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6010 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6011 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006012 DAG.getConstant(CnstVal, dl, MVT::i32),
6013 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006014 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006015 }
6016
6017 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6018 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6019 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6020 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006021 DAG.getConstant(CnstVal, dl, MVT::i32),
6022 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006023 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006024 }
6025
6026 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6027 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6028 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6029 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006030 DAG.getConstant(CnstVal, dl, MVT::i32),
6031 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006032 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006033 }
6034
6035 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6036 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6037 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6038 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006039 DAG.getConstant(CnstVal, dl, MVT::i32),
6040 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006041 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006042 }
6043
6044 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6045 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6046 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6047 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006048 DAG.getConstant(CnstVal, dl, MVT::i32),
6049 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006050 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006051 }
6052
6053 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6054 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6055 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6056 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006057 DAG.getConstant(CnstVal, dl, MVT::i32),
6058 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006059 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006060 }
6061
6062 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6063 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6064 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6065 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006066 DAG.getConstant(CnstVal, dl, MVT::i32),
6067 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006068 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006069 }
6070
6071 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6072 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6073 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6074 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006075 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006076 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006077 }
6078
6079 // The few faces of FMOV...
6080 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6081 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6082 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6083 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006084 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006085 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006086 }
6087
6088 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6089 VT.getSizeInBits() == 128) {
6090 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6091 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006092 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006093 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006094 }
6095
6096 // The many faces of MVNI...
6097 CnstVal = ~CnstVal;
6098 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6099 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6100 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6101 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006102 DAG.getConstant(CnstVal, dl, MVT::i32),
6103 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006104 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006105 }
6106
6107 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6108 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6109 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6110 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006111 DAG.getConstant(CnstVal, dl, MVT::i32),
6112 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006113 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006114 }
6115
6116 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6117 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6118 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6119 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006120 DAG.getConstant(CnstVal, dl, MVT::i32),
6121 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006122 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006123 }
6124
6125 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6126 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6127 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6128 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006129 DAG.getConstant(CnstVal, dl, MVT::i32),
6130 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006131 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006132 }
6133
6134 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6135 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6136 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6137 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006138 DAG.getConstant(CnstVal, dl, MVT::i32),
6139 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006140 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006141 }
6142
6143 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6144 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6145 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6146 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006147 DAG.getConstant(CnstVal, dl, MVT::i32),
6148 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006149 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006150 }
6151
6152 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6153 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6154 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6155 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006156 DAG.getConstant(CnstVal, dl, MVT::i32),
6157 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006158 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006159 }
6160
6161 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6162 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6163 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6164 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006165 DAG.getConstant(CnstVal, dl, MVT::i32),
6166 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006167 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006168 }
6169 }
6170
6171 if (SecondTry)
6172 goto FailedModImm;
6173 SecondTry = true;
6174 CnstBits = UndefBits;
6175 goto AttemptModImm;
6176 }
6177FailedModImm:
6178
6179 // Scan through the operands to find some interesting properties we can
6180 // exploit:
6181 // 1) If only one value is used, we can use a DUP, or
6182 // 2) if only the low element is not undef, we can just insert that, or
6183 // 3) if only one constant value is used (w/ some non-constant lanes),
6184 // we can splat the constant value into the whole vector then fill
6185 // in the non-constant lanes.
6186 // 4) FIXME: If different constant values are used, but we can intelligently
6187 // select the values we'll be overwriting for the non-constant
6188 // lanes such that we can directly materialize the vector
6189 // some other way (MOVI, e.g.), we can be sneaky.
6190 unsigned NumElts = VT.getVectorNumElements();
6191 bool isOnlyLowElement = true;
6192 bool usesOnlyOneValue = true;
6193 bool usesOnlyOneConstantValue = true;
6194 bool isConstant = true;
6195 unsigned NumConstantLanes = 0;
6196 SDValue Value;
6197 SDValue ConstantValue;
6198 for (unsigned i = 0; i < NumElts; ++i) {
6199 SDValue V = Op.getOperand(i);
6200 if (V.getOpcode() == ISD::UNDEF)
6201 continue;
6202 if (i > 0)
6203 isOnlyLowElement = false;
6204 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6205 isConstant = false;
6206
6207 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6208 ++NumConstantLanes;
6209 if (!ConstantValue.getNode())
6210 ConstantValue = V;
6211 else if (ConstantValue != V)
6212 usesOnlyOneConstantValue = false;
6213 }
6214
6215 if (!Value.getNode())
6216 Value = V;
6217 else if (V != Value)
6218 usesOnlyOneValue = false;
6219 }
6220
6221 if (!Value.getNode())
6222 return DAG.getUNDEF(VT);
6223
6224 if (isOnlyLowElement)
6225 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6226
6227 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6228 // i32 and try again.
6229 if (usesOnlyOneValue) {
6230 if (!isConstant) {
6231 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6232 Value.getValueType() != VT)
6233 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6234
6235 // This is actually a DUPLANExx operation, which keeps everything vectory.
6236
6237 // DUPLANE works on 128-bit vectors, widen it if necessary.
6238 SDValue Lane = Value.getOperand(1);
6239 Value = Value.getOperand(0);
6240 if (Value.getValueType().getSizeInBits() == 64)
6241 Value = WidenVector(Value, DAG);
6242
6243 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6244 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6245 }
6246
6247 if (VT.getVectorElementType().isFloatingPoint()) {
6248 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006249 EVT EltTy = VT.getVectorElementType();
6250 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6251 "Unsupported floating-point vector type");
6252 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006253 for (unsigned i = 0; i < NumElts; ++i)
6254 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6255 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6256 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6257 Val = LowerBUILD_VECTOR(Val, DAG);
6258 if (Val.getNode())
6259 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6260 }
6261 }
6262
6263 // If there was only one constant value used and for more than one lane,
6264 // start by splatting that value, then replace the non-constant lanes. This
6265 // is better than the default, which will perform a separate initialization
6266 // for each lane.
6267 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6268 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6269 // Now insert the non-constant lanes.
6270 for (unsigned i = 0; i < NumElts; ++i) {
6271 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006272 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006273 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6274 // Note that type legalization likely mucked about with the VT of the
6275 // source operand, so we may have to convert it here before inserting.
6276 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6277 }
6278 }
6279 return Val;
6280 }
6281
6282 // If all elements are constants and the case above didn't get hit, fall back
6283 // to the default expansion, which will generate a load from the constant
6284 // pool.
6285 if (isConstant)
6286 return SDValue();
6287
6288 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6289 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006290 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006291 return shuffle;
6292 }
6293
6294 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6295 // know the default expansion would otherwise fall back on something even
6296 // worse. For a vector with one or two non-undef values, that's
6297 // scalar_to_vector for the elements followed by a shuffle (provided the
6298 // shuffle is valid for the target) and materialization element by element
6299 // on the stack followed by a load for everything else.
6300 if (!isConstant && !usesOnlyOneValue) {
6301 SDValue Vec = DAG.getUNDEF(VT);
6302 SDValue Op0 = Op.getOperand(0);
6303 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6304 unsigned i = 0;
6305 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6306 // a) Avoid a RMW dependency on the full vector register, and
6307 // b) Allow the register coalescer to fold away the copy if the
6308 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006309 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6310 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6311 if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6312 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006313 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6314 MachineSDNode *N =
6315 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006316 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006317 Vec = SDValue(N, 0);
6318 ++i;
6319 }
6320 for (; i < NumElts; ++i) {
6321 SDValue V = Op.getOperand(i);
6322 if (V.getOpcode() == ISD::UNDEF)
6323 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006324 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006325 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6326 }
6327 return Vec;
6328 }
6329
6330 // Just use the default expansion. We failed to find a better alternative.
6331 return SDValue();
6332}
6333
6334SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6335 SelectionDAG &DAG) const {
6336 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6337
Tim Northovere4b8e132014-07-15 10:00:26 +00006338 // Check for non-constant or out of range lane.
6339 EVT VT = Op.getOperand(0).getValueType();
6340 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6341 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006342 return SDValue();
6343
Tim Northover3b0846e2014-05-24 12:50:23 +00006344
6345 // Insertion/extraction are legal for V128 types.
6346 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006347 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6348 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006349 return Op;
6350
6351 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006352 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006353 return SDValue();
6354
6355 // For V64 types, we perform insertion by expanding the value
6356 // to a V128 type and perform the insertion on that.
6357 SDLoc DL(Op);
6358 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6359 EVT WideTy = WideVec.getValueType();
6360
6361 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6362 Op.getOperand(1), Op.getOperand(2));
6363 // Re-narrow the resultant vector.
6364 return NarrowVector(Node, DAG);
6365}
6366
6367SDValue
6368AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6369 SelectionDAG &DAG) const {
6370 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6371
Tim Northovere4b8e132014-07-15 10:00:26 +00006372 // Check for non-constant or out of range lane.
6373 EVT VT = Op.getOperand(0).getValueType();
6374 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6375 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006376 return SDValue();
6377
Tim Northover3b0846e2014-05-24 12:50:23 +00006378
6379 // Insertion/extraction are legal for V128 types.
6380 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006381 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6382 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006383 return Op;
6384
6385 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006386 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006387 return SDValue();
6388
6389 // For V64 types, we perform extraction by expanding the value
6390 // to a V128 type and perform the extraction on that.
6391 SDLoc DL(Op);
6392 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6393 EVT WideTy = WideVec.getValueType();
6394
6395 EVT ExtrTy = WideTy.getVectorElementType();
6396 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6397 ExtrTy = MVT::i32;
6398
6399 // For extractions, we just return the result directly.
6400 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6401 Op.getOperand(1));
6402}
6403
6404SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6405 SelectionDAG &DAG) const {
6406 EVT VT = Op.getOperand(0).getValueType();
6407 SDLoc dl(Op);
6408 // Just in case...
6409 if (!VT.isVector())
6410 return SDValue();
6411
6412 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6413 if (!Cst)
6414 return SDValue();
6415 unsigned Val = Cst->getZExtValue();
6416
6417 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006418
6419 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6420 if (Val == 0)
6421 return Op;
6422
Tim Northover3b0846e2014-05-24 12:50:23 +00006423 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6424 // that directly.
6425 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6426 return Op;
6427
6428 return SDValue();
6429}
6430
6431bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6432 EVT VT) const {
6433 if (VT.getVectorNumElements() == 4 &&
6434 (VT.is128BitVector() || VT.is64BitVector())) {
6435 unsigned PFIndexes[4];
6436 for (unsigned i = 0; i != 4; ++i) {
6437 if (M[i] < 0)
6438 PFIndexes[i] = 8;
6439 else
6440 PFIndexes[i] = M[i];
6441 }
6442
6443 // Compute the index in the perfect shuffle table.
6444 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6445 PFIndexes[2] * 9 + PFIndexes[3];
6446 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6447 unsigned Cost = (PFEntry >> 30);
6448
6449 if (Cost <= 4)
6450 return true;
6451 }
6452
6453 bool DummyBool;
6454 int DummyInt;
6455 unsigned DummyUnsigned;
6456
6457 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6458 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6459 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6460 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6461 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6462 isZIPMask(M, VT, DummyUnsigned) ||
6463 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6464 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6465 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6466 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6467 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6468}
6469
6470/// getVShiftImm - Check if this is a valid build_vector for the immediate
6471/// operand of a vector shift operation, where all the elements of the
6472/// build_vector must have the same constant integer value.
6473static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6474 // Ignore bit_converts.
6475 while (Op.getOpcode() == ISD::BITCAST)
6476 Op = Op.getOperand(0);
6477 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6478 APInt SplatBits, SplatUndef;
6479 unsigned SplatBitSize;
6480 bool HasAnyUndefs;
6481 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6482 HasAnyUndefs, ElementBits) ||
6483 SplatBitSize > ElementBits)
6484 return false;
6485 Cnt = SplatBits.getSExtValue();
6486 return true;
6487}
6488
6489/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6490/// operand of a vector shift left operation. That value must be in the range:
6491/// 0 <= Value < ElementBits for a left shift; or
6492/// 0 <= Value <= ElementBits for a long left shift.
6493static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6494 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006495 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006496 if (!getVShiftImm(Op, ElementBits, Cnt))
6497 return false;
6498 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6499}
6500
6501/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006502/// operand of a vector shift right operation. The value must be in the range:
6503/// 1 <= Value <= ElementBits for a right shift; or
6504static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006505 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006506 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006507 if (!getVShiftImm(Op, ElementBits, Cnt))
6508 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006509 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6510}
6511
6512SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6513 SelectionDAG &DAG) const {
6514 EVT VT = Op.getValueType();
6515 SDLoc DL(Op);
6516 int64_t Cnt;
6517
6518 if (!Op.getOperand(1).getValueType().isVector())
6519 return Op;
6520 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6521
6522 switch (Op.getOpcode()) {
6523 default:
6524 llvm_unreachable("unexpected shift opcode");
6525
6526 case ISD::SHL:
6527 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006528 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6529 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006530 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006531 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6532 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006533 Op.getOperand(0), Op.getOperand(1));
6534 case ISD::SRA:
6535 case ISD::SRL:
6536 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006537 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006538 unsigned Opc =
6539 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006540 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6541 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006542 }
6543
6544 // Right shift register. Note, there is not a shift right register
6545 // instruction, but the shift left register instruction takes a signed
6546 // value, where negative numbers specify a right shift.
6547 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6548 : Intrinsic::aarch64_neon_ushl;
6549 // negate the shift amount
6550 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6551 SDValue NegShiftLeft =
6552 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006553 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6554 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006555 return NegShiftLeft;
6556 }
6557
6558 return SDValue();
6559}
6560
6561static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6562 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6563 SDLoc dl, SelectionDAG &DAG) {
6564 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006565 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6566 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006567
6568 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6569 APInt CnstBits(VT.getSizeInBits(), 0);
6570 APInt UndefBits(VT.getSizeInBits(), 0);
6571 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6572 bool IsZero = IsCnst && (CnstBits == 0);
6573
6574 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6575 switch (CC) {
6576 default:
6577 return SDValue();
6578 case AArch64CC::NE: {
6579 SDValue Fcmeq;
6580 if (IsZero)
6581 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6582 else
6583 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6584 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6585 }
6586 case AArch64CC::EQ:
6587 if (IsZero)
6588 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6589 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6590 case AArch64CC::GE:
6591 if (IsZero)
6592 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6593 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6594 case AArch64CC::GT:
6595 if (IsZero)
6596 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6597 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6598 case AArch64CC::LS:
6599 if (IsZero)
6600 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6601 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6602 case AArch64CC::LT:
6603 if (!NoNans)
6604 return SDValue();
6605 // If we ignore NaNs then we can use to the MI implementation.
6606 // Fallthrough.
6607 case AArch64CC::MI:
6608 if (IsZero)
6609 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6610 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6611 }
6612 }
6613
6614 switch (CC) {
6615 default:
6616 return SDValue();
6617 case AArch64CC::NE: {
6618 SDValue Cmeq;
6619 if (IsZero)
6620 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6621 else
6622 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6623 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6624 }
6625 case AArch64CC::EQ:
6626 if (IsZero)
6627 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6628 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6629 case AArch64CC::GE:
6630 if (IsZero)
6631 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6632 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6633 case AArch64CC::GT:
6634 if (IsZero)
6635 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6636 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6637 case AArch64CC::LE:
6638 if (IsZero)
6639 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6640 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6641 case AArch64CC::LS:
6642 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6643 case AArch64CC::LO:
6644 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6645 case AArch64CC::LT:
6646 if (IsZero)
6647 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6648 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6649 case AArch64CC::HI:
6650 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6651 case AArch64CC::HS:
6652 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6653 }
6654}
6655
6656SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6657 SelectionDAG &DAG) const {
6658 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6659 SDValue LHS = Op.getOperand(0);
6660 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006661 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006662 SDLoc dl(Op);
6663
6664 if (LHS.getValueType().getVectorElementType().isInteger()) {
6665 assert(LHS.getValueType() == RHS.getValueType());
6666 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006667 SDValue Cmp =
6668 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6669 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006670 }
6671
6672 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6673 LHS.getValueType().getVectorElementType() == MVT::f64);
6674
6675 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6676 // clean. Some of them require two branches to implement.
6677 AArch64CC::CondCode CC1, CC2;
6678 bool ShouldInvert;
6679 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6680
6681 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6682 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006683 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006684 if (!Cmp.getNode())
6685 return SDValue();
6686
6687 if (CC2 != AArch64CC::AL) {
6688 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006689 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006690 if (!Cmp2.getNode())
6691 return SDValue();
6692
Tim Northover45aa89c2015-02-08 00:50:47 +00006693 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006694 }
6695
Tim Northover45aa89c2015-02-08 00:50:47 +00006696 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6697
Tim Northover3b0846e2014-05-24 12:50:23 +00006698 if (ShouldInvert)
6699 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6700
6701 return Cmp;
6702}
6703
6704/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6705/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6706/// specified in the intrinsic calls.
6707bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6708 const CallInst &I,
6709 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006710 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006711 switch (Intrinsic) {
6712 case Intrinsic::aarch64_neon_ld2:
6713 case Intrinsic::aarch64_neon_ld3:
6714 case Intrinsic::aarch64_neon_ld4:
6715 case Intrinsic::aarch64_neon_ld1x2:
6716 case Intrinsic::aarch64_neon_ld1x3:
6717 case Intrinsic::aarch64_neon_ld1x4:
6718 case Intrinsic::aarch64_neon_ld2lane:
6719 case Intrinsic::aarch64_neon_ld3lane:
6720 case Intrinsic::aarch64_neon_ld4lane:
6721 case Intrinsic::aarch64_neon_ld2r:
6722 case Intrinsic::aarch64_neon_ld3r:
6723 case Intrinsic::aarch64_neon_ld4r: {
6724 Info.opc = ISD::INTRINSIC_W_CHAIN;
6725 // Conservatively set memVT to the entire set of vectors loaded.
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006726 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00006727 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6728 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6729 Info.offset = 0;
6730 Info.align = 0;
6731 Info.vol = false; // volatile loads with NEON intrinsics not supported
6732 Info.readMem = true;
6733 Info.writeMem = false;
6734 return true;
6735 }
6736 case Intrinsic::aarch64_neon_st2:
6737 case Intrinsic::aarch64_neon_st3:
6738 case Intrinsic::aarch64_neon_st4:
6739 case Intrinsic::aarch64_neon_st1x2:
6740 case Intrinsic::aarch64_neon_st1x3:
6741 case Intrinsic::aarch64_neon_st1x4:
6742 case Intrinsic::aarch64_neon_st2lane:
6743 case Intrinsic::aarch64_neon_st3lane:
6744 case Intrinsic::aarch64_neon_st4lane: {
6745 Info.opc = ISD::INTRINSIC_VOID;
6746 // Conservatively set memVT to the entire set of vectors stored.
6747 unsigned NumElts = 0;
6748 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6749 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6750 if (!ArgTy->isVectorTy())
6751 break;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006752 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00006753 }
6754 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6755 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6756 Info.offset = 0;
6757 Info.align = 0;
6758 Info.vol = false; // volatile stores with NEON intrinsics not supported
6759 Info.readMem = false;
6760 Info.writeMem = true;
6761 return true;
6762 }
6763 case Intrinsic::aarch64_ldaxr:
6764 case Intrinsic::aarch64_ldxr: {
6765 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6766 Info.opc = ISD::INTRINSIC_W_CHAIN;
6767 Info.memVT = MVT::getVT(PtrTy->getElementType());
6768 Info.ptrVal = I.getArgOperand(0);
6769 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006770 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006771 Info.vol = true;
6772 Info.readMem = true;
6773 Info.writeMem = false;
6774 return true;
6775 }
6776 case Intrinsic::aarch64_stlxr:
6777 case Intrinsic::aarch64_stxr: {
6778 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6779 Info.opc = ISD::INTRINSIC_W_CHAIN;
6780 Info.memVT = MVT::getVT(PtrTy->getElementType());
6781 Info.ptrVal = I.getArgOperand(1);
6782 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006783 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006784 Info.vol = true;
6785 Info.readMem = false;
6786 Info.writeMem = true;
6787 return true;
6788 }
6789 case Intrinsic::aarch64_ldaxp:
6790 case Intrinsic::aarch64_ldxp: {
6791 Info.opc = ISD::INTRINSIC_W_CHAIN;
6792 Info.memVT = MVT::i128;
6793 Info.ptrVal = I.getArgOperand(0);
6794 Info.offset = 0;
6795 Info.align = 16;
6796 Info.vol = true;
6797 Info.readMem = true;
6798 Info.writeMem = false;
6799 return true;
6800 }
6801 case Intrinsic::aarch64_stlxp:
6802 case Intrinsic::aarch64_stxp: {
6803 Info.opc = ISD::INTRINSIC_W_CHAIN;
6804 Info.memVT = MVT::i128;
6805 Info.ptrVal = I.getArgOperand(2);
6806 Info.offset = 0;
6807 Info.align = 16;
6808 Info.vol = true;
6809 Info.readMem = false;
6810 Info.writeMem = true;
6811 return true;
6812 }
6813 default:
6814 break;
6815 }
6816
6817 return false;
6818}
6819
6820// Truncations from 64-bit GPR to 32-bit GPR is free.
6821bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6822 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6823 return false;
6824 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6825 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006826 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006827}
6828bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006829 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006830 return false;
6831 unsigned NumBits1 = VT1.getSizeInBits();
6832 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006833 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006834}
6835
Chad Rosier54390052015-02-23 19:15:16 +00006836/// Check if it is profitable to hoist instruction in then/else to if.
6837/// Not profitable if I and it's user can form a FMA instruction
6838/// because we prefer FMSUB/FMADD.
6839bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6840 if (I->getOpcode() != Instruction::FMul)
6841 return true;
6842
6843 if (I->getNumUses() != 1)
6844 return true;
6845
6846 Instruction *User = I->user_back();
6847
6848 if (User &&
6849 !(User->getOpcode() == Instruction::FSub ||
6850 User->getOpcode() == Instruction::FAdd))
6851 return true;
6852
6853 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006854 const DataLayout &DL = I->getModule()->getDataLayout();
6855 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006856
6857 if (isFMAFasterThanFMulAndFAdd(VT) &&
6858 isOperationLegalOrCustom(ISD::FMA, VT) &&
6859 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6860 return false;
6861
6862 return true;
6863}
6864
Tim Northover3b0846e2014-05-24 12:50:23 +00006865// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6866// 64-bit GPR.
6867bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6868 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6869 return false;
6870 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6871 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006872 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006873}
6874bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006875 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006876 return false;
6877 unsigned NumBits1 = VT1.getSizeInBits();
6878 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006879 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006880}
6881
6882bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6883 EVT VT1 = Val.getValueType();
6884 if (isZExtFree(VT1, VT2)) {
6885 return true;
6886 }
6887
6888 if (Val.getOpcode() != ISD::LOAD)
6889 return false;
6890
6891 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006892 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6893 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6894 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006895}
6896
Quentin Colombet6843ac42015-03-31 20:52:32 +00006897bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6898 if (isa<FPExtInst>(Ext))
6899 return false;
6900
6901 // Vector types are next free.
6902 if (Ext->getType()->isVectorTy())
6903 return false;
6904
6905 for (const Use &U : Ext->uses()) {
6906 // The extension is free if we can fold it with a left shift in an
6907 // addressing mode or an arithmetic operation: add, sub, and cmp.
6908
6909 // Is there a shift?
6910 const Instruction *Instr = cast<Instruction>(U.getUser());
6911
6912 // Is this a constant shift?
6913 switch (Instr->getOpcode()) {
6914 case Instruction::Shl:
6915 if (!isa<ConstantInt>(Instr->getOperand(1)))
6916 return false;
6917 break;
6918 case Instruction::GetElementPtr: {
6919 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006920 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00006921 std::advance(GTI, U.getOperandNo());
6922 Type *IdxTy = *GTI;
6923 // This extension will end up with a shift because of the scaling factor.
6924 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6925 // Get the shift amount based on the scaling factor:
6926 // log2(sizeof(IdxTy)) - log2(8).
6927 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006928 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00006929 // Is the constant foldable in the shift of the addressing mode?
6930 // I.e., shift amount is between 1 and 4 inclusive.
6931 if (ShiftAmt == 0 || ShiftAmt > 4)
6932 return false;
6933 break;
6934 }
6935 case Instruction::Trunc:
6936 // Check if this is a noop.
6937 // trunc(sext ty1 to ty2) to ty1.
6938 if (Instr->getType() == Ext->getOperand(0)->getType())
6939 continue;
6940 // FALL THROUGH.
6941 default:
6942 return false;
6943 }
6944
6945 // At this point we can use the bfm family, so this extension is free
6946 // for that use.
6947 }
6948 return true;
6949}
6950
Tim Northover3b0846e2014-05-24 12:50:23 +00006951bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6952 unsigned &RequiredAligment) const {
6953 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6954 return false;
6955 // Cyclone supports unaligned accesses.
6956 RequiredAligment = 0;
6957 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6958 return NumBits == 32 || NumBits == 64;
6959}
6960
6961bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6962 unsigned &RequiredAligment) const {
6963 if (!LoadedType.isSimple() ||
6964 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6965 return false;
6966 // Cyclone supports unaligned accesses.
6967 RequiredAligment = 0;
6968 unsigned NumBits = LoadedType.getSizeInBits();
6969 return NumBits == 32 || NumBits == 64;
6970}
6971
Hao Liu7ec8ee32015-06-26 02:32:07 +00006972/// \brief Lower an interleaved load into a ldN intrinsic.
6973///
6974/// E.g. Lower an interleaved load (Factor = 2):
6975/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6976/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
6977/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
6978///
6979/// Into:
6980/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6981/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6982/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6983bool AArch64TargetLowering::lowerInterleavedLoad(
6984 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6985 ArrayRef<unsigned> Indices, unsigned Factor) const {
6986 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6987 "Invalid interleave factor");
6988 assert(!Shuffles.empty() && "Empty shufflevector input");
6989 assert(Shuffles.size() == Indices.size() &&
6990 "Unmatched number of shufflevectors and indices");
6991
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006992 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00006993
6994 VectorType *VecTy = Shuffles[0]->getType();
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006995 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00006996
Jeroen Ketemaaebca092015-10-07 14:53:29 +00006997 // Skip if we do not have NEON and skip illegal vector types.
6998 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00006999 return false;
7000
7001 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7002 // load integer vectors first and then convert to pointer vectors.
7003 Type *EltTy = VecTy->getVectorElementType();
7004 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007005 VecTy =
7006 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007007
7008 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7009 Type *Tys[2] = {VecTy, PtrTy};
7010 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7011 Intrinsic::aarch64_neon_ld3,
7012 Intrinsic::aarch64_neon_ld4};
7013 Function *LdNFunc =
7014 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7015
7016 IRBuilder<> Builder(LI);
7017 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7018
7019 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7020
7021 // Replace uses of each shufflevector with the corresponding vector loaded
7022 // by ldN.
7023 for (unsigned i = 0; i < Shuffles.size(); i++) {
7024 ShuffleVectorInst *SVI = Shuffles[i];
7025 unsigned Index = Indices[i];
7026
7027 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7028
7029 // Convert the integer vector to pointer vector if the element is pointer.
7030 if (EltTy->isPointerTy())
7031 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7032
7033 SVI->replaceAllUsesWith(SubVec);
7034 }
7035
7036 return true;
7037}
7038
7039/// \brief Get a mask consisting of sequential integers starting from \p Start.
7040///
7041/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7042static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7043 unsigned NumElts) {
7044 SmallVector<Constant *, 16> Mask;
7045 for (unsigned i = 0; i < NumElts; i++)
7046 Mask.push_back(Builder.getInt32(Start + i));
7047
7048 return ConstantVector::get(Mask);
7049}
7050
7051/// \brief Lower an interleaved store into a stN intrinsic.
7052///
7053/// E.g. Lower an interleaved store (Factor = 3):
7054/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7055/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7056/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7057///
7058/// Into:
7059/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7060/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7061/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7062/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7063///
7064/// Note that the new shufflevectors will be removed and we'll only generate one
7065/// st3 instruction in CodeGen.
7066bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7067 ShuffleVectorInst *SVI,
7068 unsigned Factor) const {
7069 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7070 "Invalid interleave factor");
7071
7072 VectorType *VecTy = SVI->getType();
7073 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7074 "Invalid interleaved store");
7075
7076 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7077 Type *EltTy = VecTy->getVectorElementType();
7078 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7079
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007080 const DataLayout &DL = SI->getModule()->getDataLayout();
7081 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007082
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007083 // Skip if we do not have NEON and skip illegal vector types.
7084 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007085 return false;
7086
7087 Value *Op0 = SVI->getOperand(0);
7088 Value *Op1 = SVI->getOperand(1);
7089 IRBuilder<> Builder(SI);
7090
7091 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7092 // vectors to integer vectors.
7093 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007094 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007095 unsigned NumOpElts =
7096 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7097
7098 // Convert to the corresponding integer vector.
7099 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7100 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7101 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7102
7103 SubVecTy = VectorType::get(IntTy, NumSubElts);
7104 }
7105
7106 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7107 Type *Tys[2] = {SubVecTy, PtrTy};
7108 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7109 Intrinsic::aarch64_neon_st3,
7110 Intrinsic::aarch64_neon_st4};
7111 Function *StNFunc =
7112 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7113
7114 SmallVector<Value *, 5> Ops;
7115
7116 // Split the shufflevector operands into sub vectors for the new stN call.
7117 for (unsigned i = 0; i < Factor; i++)
7118 Ops.push_back(Builder.CreateShuffleVector(
7119 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7120
7121 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7122 Builder.CreateCall(StNFunc, Ops);
7123 return true;
7124}
7125
Tim Northover3b0846e2014-05-24 12:50:23 +00007126static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7127 unsigned AlignCheck) {
7128 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7129 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7130}
7131
7132EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7133 unsigned SrcAlign, bool IsMemset,
7134 bool ZeroMemset,
7135 bool MemcpyStrSrc,
7136 MachineFunction &MF) const {
7137 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7138 // instruction to materialize the v2i64 zero and one store (with restrictive
7139 // addressing mode). Just do two i64 store of zero-registers.
7140 bool Fast;
7141 const Function *F = MF.getFunction();
7142 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007143 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007144 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007145 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007146 return MVT::f128;
7147
Lang Hames90333852015-04-09 03:40:33 +00007148 if (Size >= 8 &&
7149 (memOpAlign(SrcAlign, DstAlign, 8) ||
7150 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7151 return MVT::i64;
7152
7153 if (Size >= 4 &&
7154 (memOpAlign(SrcAlign, DstAlign, 4) ||
7155 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007156 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007157
7158 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007159}
7160
7161// 12-bit optionally shifted immediates are legal for adds.
7162bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7163 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7164 return true;
7165 return false;
7166}
7167
7168// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7169// immediates is the same as for an add or a sub.
7170bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7171 if (Immed < 0)
7172 Immed *= -1;
7173 return isLegalAddImmediate(Immed);
7174}
7175
7176/// isLegalAddressingMode - Return true if the addressing mode represented
7177/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007178bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7179 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007180 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007181 // AArch64 has five basic addressing modes:
7182 // reg
7183 // reg + 9-bit signed offset
7184 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7185 // reg1 + reg2
7186 // reg + SIZE_IN_BYTES * reg
7187
7188 // No global is ever allowed as a base.
7189 if (AM.BaseGV)
7190 return false;
7191
7192 // No reg+reg+imm addressing.
7193 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7194 return false;
7195
7196 // check reg + imm case:
7197 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7198 uint64_t NumBytes = 0;
7199 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007200 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007201 NumBytes = NumBits / 8;
7202 if (!isPowerOf2_64(NumBits))
7203 NumBytes = 0;
7204 }
7205
7206 if (!AM.Scale) {
7207 int64_t Offset = AM.BaseOffs;
7208
7209 // 9-bit signed offset
7210 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7211 return true;
7212
7213 // 12-bit unsigned offset
7214 unsigned shift = Log2_64(NumBytes);
7215 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7216 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7217 (Offset >> shift) << shift == Offset)
7218 return true;
7219 return false;
7220 }
7221
7222 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7223
7224 if (!AM.Scale || AM.Scale == 1 ||
7225 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7226 return true;
7227 return false;
7228}
7229
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007230int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7231 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007232 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007233 // Scaling factors are not free at all.
7234 // Operands | Rt Latency
7235 // -------------------------------------------
7236 // Rt, [Xn, Xm] | 4
7237 // -------------------------------------------
7238 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7239 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007240 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007241 // Scale represents reg2 * scale, thus account for 1 if
7242 // it is not equal to 0 or 1.
7243 return AM.Scale != 0 && AM.Scale != 1;
7244 return -1;
7245}
7246
7247bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7248 VT = VT.getScalarType();
7249
7250 if (!VT.isSimple())
7251 return false;
7252
7253 switch (VT.getSimpleVT().SimpleTy) {
7254 case MVT::f32:
7255 case MVT::f64:
7256 return true;
7257 default:
7258 break;
7259 }
7260
7261 return false;
7262}
7263
7264const MCPhysReg *
7265AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7266 // LR is a callee-save register, but we must treat it as clobbered by any call
7267 // site. Hence we include LR in the scratch registers, which are in turn added
7268 // as implicit-defs for stackmaps and patchpoints.
7269 static const MCPhysReg ScratchRegs[] = {
7270 AArch64::X16, AArch64::X17, AArch64::LR, 0
7271 };
7272 return ScratchRegs;
7273}
7274
7275bool
7276AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7277 EVT VT = N->getValueType(0);
7278 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7279 // it with shift to let it be lowered to UBFX.
7280 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7281 isa<ConstantSDNode>(N->getOperand(1))) {
7282 uint64_t TruncMask = N->getConstantOperandVal(1);
7283 if (isMask_64(TruncMask) &&
7284 N->getOperand(0).getOpcode() == ISD::SRL &&
7285 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7286 return false;
7287 }
7288 return true;
7289}
7290
7291bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7292 Type *Ty) const {
7293 assert(Ty->isIntegerTy());
7294
7295 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7296 if (BitSize == 0)
7297 return false;
7298
7299 int64_t Val = Imm.getSExtValue();
7300 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7301 return true;
7302
7303 if ((int64_t)Val < 0)
7304 Val = ~Val;
7305 if (BitSize == 32)
7306 Val &= (1LL << 32) - 1;
7307
7308 unsigned LZ = countLeadingZeros((uint64_t)Val);
7309 unsigned Shift = (63 - LZ) / 16;
7310 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007311 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007312}
7313
7314// Generate SUBS and CSEL for integer abs.
7315static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7316 EVT VT = N->getValueType(0);
7317
7318 SDValue N0 = N->getOperand(0);
7319 SDValue N1 = N->getOperand(1);
7320 SDLoc DL(N);
7321
7322 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7323 // and change it to SUB and CSEL.
7324 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7325 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7326 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7327 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7328 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007329 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007330 N0.getOperand(0));
7331 // Generate SUBS & CSEL.
7332 SDValue Cmp =
7333 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007334 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007335 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007336 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007337 SDValue(Cmp.getNode(), 1));
7338 }
7339 return SDValue();
7340}
7341
7342// performXorCombine - Attempts to handle integer ABS.
7343static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7344 TargetLowering::DAGCombinerInfo &DCI,
7345 const AArch64Subtarget *Subtarget) {
7346 if (DCI.isBeforeLegalizeOps())
7347 return SDValue();
7348
7349 return performIntegerAbsCombine(N, DAG);
7350}
7351
Chad Rosier17020f92014-07-23 14:57:52 +00007352SDValue
7353AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7354 SelectionDAG &DAG,
7355 std::vector<SDNode *> *Created) const {
7356 // fold (sdiv X, pow2)
7357 EVT VT = N->getValueType(0);
7358 if ((VT != MVT::i32 && VT != MVT::i64) ||
7359 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7360 return SDValue();
7361
7362 SDLoc DL(N);
7363 SDValue N0 = N->getOperand(0);
7364 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007365 SDValue Zero = DAG.getConstant(0, DL, VT);
7366 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007367
7368 // Add (N0 < 0) ? Pow2 - 1 : 0;
7369 SDValue CCVal;
7370 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7371 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7372 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7373
7374 if (Created) {
7375 Created->push_back(Cmp.getNode());
7376 Created->push_back(Add.getNode());
7377 Created->push_back(CSel.getNode());
7378 }
7379
7380 // Divide by pow2.
7381 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007382 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007383
7384 // If we're dividing by a positive value, we're done. Otherwise, we must
7385 // negate the result.
7386 if (Divisor.isNonNegative())
7387 return SRA;
7388
7389 if (Created)
7390 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007391 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007392}
7393
Tim Northover3b0846e2014-05-24 12:50:23 +00007394static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7395 TargetLowering::DAGCombinerInfo &DCI,
7396 const AArch64Subtarget *Subtarget) {
7397 if (DCI.isBeforeLegalizeOps())
7398 return SDValue();
7399
7400 // Multiplication of a power of two plus/minus one can be done more
7401 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7402 // future CPUs have a cheaper MADD instruction, this may need to be
7403 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7404 // 64-bit is 5 cycles, so this is always a win.
7405 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7406 APInt Value = C->getAPIntValue();
7407 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007408 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007409 if (Value.isNonNegative()) {
7410 // (mul x, 2^N + 1) => (add (shl x, N), x)
7411 APInt VM1 = Value - 1;
7412 if (VM1.isPowerOf2()) {
7413 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007414 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7415 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7416 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007417 N->getOperand(0));
7418 }
7419 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7420 APInt VP1 = Value + 1;
7421 if (VP1.isPowerOf2()) {
7422 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007423 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7424 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7425 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007426 N->getOperand(0));
7427 }
7428 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007429 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7430 APInt VNP1 = -Value + 1;
7431 if (VNP1.isPowerOf2()) {
7432 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007433 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7434 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7435 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007436 ShiftedVal);
7437 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007438 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7439 APInt VNM1 = -Value - 1;
7440 if (VNM1.isPowerOf2()) {
7441 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007442 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7443 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007444 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007445 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7446 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007447 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007448 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007449 }
7450 return SDValue();
7451}
7452
Jim Grosbachf7502c42014-07-18 00:40:52 +00007453static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7454 SelectionDAG &DAG) {
7455 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7456 // optimize away operation when it's from a constant.
7457 //
7458 // The general transformation is:
7459 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7460 // AND(VECTOR_CMP(x,y), constant2)
7461 // constant2 = UNARYOP(constant)
7462
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007463 // Early exit if this isn't a vector operation, the operand of the
7464 // unary operation isn't a bitwise AND, or if the sizes of the operations
7465 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007466 EVT VT = N->getValueType(0);
7467 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007468 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7469 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007470 return SDValue();
7471
Jim Grosbach724e4382014-07-23 20:41:43 +00007472 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007473 // make the transformation for non-constant splats as well, but it's unclear
7474 // that would be a benefit as it would not eliminate any operations, just
7475 // perform one more step in scalar code before moving to the vector unit.
7476 if (BuildVectorSDNode *BV =
7477 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007478 // Bail out if the vector isn't a constant.
7479 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007480 return SDValue();
7481
7482 // Everything checks out. Build up the new and improved node.
7483 SDLoc DL(N);
7484 EVT IntVT = BV->getValueType(0);
7485 // Create a new constant of the appropriate type for the transformed
7486 // DAG.
7487 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7488 // The AND node needs bitcasts to/from an integer vector type around it.
7489 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7490 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7491 N->getOperand(0)->getOperand(0), MaskConst);
7492 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7493 return Res;
7494 }
7495
7496 return SDValue();
7497}
7498
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007499static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7500 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007501 // First try to optimize away the conversion when it's conditionally from
7502 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007503 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007504 return Res;
7505
Tim Northover3b0846e2014-05-24 12:50:23 +00007506 EVT VT = N->getValueType(0);
7507 if (VT != MVT::f32 && VT != MVT::f64)
7508 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007509
Tim Northover3b0846e2014-05-24 12:50:23 +00007510 // Only optimize when the source and destination types have the same width.
7511 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7512 return SDValue();
7513
7514 // If the result of an integer load is only used by an integer-to-float
7515 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007516 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007517 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007518 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007519 // Do not change the width of a volatile load.
7520 !cast<LoadSDNode>(N0)->isVolatile()) {
7521 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7522 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7523 LN0->getPointerInfo(), LN0->isVolatile(),
7524 LN0->isNonTemporal(), LN0->isInvariant(),
7525 LN0->getAlignment());
7526
7527 // Make sure successors of the original load stay after it by updating them
7528 // to use the new Chain.
7529 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7530
7531 unsigned Opcode =
7532 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7533 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7534 }
7535
7536 return SDValue();
7537}
7538
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007539/// Fold a floating-point multiply by power of two into floating-point to
7540/// fixed-point conversion.
7541static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7542 const AArch64Subtarget *Subtarget) {
7543 if (!Subtarget->hasNEON())
7544 return SDValue();
7545
7546 SDValue Op = N->getOperand(0);
7547 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7548 return SDValue();
7549
7550 SDValue ConstVec = Op->getOperand(1);
7551 if (!isa<BuildVectorSDNode>(ConstVec))
7552 return SDValue();
7553
7554 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7555 uint32_t FloatBits = FloatTy.getSizeInBits();
7556 if (FloatBits != 32 && FloatBits != 64)
7557 return SDValue();
7558
7559 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7560 uint32_t IntBits = IntTy.getSizeInBits();
7561 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7562 return SDValue();
7563
7564 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7565 if (IntBits > FloatBits)
7566 return SDValue();
7567
7568 BitVector UndefElements;
7569 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7570 int32_t Bits = IntBits == 64 ? 64 : 32;
7571 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7572 if (C == -1 || C == 0 || C > Bits)
7573 return SDValue();
7574
7575 MVT ResTy;
7576 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7577 switch (NumLanes) {
7578 default:
7579 return SDValue();
7580 case 2:
7581 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7582 break;
7583 case 4:
7584 ResTy = MVT::v4i32;
7585 break;
7586 }
7587
7588 SDLoc DL(N);
7589 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7590 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7591 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7592 SDValue FixConv =
7593 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7594 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7595 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7596 // We can handle smaller integers by generating an extra trunc.
7597 if (IntBits < FloatBits)
7598 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7599
7600 return FixConv;
7601}
7602
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007603/// Fold a floating-point divide by power of two into fixed-point to
7604/// floating-point conversion.
7605static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7606 const AArch64Subtarget *Subtarget) {
7607 if (!Subtarget->hasNEON())
7608 return SDValue();
7609
7610 SDValue Op = N->getOperand(0);
7611 unsigned Opc = Op->getOpcode();
7612 if (!Op.getValueType().isVector() ||
7613 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7614 return SDValue();
7615
7616 SDValue ConstVec = N->getOperand(1);
7617 if (!isa<BuildVectorSDNode>(ConstVec))
7618 return SDValue();
7619
7620 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7621 int32_t IntBits = IntTy.getSizeInBits();
7622 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7623 return SDValue();
7624
7625 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7626 int32_t FloatBits = FloatTy.getSizeInBits();
7627 if (FloatBits != 32 && FloatBits != 64)
7628 return SDValue();
7629
7630 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7631 if (IntBits > FloatBits)
7632 return SDValue();
7633
7634 BitVector UndefElements;
7635 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7636 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7637 if (C == -1 || C == 0 || C > FloatBits)
7638 return SDValue();
7639
7640 MVT ResTy;
7641 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7642 switch (NumLanes) {
7643 default:
7644 return SDValue();
7645 case 2:
7646 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7647 break;
7648 case 4:
7649 ResTy = MVT::v4i32;
7650 break;
7651 }
7652
7653 SDLoc DL(N);
7654 SDValue ConvInput = Op.getOperand(0);
7655 bool IsSigned = Opc == ISD::SINT_TO_FP;
7656 if (IntBits < FloatBits)
7657 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7658 ResTy, ConvInput);
7659
7660 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7661 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7662 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7663 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7664 DAG.getConstant(C, DL, MVT::i32));
7665}
7666
Tim Northover3b0846e2014-05-24 12:50:23 +00007667/// An EXTR instruction is made up of two shifts, ORed together. This helper
7668/// searches for and classifies those shifts.
7669static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7670 bool &FromHi) {
7671 if (N.getOpcode() == ISD::SHL)
7672 FromHi = false;
7673 else if (N.getOpcode() == ISD::SRL)
7674 FromHi = true;
7675 else
7676 return false;
7677
7678 if (!isa<ConstantSDNode>(N.getOperand(1)))
7679 return false;
7680
7681 ShiftAmount = N->getConstantOperandVal(1);
7682 Src = N->getOperand(0);
7683 return true;
7684}
7685
7686/// EXTR instruction extracts a contiguous chunk of bits from two existing
7687/// registers viewed as a high/low pair. This function looks for the pattern:
7688/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7689/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7690/// independent.
7691static SDValue tryCombineToEXTR(SDNode *N,
7692 TargetLowering::DAGCombinerInfo &DCI) {
7693 SelectionDAG &DAG = DCI.DAG;
7694 SDLoc DL(N);
7695 EVT VT = N->getValueType(0);
7696
7697 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7698
7699 if (VT != MVT::i32 && VT != MVT::i64)
7700 return SDValue();
7701
7702 SDValue LHS;
7703 uint32_t ShiftLHS = 0;
7704 bool LHSFromHi = 0;
7705 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7706 return SDValue();
7707
7708 SDValue RHS;
7709 uint32_t ShiftRHS = 0;
7710 bool RHSFromHi = 0;
7711 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7712 return SDValue();
7713
7714 // If they're both trying to come from the high part of the register, they're
7715 // not really an EXTR.
7716 if (LHSFromHi == RHSFromHi)
7717 return SDValue();
7718
7719 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7720 return SDValue();
7721
7722 if (LHSFromHi) {
7723 std::swap(LHS, RHS);
7724 std::swap(ShiftLHS, ShiftRHS);
7725 }
7726
7727 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007728 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007729}
7730
7731static SDValue tryCombineToBSL(SDNode *N,
7732 TargetLowering::DAGCombinerInfo &DCI) {
7733 EVT VT = N->getValueType(0);
7734 SelectionDAG &DAG = DCI.DAG;
7735 SDLoc DL(N);
7736
7737 if (!VT.isVector())
7738 return SDValue();
7739
7740 SDValue N0 = N->getOperand(0);
7741 if (N0.getOpcode() != ISD::AND)
7742 return SDValue();
7743
7744 SDValue N1 = N->getOperand(1);
7745 if (N1.getOpcode() != ISD::AND)
7746 return SDValue();
7747
7748 // We only have to look for constant vectors here since the general, variable
7749 // case can be handled in TableGen.
7750 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7751 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7752 for (int i = 1; i >= 0; --i)
7753 for (int j = 1; j >= 0; --j) {
7754 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7755 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7756 if (!BVN0 || !BVN1)
7757 continue;
7758
7759 bool FoundMatch = true;
7760 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7761 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7762 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7763 if (!CN0 || !CN1 ||
7764 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7765 FoundMatch = false;
7766 break;
7767 }
7768 }
7769
7770 if (FoundMatch)
7771 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7772 N0->getOperand(1 - i), N1->getOperand(1 - j));
7773 }
7774
7775 return SDValue();
7776}
7777
7778static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7779 const AArch64Subtarget *Subtarget) {
7780 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7781 if (!EnableAArch64ExtrGeneration)
7782 return SDValue();
7783 SelectionDAG &DAG = DCI.DAG;
7784 EVT VT = N->getValueType(0);
7785
7786 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7787 return SDValue();
7788
7789 SDValue Res = tryCombineToEXTR(N, DCI);
7790 if (Res.getNode())
7791 return Res;
7792
7793 Res = tryCombineToBSL(N, DCI);
7794 if (Res.getNode())
7795 return Res;
7796
7797 return SDValue();
7798}
7799
7800static SDValue performBitcastCombine(SDNode *N,
7801 TargetLowering::DAGCombinerInfo &DCI,
7802 SelectionDAG &DAG) {
7803 // Wait 'til after everything is legalized to try this. That way we have
7804 // legal vector types and such.
7805 if (DCI.isBeforeLegalizeOps())
7806 return SDValue();
7807
7808 // Remove extraneous bitcasts around an extract_subvector.
7809 // For example,
7810 // (v4i16 (bitconvert
7811 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7812 // becomes
7813 // (extract_subvector ((v8i16 ...), (i64 4)))
7814
7815 // Only interested in 64-bit vectors as the ultimate result.
7816 EVT VT = N->getValueType(0);
7817 if (!VT.isVector())
7818 return SDValue();
7819 if (VT.getSimpleVT().getSizeInBits() != 64)
7820 return SDValue();
7821 // Is the operand an extract_subvector starting at the beginning or halfway
7822 // point of the vector? A low half may also come through as an
7823 // EXTRACT_SUBREG, so look for that, too.
7824 SDValue Op0 = N->getOperand(0);
7825 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7826 !(Op0->isMachineOpcode() &&
7827 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7828 return SDValue();
7829 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7830 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7831 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7832 return SDValue();
7833 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7834 if (idx != AArch64::dsub)
7835 return SDValue();
7836 // The dsub reference is equivalent to a lane zero subvector reference.
7837 idx = 0;
7838 }
7839 // Look through the bitcast of the input to the extract.
7840 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7841 return SDValue();
7842 SDValue Source = Op0->getOperand(0)->getOperand(0);
7843 // If the source type has twice the number of elements as our destination
7844 // type, we know this is an extract of the high or low half of the vector.
7845 EVT SVT = Source->getValueType(0);
7846 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7847 return SDValue();
7848
7849 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7850
7851 // Create the simplified form to just extract the low or high half of the
7852 // vector directly rather than bothering with the bitcasts.
7853 SDLoc dl(N);
7854 unsigned NumElements = VT.getVectorNumElements();
7855 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007856 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007857 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7858 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007859 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007860 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7861 Source, SubReg),
7862 0);
7863 }
7864}
7865
7866static SDValue performConcatVectorsCombine(SDNode *N,
7867 TargetLowering::DAGCombinerInfo &DCI,
7868 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007869 SDLoc dl(N);
7870 EVT VT = N->getValueType(0);
7871 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7872
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007873 // Optimize concat_vectors of truncated vectors, where the intermediate
7874 // type is illegal, to avoid said illegality, e.g.,
7875 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7876 // (v2i16 (truncate (v2i64)))))
7877 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007878 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7879 // (v4i32 (bitcast (v2i64))),
7880 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007881 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7882 // on both input and result type, so we might generate worse code.
7883 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7884 if (N->getNumOperands() == 2 &&
7885 N0->getOpcode() == ISD::TRUNCATE &&
7886 N1->getOpcode() == ISD::TRUNCATE) {
7887 SDValue N00 = N0->getOperand(0);
7888 SDValue N10 = N1->getOperand(0);
7889 EVT N00VT = N00.getValueType();
7890
7891 if (N00VT == N10.getValueType() &&
7892 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7893 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007894 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7895 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7896 for (size_t i = 0; i < Mask.size(); ++i)
7897 Mask[i] = i * 2;
7898 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7899 DAG.getVectorShuffle(
7900 MidVT, dl,
7901 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7902 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007903 }
7904 }
7905
Tim Northover3b0846e2014-05-24 12:50:23 +00007906 // Wait 'til after everything is legalized to try this. That way we have
7907 // legal vector types and such.
7908 if (DCI.isBeforeLegalizeOps())
7909 return SDValue();
7910
Tim Northover3b0846e2014-05-24 12:50:23 +00007911 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7912 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7913 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007914 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007915 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007916 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007917 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007918 }
7919
7920 // Canonicalise concat_vectors so that the right-hand vector has as few
7921 // bit-casts as possible before its real operation. The primary matching
7922 // destination for these operations will be the narrowing "2" instructions,
7923 // which depend on the operation being performed on this right-hand vector.
7924 // For example,
7925 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7926 // becomes
7927 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7928
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007929 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00007930 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007931 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007932 MVT RHSTy = RHS.getValueType().getSimpleVT();
7933 // If the RHS is not a vector, this is not the pattern we're looking for.
7934 if (!RHSTy.isVector())
7935 return SDValue();
7936
7937 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7938
7939 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7940 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007941 return DAG.getNode(ISD::BITCAST, dl, VT,
7942 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7943 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7944 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00007945}
7946
7947static SDValue tryCombineFixedPointConvert(SDNode *N,
7948 TargetLowering::DAGCombinerInfo &DCI,
7949 SelectionDAG &DAG) {
7950 // Wait 'til after everything is legalized to try this. That way we have
7951 // legal vector types and such.
7952 if (DCI.isBeforeLegalizeOps())
7953 return SDValue();
7954 // Transform a scalar conversion of a value from a lane extract into a
7955 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7956 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7957 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7958 //
7959 // The second form interacts better with instruction selection and the
7960 // register allocator to avoid cross-class register copies that aren't
7961 // coalescable due to a lane reference.
7962
7963 // Check the operand and see if it originates from a lane extract.
7964 SDValue Op1 = N->getOperand(1);
7965 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7966 // Yep, no additional predication needed. Perform the transform.
7967 SDValue IID = N->getOperand(0);
7968 SDValue Shift = N->getOperand(2);
7969 SDValue Vec = Op1.getOperand(0);
7970 SDValue Lane = Op1.getOperand(1);
7971 EVT ResTy = N->getValueType(0);
7972 EVT VecResTy;
7973 SDLoc DL(N);
7974
7975 // The vector width should be 128 bits by the time we get here, even
7976 // if it started as 64 bits (the extract_vector handling will have
7977 // done so).
7978 assert(Vec.getValueType().getSizeInBits() == 128 &&
7979 "unexpected vector size on extract_vector_elt!");
7980 if (Vec.getValueType() == MVT::v4i32)
7981 VecResTy = MVT::v4f32;
7982 else if (Vec.getValueType() == MVT::v2i64)
7983 VecResTy = MVT::v2f64;
7984 else
Craig Topper2a30d782014-06-18 05:05:13 +00007985 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007986
7987 SDValue Convert =
7988 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7989 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7990 }
7991 return SDValue();
7992}
7993
7994// AArch64 high-vector "long" operations are formed by performing the non-high
7995// version on an extract_subvector of each operand which gets the high half:
7996//
7997// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7998//
7999// However, there are cases which don't have an extract_high explicitly, but
8000// have another operation that can be made compatible with one for free. For
8001// example:
8002//
8003// (dupv64 scalar) --> (extract_high (dup128 scalar))
8004//
8005// This routine does the actual conversion of such DUPs, once outer routines
8006// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008007// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8008// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008009static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008010 switch (N.getOpcode()) {
8011 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008012 case AArch64ISD::DUPLANE8:
8013 case AArch64ISD::DUPLANE16:
8014 case AArch64ISD::DUPLANE32:
8015 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008016 case AArch64ISD::MOVI:
8017 case AArch64ISD::MOVIshift:
8018 case AArch64ISD::MOVIedit:
8019 case AArch64ISD::MOVImsl:
8020 case AArch64ISD::MVNIshift:
8021 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008022 break;
8023 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008024 // FMOV could be supported, but isn't very useful, as it would only occur
8025 // if you passed a bitcast' floating point immediate to an eligible long
8026 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008027 return SDValue();
8028 }
8029
8030 MVT NarrowTy = N.getSimpleValueType();
8031 if (!NarrowTy.is64BitVector())
8032 return SDValue();
8033
8034 MVT ElementTy = NarrowTy.getVectorElementType();
8035 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008036 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008037
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008038 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008039 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8040 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008041 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008042}
8043
8044static bool isEssentiallyExtractSubvector(SDValue N) {
8045 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8046 return true;
8047
8048 return N.getOpcode() == ISD::BITCAST &&
8049 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8050}
8051
8052/// \brief Helper structure to keep track of ISD::SET_CC operands.
8053struct GenericSetCCInfo {
8054 const SDValue *Opnd0;
8055 const SDValue *Opnd1;
8056 ISD::CondCode CC;
8057};
8058
8059/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8060struct AArch64SetCCInfo {
8061 const SDValue *Cmp;
8062 AArch64CC::CondCode CC;
8063};
8064
8065/// \brief Helper structure to keep track of SetCC information.
8066union SetCCInfo {
8067 GenericSetCCInfo Generic;
8068 AArch64SetCCInfo AArch64;
8069};
8070
8071/// \brief Helper structure to be able to read SetCC information. If set to
8072/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8073/// GenericSetCCInfo.
8074struct SetCCInfoAndKind {
8075 SetCCInfo Info;
8076 bool IsAArch64;
8077};
8078
8079/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8080/// an
8081/// AArch64 lowered one.
8082/// \p SetCCInfo is filled accordingly.
8083/// \post SetCCInfo is meanginfull only when this function returns true.
8084/// \return True when Op is a kind of SET_CC operation.
8085static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8086 // If this is a setcc, this is straight forward.
8087 if (Op.getOpcode() == ISD::SETCC) {
8088 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8089 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8090 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8091 SetCCInfo.IsAArch64 = false;
8092 return true;
8093 }
8094 // Otherwise, check if this is a matching csel instruction.
8095 // In other words:
8096 // - csel 1, 0, cc
8097 // - csel 0, 1, !cc
8098 if (Op.getOpcode() != AArch64ISD::CSEL)
8099 return false;
8100 // Set the information about the operands.
8101 // TODO: we want the operands of the Cmp not the csel
8102 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8103 SetCCInfo.IsAArch64 = true;
8104 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8105 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8106
8107 // Check that the operands matches the constraints:
8108 // (1) Both operands must be constants.
8109 // (2) One must be 1 and the other must be 0.
8110 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8111 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8112
8113 // Check (1).
8114 if (!TValue || !FValue)
8115 return false;
8116
8117 // Check (2).
8118 if (!TValue->isOne()) {
8119 // Update the comparison when we are interested in !cc.
8120 std::swap(TValue, FValue);
8121 SetCCInfo.Info.AArch64.CC =
8122 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8123 }
8124 return TValue->isOne() && FValue->isNullValue();
8125}
8126
8127// Returns true if Op is setcc or zext of setcc.
8128static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8129 if (isSetCC(Op, Info))
8130 return true;
8131 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8132 isSetCC(Op->getOperand(0), Info));
8133}
8134
8135// The folding we want to perform is:
8136// (add x, [zext] (setcc cc ...) )
8137// -->
8138// (csel x, (add x, 1), !cc ...)
8139//
8140// The latter will get matched to a CSINC instruction.
8141static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8142 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8143 SDValue LHS = Op->getOperand(0);
8144 SDValue RHS = Op->getOperand(1);
8145 SetCCInfoAndKind InfoAndKind;
8146
8147 // If neither operand is a SET_CC, give up.
8148 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8149 std::swap(LHS, RHS);
8150 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8151 return SDValue();
8152 }
8153
8154 // FIXME: This could be generatized to work for FP comparisons.
8155 EVT CmpVT = InfoAndKind.IsAArch64
8156 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8157 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8158 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8159 return SDValue();
8160
8161 SDValue CCVal;
8162 SDValue Cmp;
8163 SDLoc dl(Op);
8164 if (InfoAndKind.IsAArch64) {
8165 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008166 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8167 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008168 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8169 } else
8170 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8171 *InfoAndKind.Info.Generic.Opnd1,
8172 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8173 CCVal, DAG, dl);
8174
8175 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008176 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008177 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8178}
8179
8180// The basic add/sub long vector instructions have variants with "2" on the end
8181// which act on the high-half of their inputs. They are normally matched by
8182// patterns like:
8183//
8184// (add (zeroext (extract_high LHS)),
8185// (zeroext (extract_high RHS)))
8186// -> uaddl2 vD, vN, vM
8187//
8188// However, if one of the extracts is something like a duplicate, this
8189// instruction can still be used profitably. This function puts the DAG into a
8190// more appropriate form for those patterns to trigger.
8191static SDValue performAddSubLongCombine(SDNode *N,
8192 TargetLowering::DAGCombinerInfo &DCI,
8193 SelectionDAG &DAG) {
8194 if (DCI.isBeforeLegalizeOps())
8195 return SDValue();
8196
8197 MVT VT = N->getSimpleValueType(0);
8198 if (!VT.is128BitVector()) {
8199 if (N->getOpcode() == ISD::ADD)
8200 return performSetccAddFolding(N, DAG);
8201 return SDValue();
8202 }
8203
8204 // Make sure both branches are extended in the same way.
8205 SDValue LHS = N->getOperand(0);
8206 SDValue RHS = N->getOperand(1);
8207 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8208 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8209 LHS.getOpcode() != RHS.getOpcode())
8210 return SDValue();
8211
8212 unsigned ExtType = LHS.getOpcode();
8213
8214 // It's not worth doing if at least one of the inputs isn't already an
8215 // extract, but we don't know which it'll be so we have to try both.
8216 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8217 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8218 if (!RHS.getNode())
8219 return SDValue();
8220
8221 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8222 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8223 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8224 if (!LHS.getNode())
8225 return SDValue();
8226
8227 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8228 }
8229
8230 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8231}
8232
8233// Massage DAGs which we can use the high-half "long" operations on into
8234// something isel will recognize better. E.g.
8235//
8236// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8237// (aarch64_neon_umull (extract_high (v2i64 vec)))
8238// (extract_high (v2i64 (dup128 scalar)))))
8239//
James Molloyfaf4e3c2015-07-17 17:10:45 +00008240static SDValue tryCombineLongOpWithDup(SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008241 TargetLowering::DAGCombinerInfo &DCI,
8242 SelectionDAG &DAG) {
8243 if (DCI.isBeforeLegalizeOps())
8244 return SDValue();
8245
James Molloyfaf4e3c2015-07-17 17:10:45 +00008246 bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8247 SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8248 SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
Tim Northover3b0846e2014-05-24 12:50:23 +00008249 assert(LHS.getValueType().is64BitVector() &&
8250 RHS.getValueType().is64BitVector() &&
8251 "unexpected shape for long operation");
8252
8253 // Either node could be a DUP, but it's not worth doing both of them (you'd
8254 // just as well use the non-high version) so look for a corresponding extract
8255 // operation on the other "wing".
8256 if (isEssentiallyExtractSubvector(LHS)) {
8257 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8258 if (!RHS.getNode())
8259 return SDValue();
8260 } else if (isEssentiallyExtractSubvector(RHS)) {
8261 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8262 if (!LHS.getNode())
8263 return SDValue();
8264 }
8265
James Molloyfaf4e3c2015-07-17 17:10:45 +00008266 // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8267 if (IsIntrinsic)
8268 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8269 N->getOperand(0), LHS, RHS);
8270 else
8271 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8272 LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008273}
8274
8275static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8276 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8277 unsigned ElemBits = ElemTy.getSizeInBits();
8278
8279 int64_t ShiftAmount;
8280 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8281 APInt SplatValue, SplatUndef;
8282 unsigned SplatBitSize;
8283 bool HasAnyUndefs;
8284 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8285 HasAnyUndefs, ElemBits) ||
8286 SplatBitSize != ElemBits)
8287 return SDValue();
8288
8289 ShiftAmount = SplatValue.getSExtValue();
8290 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8291 ShiftAmount = CVN->getSExtValue();
8292 } else
8293 return SDValue();
8294
8295 unsigned Opcode;
8296 bool IsRightShift;
8297 switch (IID) {
8298 default:
8299 llvm_unreachable("Unknown shift intrinsic");
8300 case Intrinsic::aarch64_neon_sqshl:
8301 Opcode = AArch64ISD::SQSHL_I;
8302 IsRightShift = false;
8303 break;
8304 case Intrinsic::aarch64_neon_uqshl:
8305 Opcode = AArch64ISD::UQSHL_I;
8306 IsRightShift = false;
8307 break;
8308 case Intrinsic::aarch64_neon_srshl:
8309 Opcode = AArch64ISD::SRSHR_I;
8310 IsRightShift = true;
8311 break;
8312 case Intrinsic::aarch64_neon_urshl:
8313 Opcode = AArch64ISD::URSHR_I;
8314 IsRightShift = true;
8315 break;
8316 case Intrinsic::aarch64_neon_sqshlu:
8317 Opcode = AArch64ISD::SQSHLU_I;
8318 IsRightShift = false;
8319 break;
8320 }
8321
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008322 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8323 SDLoc dl(N);
8324 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8325 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8326 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8327 SDLoc dl(N);
8328 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8329 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8330 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008331
8332 return SDValue();
8333}
8334
8335// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8336// the intrinsics must be legal and take an i32, this means there's almost
8337// certainly going to be a zext in the DAG which we can eliminate.
8338static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8339 SDValue AndN = N->getOperand(2);
8340 if (AndN.getOpcode() != ISD::AND)
8341 return SDValue();
8342
8343 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8344 if (!CMask || CMask->getZExtValue() != Mask)
8345 return SDValue();
8346
8347 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8348 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8349}
8350
Ahmed Bougachafab58922015-03-10 20:45:38 +00008351static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8352 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008353 SDLoc dl(N);
8354 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8355 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008356 N->getOperand(1).getSimpleValueType(),
8357 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008358 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008359}
8360
Tim Northover3b0846e2014-05-24 12:50:23 +00008361static SDValue performIntrinsicCombine(SDNode *N,
8362 TargetLowering::DAGCombinerInfo &DCI,
8363 const AArch64Subtarget *Subtarget) {
8364 SelectionDAG &DAG = DCI.DAG;
8365 unsigned IID = getIntrinsicID(N);
8366 switch (IID) {
8367 default:
8368 break;
8369 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8370 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8371 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008372 case Intrinsic::aarch64_neon_saddv:
8373 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8374 case Intrinsic::aarch64_neon_uaddv:
8375 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8376 case Intrinsic::aarch64_neon_sminv:
8377 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8378 case Intrinsic::aarch64_neon_uminv:
8379 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8380 case Intrinsic::aarch64_neon_smaxv:
8381 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8382 case Intrinsic::aarch64_neon_umaxv:
8383 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008384 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008385 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008386 N->getOperand(1), N->getOperand(2));
8387 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008388 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008389 N->getOperand(1), N->getOperand(2));
James Molloyfaf4e3c2015-07-17 17:10:45 +00008390 case Intrinsic::aarch64_neon_sabd:
8391 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8392 N->getOperand(1), N->getOperand(2));
8393 case Intrinsic::aarch64_neon_uabd:
8394 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8395 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008396 case Intrinsic::aarch64_neon_fmaxnm:
8397 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8398 N->getOperand(1), N->getOperand(2));
8399 case Intrinsic::aarch64_neon_fminnm:
8400 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8401 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008402 case Intrinsic::aarch64_neon_smull:
8403 case Intrinsic::aarch64_neon_umull:
8404 case Intrinsic::aarch64_neon_pmull:
8405 case Intrinsic::aarch64_neon_sqdmull:
James Molloyfaf4e3c2015-07-17 17:10:45 +00008406 return tryCombineLongOpWithDup(N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008407 case Intrinsic::aarch64_neon_sqshl:
8408 case Intrinsic::aarch64_neon_uqshl:
8409 case Intrinsic::aarch64_neon_sqshlu:
8410 case Intrinsic::aarch64_neon_srshl:
8411 case Intrinsic::aarch64_neon_urshl:
8412 return tryCombineShiftImm(IID, N, DAG);
8413 case Intrinsic::aarch64_crc32b:
8414 case Intrinsic::aarch64_crc32cb:
8415 return tryCombineCRC32(0xff, N, DAG);
8416 case Intrinsic::aarch64_crc32h:
8417 case Intrinsic::aarch64_crc32ch:
8418 return tryCombineCRC32(0xffff, N, DAG);
8419 }
8420 return SDValue();
8421}
8422
8423static SDValue performExtendCombine(SDNode *N,
8424 TargetLowering::DAGCombinerInfo &DCI,
8425 SelectionDAG &DAG) {
8426 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8427 // we can convert that DUP into another extract_high (of a bigger DUP), which
8428 // helps the backend to decide that an sabdl2 would be useful, saving a real
8429 // extract_high operation.
8430 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
James Molloyfaf4e3c2015-07-17 17:10:45 +00008431 (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8432 N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008433 SDNode *ABDNode = N->getOperand(0).getNode();
James Molloyfaf4e3c2015-07-17 17:10:45 +00008434 SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8435 if (!NewABD.getNode())
8436 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008437
James Molloyfaf4e3c2015-07-17 17:10:45 +00008438 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8439 NewABD);
Tim Northover3b0846e2014-05-24 12:50:23 +00008440 }
8441
8442 // This is effectively a custom type legalization for AArch64.
8443 //
8444 // Type legalization will split an extend of a small, legal, type to a larger
8445 // illegal type by first splitting the destination type, often creating
8446 // illegal source types, which then get legalized in isel-confusing ways,
8447 // leading to really terrible codegen. E.g.,
8448 // %result = v8i32 sext v8i8 %value
8449 // becomes
8450 // %losrc = extract_subreg %value, ...
8451 // %hisrc = extract_subreg %value, ...
8452 // %lo = v4i32 sext v4i8 %losrc
8453 // %hi = v4i32 sext v4i8 %hisrc
8454 // Things go rapidly downhill from there.
8455 //
8456 // For AArch64, the [sz]ext vector instructions can only go up one element
8457 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8458 // take two instructions.
8459 //
8460 // This implies that the most efficient way to do the extend from v8i8
8461 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8462 // the normal splitting to happen for the v8i16->v8i32.
8463
8464 // This is pre-legalization to catch some cases where the default
8465 // type legalization will create ill-tempered code.
8466 if (!DCI.isBeforeLegalizeOps())
8467 return SDValue();
8468
8469 // We're only interested in cleaning things up for non-legal vector types
8470 // here. If both the source and destination are legal, things will just
8471 // work naturally without any fiddling.
8472 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8473 EVT ResVT = N->getValueType(0);
8474 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8475 return SDValue();
8476 // If the vector type isn't a simple VT, it's beyond the scope of what
8477 // we're worried about here. Let legalization do its thing and hope for
8478 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008479 SDValue Src = N->getOperand(0);
8480 EVT SrcVT = Src->getValueType(0);
8481 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008482 return SDValue();
8483
Tim Northover3b0846e2014-05-24 12:50:23 +00008484 // If the source VT is a 64-bit vector, we can play games and get the
8485 // better results we want.
8486 if (SrcVT.getSizeInBits() != 64)
8487 return SDValue();
8488
8489 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8490 unsigned ElementCount = SrcVT.getVectorNumElements();
8491 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8492 SDLoc DL(N);
8493 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8494
8495 // Now split the rest of the operation into two halves, each with a 64
8496 // bit source.
8497 EVT LoVT, HiVT;
8498 SDValue Lo, Hi;
8499 unsigned NumElements = ResVT.getVectorNumElements();
8500 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8501 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8502 ResVT.getVectorElementType(), NumElements / 2);
8503
8504 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8505 LoVT.getVectorNumElements());
8506 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008507 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008508 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008509 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008510 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8511 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8512
8513 // Now combine the parts back together so we still have a single result
8514 // like the combiner expects.
8515 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8516}
8517
8518/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8519/// value. The load store optimizer pass will merge them to store pair stores.
8520/// This has better performance than a splat of the scalar followed by a split
8521/// vector store. Even if the stores are not merged it is four stores vs a dup,
8522/// followed by an ext.b and two stores.
8523static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8524 SDValue StVal = St->getValue();
8525 EVT VT = StVal.getValueType();
8526
8527 // Don't replace floating point stores, they possibly won't be transformed to
8528 // stp because of the store pair suppress pass.
8529 if (VT.isFloatingPoint())
8530 return SDValue();
8531
8532 // Check for insert vector elements.
8533 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8534 return SDValue();
8535
8536 // We can express a splat as store pair(s) for 2 or 4 elements.
8537 unsigned NumVecElts = VT.getVectorNumElements();
8538 if (NumVecElts != 4 && NumVecElts != 2)
8539 return SDValue();
8540 SDValue SplatVal = StVal.getOperand(1);
8541 unsigned RemainInsertElts = NumVecElts - 1;
8542
8543 // Check that this is a splat.
8544 while (--RemainInsertElts) {
8545 SDValue NextInsertElt = StVal.getOperand(0);
8546 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8547 return SDValue();
8548 if (NextInsertElt.getOperand(1) != SplatVal)
8549 return SDValue();
8550 StVal = NextInsertElt;
8551 }
8552 unsigned OrigAlignment = St->getAlignment();
8553 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8554 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8555
8556 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008557 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008558 // Most of the time the three stores should be replaced by store pair
8559 // instructions (stp).
8560 SDLoc DL(St);
8561 SDValue BasePtr = St->getBasePtr();
8562 SDValue NewST1 =
8563 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8564 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8565
8566 unsigned Offset = EltOffset;
8567 while (--NumVecElts) {
8568 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008569 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008570 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8571 St->getPointerInfo(), St->isVolatile(),
8572 St->isNonTemporal(), Alignment);
8573 Offset += EltOffset;
8574 }
8575 return NewST1;
8576}
8577
Tim Northover339c83e2015-11-10 00:44:23 +00008578static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8579 SelectionDAG &DAG,
8580 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008581 if (!DCI.isBeforeLegalize())
8582 return SDValue();
8583
8584 StoreSDNode *S = cast<StoreSDNode>(N);
8585 if (S->isVolatile())
8586 return SDValue();
8587
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008588 // FIXME: The logic for deciding if an unaligned store should be split should
8589 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8590 // a call to that function here.
8591
Tim Northover3b0846e2014-05-24 12:50:23 +00008592 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008593 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008594 if (!Subtarget->isCyclone())
8595 return SDValue();
8596
Sanjay Patel924879a2015-08-04 15:49:57 +00008597 // Don't split at -Oz.
8598 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008599 return SDValue();
8600
8601 SDValue StVal = S->getValue();
8602 EVT VT = StVal.getValueType();
8603
8604 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8605 // those up regresses performance on micro-benchmarks and olden/bh.
8606 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8607 return SDValue();
8608
8609 // Split unaligned 16B stores. They are terrible for performance.
8610 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8611 // extensions can use this to mark that it does not want splitting to happen
8612 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8613 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8614 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8615 S->getAlignment() <= 2)
8616 return SDValue();
8617
8618 // If we get a splat of a scalar convert this vector store to a store of
8619 // scalars. They will be merged into store pairs thereby removing two
8620 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008621 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008622 return ReplacedSplat;
8623
8624 SDLoc DL(S);
8625 unsigned NumElts = VT.getVectorNumElements() / 2;
8626 // Split VT into two.
8627 EVT HalfVT =
8628 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8629 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008630 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008631 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008632 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008633 SDValue BasePtr = S->getBasePtr();
8634 SDValue NewST1 =
8635 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8636 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8637 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008638 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008639 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8640 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8641 S->getAlignment());
8642}
8643
8644/// Target-specific DAG combine function for post-increment LD1 (lane) and
8645/// post-increment LD1R.
8646static SDValue performPostLD1Combine(SDNode *N,
8647 TargetLowering::DAGCombinerInfo &DCI,
8648 bool IsLaneOp) {
8649 if (DCI.isBeforeLegalizeOps())
8650 return SDValue();
8651
8652 SelectionDAG &DAG = DCI.DAG;
8653 EVT VT = N->getValueType(0);
8654
8655 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8656 SDNode *LD = N->getOperand(LoadIdx).getNode();
8657 // If it is not LOAD, can not do such combine.
8658 if (LD->getOpcode() != ISD::LOAD)
8659 return SDValue();
8660
8661 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8662 EVT MemVT = LoadSDN->getMemoryVT();
8663 // Check if memory operand is the same type as the vector element.
8664 if (MemVT != VT.getVectorElementType())
8665 return SDValue();
8666
8667 // Check if there are other uses. If so, do not combine as it will introduce
8668 // an extra load.
8669 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8670 ++UI) {
8671 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8672 continue;
8673 if (*UI != N)
8674 return SDValue();
8675 }
8676
8677 SDValue Addr = LD->getOperand(1);
8678 SDValue Vector = N->getOperand(0);
8679 // Search for a use of the address operand that is an increment.
8680 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8681 Addr.getNode()->use_end(); UI != UE; ++UI) {
8682 SDNode *User = *UI;
8683 if (User->getOpcode() != ISD::ADD
8684 || UI.getUse().getResNo() != Addr.getResNo())
8685 continue;
8686
8687 // Check that the add is independent of the load. Otherwise, folding it
8688 // would create a cycle.
8689 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8690 continue;
8691 // Also check that add is not used in the vector operand. This would also
8692 // create a cycle.
8693 if (User->isPredecessorOf(Vector.getNode()))
8694 continue;
8695
8696 // If the increment is a constant, it must match the memory ref size.
8697 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8698 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8699 uint32_t IncVal = CInc->getZExtValue();
8700 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8701 if (IncVal != NumBytes)
8702 continue;
8703 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8704 }
8705
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008706 // Finally, check that the vector doesn't depend on the load.
8707 // Again, this would create a cycle.
8708 // The load depending on the vector is fine, as that's the case for the
8709 // LD1*post we'll eventually generate anyway.
8710 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8711 continue;
8712
Tim Northover3b0846e2014-05-24 12:50:23 +00008713 SmallVector<SDValue, 8> Ops;
8714 Ops.push_back(LD->getOperand(0)); // Chain
8715 if (IsLaneOp) {
8716 Ops.push_back(Vector); // The vector to be inserted
8717 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8718 }
8719 Ops.push_back(Addr);
8720 Ops.push_back(Inc);
8721
8722 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008723 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008724 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8725 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8726 MemVT,
8727 LoadSDN->getMemOperand());
8728
8729 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008730 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008731 NewResults.push_back(SDValue(LD, 0)); // The result of load
8732 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8733 DCI.CombineTo(LD, NewResults);
8734 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8735 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8736
8737 break;
8738 }
8739 return SDValue();
8740}
8741
Tim Northover339c83e2015-11-10 00:44:23 +00008742/// Simplify \Addr given that the top byte of it is ignored by HW during
8743/// address translation.
8744static bool performTBISimplification(SDValue Addr,
8745 TargetLowering::DAGCombinerInfo &DCI,
8746 SelectionDAG &DAG) {
8747 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8748 APInt KnownZero, KnownOne;
8749 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8750 DCI.isBeforeLegalizeOps());
8751 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8752 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8753 DCI.CommitTargetLoweringOpt(TLO);
8754 return true;
8755 }
8756 return false;
8757}
8758
8759static SDValue performSTORECombine(SDNode *N,
8760 TargetLowering::DAGCombinerInfo &DCI,
8761 SelectionDAG &DAG,
8762 const AArch64Subtarget *Subtarget) {
8763 SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8764 if (Split.getNode())
8765 return Split;
8766
8767 if (Subtarget->supportsAddressTopByteIgnored() &&
8768 performTBISimplification(N->getOperand(2), DCI, DAG))
8769 return SDValue(N, 0);
8770
8771 return SDValue();
8772}
8773
8774 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008775/// LoopVectorizer for the across vector reduction. It consists of
8776/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8777/// are reduced, where s is an induction variable from 0 to
8778/// log2(NumVectorElements).
8779static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8780 unsigned Op,
8781 SelectionDAG &DAG) {
8782 EVT VTy = OpV->getOperand(0).getValueType();
8783 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008784 return SDValue();
8785
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008786 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008787 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8788 if (NumVecElts != 4)
8789 return SDValue();
8790 } else {
8791 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8792 return SDValue();
8793 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008794
8795 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008796 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008797 // Iterate over each step of the across vector reduction.
8798 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008799 SDValue CurOp = PreOp.getOperand(0);
8800 SDValue Shuffle = PreOp.getOperand(1);
8801 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008802 // Try to swap the 1st and 2nd operand as add and min/max instructions
8803 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008804 CurOp = PreOp.getOperand(1);
8805 Shuffle = PreOp.getOperand(0);
8806 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8807 return SDValue();
8808 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008809
8810 // Check if the input vector is fed by the operator we want to handle,
8811 // except the last step; the very first input vector is not necessarily
8812 // the same operator we are handling.
8813 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8814 return SDValue();
8815
Chad Rosier6c36eff2015-09-03 18:13:57 +00008816 // Check if it forms one step of the across vector reduction.
8817 // E.g.,
8818 // %cur = add %1, %0
8819 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8820 // %pre = add %cur, %shuffle
8821 if (Shuffle.getOperand(0) != CurOp)
8822 return SDValue();
8823
8824 int NumMaskElts = 1 << CurStep;
8825 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8826 // Check mask values in each step.
8827 // We expect the shuffle mask in each step follows a specific pattern
8828 // denoted here by the <M, U> form, where M is a sequence of integers
8829 // starting from NumMaskElts, increasing by 1, and the number integers
8830 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8831 // of undef in U should be NumVecElts - NumMaskElts.
8832 // E.g., for <8 x i16>, mask values in each step should be :
8833 // step 0 : <1,u,u,u,u,u,u,u>
8834 // step 1 : <2,3,u,u,u,u,u,u>
8835 // step 2 : <4,5,6,7,u,u,u,u>
8836 for (int i = 0; i < NumVecElts; ++i)
8837 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8838 (i >= NumMaskElts && !(Mask[i] < 0)))
8839 return SDValue();
8840
8841 PreOp = CurOp;
8842 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008843 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008844 bool IsIntrinsic = false;
8845
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008846 switch (Op) {
8847 default:
8848 llvm_unreachable("Unexpected operator for across vector reduction");
8849 case ISD::ADD:
8850 Opcode = AArch64ISD::UADDV;
8851 break;
8852 case ISD::SMAX:
8853 Opcode = AArch64ISD::SMAXV;
8854 break;
8855 case ISD::UMAX:
8856 Opcode = AArch64ISD::UMAXV;
8857 break;
8858 case ISD::SMIN:
8859 Opcode = AArch64ISD::SMINV;
8860 break;
8861 case ISD::UMIN:
8862 Opcode = AArch64ISD::UMINV;
8863 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008864 case ISD::FMAXNUM:
8865 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8866 IsIntrinsic = true;
8867 break;
8868 case ISD::FMINNUM:
8869 Opcode = Intrinsic::aarch64_neon_fminnmv;
8870 IsIntrinsic = true;
8871 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008872 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008873 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00008874
8875 return IsIntrinsic
8876 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8877 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8878 : DAG.getNode(
8879 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8880 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8881 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008882}
8883
8884/// Target-specific DAG combine for the across vector min/max reductions.
8885/// This function specifically handles the final clean-up step of the vector
8886/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8887/// pattern, which narrows down and finds the final min/max value from all
8888/// elements of the vector.
8889/// For example, for a <16 x i8> vector :
8890/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8891/// %smax0 = smax %arr, svn0
8892/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8893/// %smax1 = smax %smax0, %svn1
8894/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8895/// %smax2 = smax %smax1, svn2
8896/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8897/// %sc = setcc %smax2, %svn3, gt
8898/// %n0 = extract_vector_elt %sc, #0
8899/// %n1 = extract_vector_elt %smax2, #0
8900/// %n2 = extract_vector_elt $smax2, #1
8901/// %result = select %n0, %n1, n2
8902/// becomes :
8903/// %1 = smaxv %0
8904/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008905static SDValue
8906performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8907 const AArch64Subtarget *Subtarget) {
8908 if (!Subtarget->hasNEON())
8909 return SDValue();
8910
8911 SDValue N0 = N->getOperand(0);
8912 SDValue IfTrue = N->getOperand(1);
8913 SDValue IfFalse = N->getOperand(2);
8914
8915 // Check if the SELECT merges up the final result of the min/max
8916 // from a vector.
8917 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8918 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8919 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8920 return SDValue();
8921
8922 // Expect N0 is fed by SETCC.
8923 SDValue SetCC = N0.getOperand(0);
8924 EVT SetCCVT = SetCC.getValueType();
8925 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8926 SetCCVT.getVectorElementType() != MVT::i1)
8927 return SDValue();
8928
8929 SDValue VectorOp = SetCC.getOperand(0);
8930 unsigned Op = VectorOp->getOpcode();
8931 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00008932 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8933 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008934 return SDValue();
8935
8936 EVT VTy = VectorOp.getValueType();
8937 if (!VTy.isVector())
8938 return SDValue();
8939
Jun Bum Lim0aace132015-10-09 14:11:25 +00008940 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008941 return SDValue();
8942
Jun Bum Lim0aace132015-10-09 14:11:25 +00008943 EVT EltTy = VTy.getVectorElementType();
8944 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8945 if (EltTy != MVT::f32)
8946 return SDValue();
8947 } else {
8948 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8949 return SDValue();
8950 }
8951
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008952 // Check if extracting from the same vector.
8953 // For example,
8954 // %sc = setcc %vector, %svn1, gt
8955 // %n0 = extract_vector_elt %sc, #0
8956 // %n1 = extract_vector_elt %vector, #0
8957 // %n2 = extract_vector_elt $vector, #1
8958 if (!(VectorOp == IfTrue->getOperand(0) &&
8959 VectorOp == IfFalse->getOperand(0)))
8960 return SDValue();
8961
8962 // Check if the condition code is matched with the operator type.
8963 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8964 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8965 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8966 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00008967 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8968 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8969 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8970 CC != ISD::SETGE) ||
8971 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8972 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8973 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008974 return SDValue();
8975
8976 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008977 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008978 return SDValue();
8979
8980 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008981 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008982 return SDValue();
8983
8984 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008985 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008986 return SDValue();
8987
8988 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8989}
8990
8991/// Target-specific DAG combine for the across vector add reduction.
8992/// This function specifically handles the final clean-up step of the vector
8993/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8994/// pattern, which adds all elements of a vector together.
8995/// For example, for a <4 x i32> vector :
8996/// %1 = vector_shuffle %0, <2,3,u,u>
8997/// %2 = add %0, %1
8998/// %3 = vector_shuffle %2, <1,u,u,u>
8999/// %4 = add %2, %3
9000/// %result = extract_vector_elt %4, 0
9001/// becomes :
9002/// %0 = uaddv %0
9003/// %result = extract_vector_elt %0, 0
9004static SDValue
9005performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9006 const AArch64Subtarget *Subtarget) {
9007 if (!Subtarget->hasNEON())
9008 return SDValue();
9009 SDValue N0 = N->getOperand(0);
9010 SDValue N1 = N->getOperand(1);
9011
9012 // Check if the input vector is fed by the ADD.
9013 if (N0->getOpcode() != ISD::ADD)
9014 return SDValue();
9015
9016 // The vector extract idx must constant zero because we only expect the final
9017 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009018 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009019 return SDValue();
9020
9021 EVT VTy = N0.getValueType();
9022 if (!VTy.isVector())
9023 return SDValue();
9024
9025 EVT EltTy = VTy.getVectorElementType();
9026 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9027 return SDValue();
9028
Jun Bum Lim0aace132015-10-09 14:11:25 +00009029 if (VTy.getSizeInBits() < 64)
9030 return SDValue();
9031
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009032 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009033}
9034
Tim Northover3b0846e2014-05-24 12:50:23 +00009035/// Target-specific DAG combine function for NEON load/store intrinsics
9036/// to merge base address updates.
9037static SDValue performNEONPostLDSTCombine(SDNode *N,
9038 TargetLowering::DAGCombinerInfo &DCI,
9039 SelectionDAG &DAG) {
9040 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9041 return SDValue();
9042
9043 unsigned AddrOpIdx = N->getNumOperands() - 1;
9044 SDValue Addr = N->getOperand(AddrOpIdx);
9045
9046 // Search for a use of the address operand that is an increment.
9047 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9048 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9049 SDNode *User = *UI;
9050 if (User->getOpcode() != ISD::ADD ||
9051 UI.getUse().getResNo() != Addr.getResNo())
9052 continue;
9053
9054 // Check that the add is independent of the load/store. Otherwise, folding
9055 // it would create a cycle.
9056 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9057 continue;
9058
9059 // Find the new opcode for the updating load/store.
9060 bool IsStore = false;
9061 bool IsLaneOp = false;
9062 bool IsDupOp = false;
9063 unsigned NewOpc = 0;
9064 unsigned NumVecs = 0;
9065 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9066 switch (IntNo) {
9067 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9068 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9069 NumVecs = 2; break;
9070 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9071 NumVecs = 3; break;
9072 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9073 NumVecs = 4; break;
9074 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9075 NumVecs = 2; IsStore = true; break;
9076 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9077 NumVecs = 3; IsStore = true; break;
9078 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9079 NumVecs = 4; IsStore = true; break;
9080 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9081 NumVecs = 2; break;
9082 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9083 NumVecs = 3; break;
9084 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9085 NumVecs = 4; break;
9086 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9087 NumVecs = 2; IsStore = true; break;
9088 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9089 NumVecs = 3; IsStore = true; break;
9090 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9091 NumVecs = 4; IsStore = true; break;
9092 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9093 NumVecs = 2; IsDupOp = true; break;
9094 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9095 NumVecs = 3; IsDupOp = true; break;
9096 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9097 NumVecs = 4; IsDupOp = true; break;
9098 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9099 NumVecs = 2; IsLaneOp = true; break;
9100 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9101 NumVecs = 3; IsLaneOp = true; break;
9102 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9103 NumVecs = 4; IsLaneOp = true; break;
9104 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9105 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9106 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9107 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9108 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9109 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9110 }
9111
9112 EVT VecTy;
9113 if (IsStore)
9114 VecTy = N->getOperand(2).getValueType();
9115 else
9116 VecTy = N->getValueType(0);
9117
9118 // If the increment is a constant, it must match the memory ref size.
9119 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9120 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9121 uint32_t IncVal = CInc->getZExtValue();
9122 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9123 if (IsLaneOp || IsDupOp)
9124 NumBytes /= VecTy.getVectorNumElements();
9125 if (IncVal != NumBytes)
9126 continue;
9127 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9128 }
9129 SmallVector<SDValue, 8> Ops;
9130 Ops.push_back(N->getOperand(0)); // Incoming chain
9131 // Load lane and store have vector list as input.
9132 if (IsLaneOp || IsStore)
9133 for (unsigned i = 2; i < AddrOpIdx; ++i)
9134 Ops.push_back(N->getOperand(i));
9135 Ops.push_back(Addr); // Base register
9136 Ops.push_back(Inc);
9137
9138 // Return Types.
9139 EVT Tys[6];
9140 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9141 unsigned n;
9142 for (n = 0; n < NumResultVecs; ++n)
9143 Tys[n] = VecTy;
9144 Tys[n++] = MVT::i64; // Type of write back register
9145 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009146 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009147
9148 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9149 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9150 MemInt->getMemoryVT(),
9151 MemInt->getMemOperand());
9152
9153 // Update the uses.
9154 std::vector<SDValue> NewResults;
9155 for (unsigned i = 0; i < NumResultVecs; ++i) {
9156 NewResults.push_back(SDValue(UpdN.getNode(), i));
9157 }
9158 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9159 DCI.CombineTo(N, NewResults);
9160 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9161
9162 break;
9163 }
9164 return SDValue();
9165}
9166
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009167// Checks to see if the value is the prescribed width and returns information
9168// about its extension mode.
9169static
9170bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9171 ExtType = ISD::NON_EXTLOAD;
9172 switch(V.getNode()->getOpcode()) {
9173 default:
9174 return false;
9175 case ISD::LOAD: {
9176 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9177 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9178 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9179 ExtType = LoadNode->getExtensionType();
9180 return true;
9181 }
9182 return false;
9183 }
9184 case ISD::AssertSext: {
9185 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9186 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9187 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9188 ExtType = ISD::SEXTLOAD;
9189 return true;
9190 }
9191 return false;
9192 }
9193 case ISD::AssertZext: {
9194 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9195 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9196 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9197 ExtType = ISD::ZEXTLOAD;
9198 return true;
9199 }
9200 return false;
9201 }
9202 case ISD::Constant:
9203 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00009204 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00009205 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009206 return true;
9207 return false;
9208 }
9209 }
9210
9211 return true;
9212}
9213
9214// This function does a whole lot of voodoo to determine if the tests are
9215// equivalent without and with a mask. Essentially what happens is that given a
9216// DAG resembling:
9217//
9218// +-------------+ +-------------+ +-------------+ +-------------+
9219// | Input | | AddConstant | | CompConstant| | CC |
9220// +-------------+ +-------------+ +-------------+ +-------------+
9221// | | | |
9222// V V | +----------+
9223// +-------------+ +----+ | |
9224// | ADD | |0xff| | |
9225// +-------------+ +----+ | |
9226// | | | |
9227// V V | |
9228// +-------------+ | |
9229// | AND | | |
9230// +-------------+ | |
9231// | | |
9232// +-----+ | |
9233// | | |
9234// V V V
9235// +-------------+
9236// | CMP |
9237// +-------------+
9238//
9239// The AND node may be safely removed for some combinations of inputs. In
9240// particular we need to take into account the extension type of the Input,
9241// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9242// width of the input (this can work for any width inputs, the above graph is
9243// specific to 8 bits.
9244//
9245// The specific equations were worked out by generating output tables for each
9246// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9247// problem was simplified by working with 4 bit inputs, which means we only
9248// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9249// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9250// patterns present in both extensions (0,7). For every distinct set of
9251// AddConstant and CompConstants bit patterns we can consider the masked and
9252// unmasked versions to be equivalent if the result of this function is true for
9253// all 16 distinct bit patterns of for the current extension type of Input (w0).
9254//
9255// sub w8, w0, w1
9256// and w10, w8, #0x0f
9257// cmp w8, w2
9258// cset w9, AArch64CC
9259// cmp w10, w2
9260// cset w11, AArch64CC
9261// cmp w9, w11
9262// cset w0, eq
9263// ret
9264//
9265// Since the above function shows when the outputs are equivalent it defines
9266// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9267// would be expensive to run during compiles. The equations below were written
9268// in a test harness that confirmed they gave equivalent outputs to the above
9269// for all inputs function, so they can be used determine if the removal is
9270// legal instead.
9271//
9272// isEquivalentMaskless() is the code for testing if the AND can be removed
9273// factored out of the DAG recognition as the DAG can take several forms.
9274
9275static
9276bool isEquivalentMaskless(unsigned CC, unsigned width,
9277 ISD::LoadExtType ExtType, signed AddConstant,
9278 signed CompConstant) {
9279 // By being careful about our equations and only writing the in term
9280 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9281 // make them generally applicable to all bit widths.
9282 signed MaxUInt = (1 << width);
9283
9284 // For the purposes of these comparisons sign extending the type is
9285 // equivalent to zero extending the add and displacing it by half the integer
9286 // width. Provided we are careful and make sure our equations are valid over
9287 // the whole range we can just adjust the input and avoid writing equations
9288 // for sign extended inputs.
9289 if (ExtType == ISD::SEXTLOAD)
9290 AddConstant -= (1 << (width-1));
9291
9292 switch(CC) {
9293 case AArch64CC::LE:
9294 case AArch64CC::GT: {
9295 if ((AddConstant == 0) ||
9296 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9297 (AddConstant >= 0 && CompConstant < 0) ||
9298 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9299 return true;
9300 } break;
9301 case AArch64CC::LT:
9302 case AArch64CC::GE: {
9303 if ((AddConstant == 0) ||
9304 (AddConstant >= 0 && CompConstant <= 0) ||
9305 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9306 return true;
9307 } break;
9308 case AArch64CC::HI:
9309 case AArch64CC::LS: {
9310 if ((AddConstant >= 0 && CompConstant < 0) ||
9311 (AddConstant <= 0 && CompConstant >= -1 &&
9312 CompConstant < AddConstant + MaxUInt))
9313 return true;
9314 } break;
9315 case AArch64CC::PL:
9316 case AArch64CC::MI: {
9317 if ((AddConstant == 0) ||
9318 (AddConstant > 0 && CompConstant <= 0) ||
9319 (AddConstant < 0 && CompConstant <= AddConstant))
9320 return true;
9321 } break;
9322 case AArch64CC::LO:
9323 case AArch64CC::HS: {
9324 if ((AddConstant >= 0 && CompConstant <= 0) ||
9325 (AddConstant <= 0 && CompConstant >= 0 &&
9326 CompConstant <= AddConstant + MaxUInt))
9327 return true;
9328 } break;
9329 case AArch64CC::EQ:
9330 case AArch64CC::NE: {
9331 if ((AddConstant > 0 && CompConstant < 0) ||
9332 (AddConstant < 0 && CompConstant >= 0 &&
9333 CompConstant < AddConstant + MaxUInt) ||
9334 (AddConstant >= 0 && CompConstant >= 0 &&
9335 CompConstant >= AddConstant) ||
9336 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9337
9338 return true;
9339 } break;
9340 case AArch64CC::VS:
9341 case AArch64CC::VC:
9342 case AArch64CC::AL:
9343 case AArch64CC::NV:
9344 return true;
9345 case AArch64CC::Invalid:
9346 break;
9347 }
9348
9349 return false;
9350}
9351
9352static
9353SDValue performCONDCombine(SDNode *N,
9354 TargetLowering::DAGCombinerInfo &DCI,
9355 SelectionDAG &DAG, unsigned CCIndex,
9356 unsigned CmpIndex) {
9357 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9358 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9359 unsigned CondOpcode = SubsNode->getOpcode();
9360
9361 if (CondOpcode != AArch64ISD::SUBS)
9362 return SDValue();
9363
9364 // There is a SUBS feeding this condition. Is it fed by a mask we can
9365 // use?
9366
9367 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9368 unsigned MaskBits = 0;
9369
9370 if (AndNode->getOpcode() != ISD::AND)
9371 return SDValue();
9372
9373 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9374 uint32_t CNV = CN->getZExtValue();
9375 if (CNV == 255)
9376 MaskBits = 8;
9377 else if (CNV == 65535)
9378 MaskBits = 16;
9379 }
9380
9381 if (!MaskBits)
9382 return SDValue();
9383
9384 SDValue AddValue = AndNode->getOperand(0);
9385
9386 if (AddValue.getOpcode() != ISD::ADD)
9387 return SDValue();
9388
9389 // The basic dag structure is correct, grab the inputs and validate them.
9390
9391 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9392 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9393 SDValue SubsInputValue = SubsNode->getOperand(1);
9394
9395 // The mask is present and the provenance of all the values is a smaller type,
9396 // lets see if the mask is superfluous.
9397
9398 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9399 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9400 return SDValue();
9401
9402 ISD::LoadExtType ExtType;
9403
9404 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9405 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9406 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9407 return SDValue();
9408
9409 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9410 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9411 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9412 return SDValue();
9413
9414 // The AND is not necessary, remove it.
9415
9416 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9417 SubsNode->getValueType(1));
9418 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9419
9420 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9421 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9422
9423 return SDValue(N, 0);
9424}
9425
Tim Northover3b0846e2014-05-24 12:50:23 +00009426// Optimize compare with zero and branch.
9427static SDValue performBRCONDCombine(SDNode *N,
9428 TargetLowering::DAGCombinerInfo &DCI,
9429 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009430 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9431 if (NV.getNode())
9432 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009433 SDValue Chain = N->getOperand(0);
9434 SDValue Dest = N->getOperand(1);
9435 SDValue CCVal = N->getOperand(2);
9436 SDValue Cmp = N->getOperand(3);
9437
9438 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9439 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9440 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9441 return SDValue();
9442
9443 unsigned CmpOpc = Cmp.getOpcode();
9444 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9445 return SDValue();
9446
9447 // Only attempt folding if there is only one use of the flag and no use of the
9448 // value.
9449 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9450 return SDValue();
9451
9452 SDValue LHS = Cmp.getOperand(0);
9453 SDValue RHS = Cmp.getOperand(1);
9454
9455 assert(LHS.getValueType() == RHS.getValueType() &&
9456 "Expected the value type to be the same for both operands!");
9457 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9458 return SDValue();
9459
Artyom Skrobov314ee042015-11-25 19:41:11 +00009460 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009461 std::swap(LHS, RHS);
9462
Artyom Skrobov314ee042015-11-25 19:41:11 +00009463 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009464 return SDValue();
9465
9466 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9467 LHS.getOpcode() == ISD::SRL)
9468 return SDValue();
9469
9470 // Fold the compare into the branch instruction.
9471 SDValue BR;
9472 if (CC == AArch64CC::EQ)
9473 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9474 else
9475 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9476
9477 // Do not add new nodes to DAG combiner worklist.
9478 DCI.CombineTo(N, BR, false);
9479
9480 return SDValue();
9481}
9482
9483// vselect (v1i1 setcc) ->
9484// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9485// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9486// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9487// such VSELECT.
9488static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9489 SDValue N0 = N->getOperand(0);
9490 EVT CCVT = N0.getValueType();
9491
9492 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9493 CCVT.getVectorElementType() != MVT::i1)
9494 return SDValue();
9495
9496 EVT ResVT = N->getValueType(0);
9497 EVT CmpVT = N0.getOperand(0).getValueType();
9498 // Only combine when the result type is of the same size as the compared
9499 // operands.
9500 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9501 return SDValue();
9502
9503 SDValue IfTrue = N->getOperand(1);
9504 SDValue IfFalse = N->getOperand(2);
9505 SDValue SetCC =
9506 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9507 N0.getOperand(0), N0.getOperand(1),
9508 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9509 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9510 IfTrue, IfFalse);
9511}
9512
9513/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9514/// the compare-mask instructions rather than going via NZCV, even if LHS and
9515/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9516/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009517static SDValue performSelectCombine(SDNode *N,
9518 TargetLowering::DAGCombinerInfo &DCI) {
9519 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009520 SDValue N0 = N->getOperand(0);
9521 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009522
Ahmed Bougachac004c602015-04-27 21:43:12 +00009523 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009524 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009525
Ahmed Bougachac004c602015-04-27 21:43:12 +00009526 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9527 // scalar SetCCResultType. We also don't expect vectors, because we assume
9528 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9529 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9530 "Scalar-SETCC feeding SELECT has unexpected result type!");
9531
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009532 // If NumMaskElts == 0, the comparison is larger than select result. The
9533 // largest real NEON comparison is 64-bits per lane, which means the result is
9534 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009535 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009536
9537 // Don't try to do this optimization when the setcc itself has i1 operands.
9538 // There are no legal vectors of i1, so this would be pointless.
9539 if (SrcVT == MVT::i1)
9540 return SDValue();
9541
Tim Northover3c0915e2014-08-29 15:34:58 +00009542 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009543 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009544 return SDValue();
9545
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009546 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009547 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9548
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009549 // Also bail out if the vector CCVT isn't the same size as ResVT.
9550 // This can happen if the SETCC operand size doesn't divide the ResVT size
9551 // (e.g., f64 vs v3f32).
9552 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9553 return SDValue();
9554
Ahmed Bougachac004c602015-04-27 21:43:12 +00009555 // Make sure we didn't create illegal types, if we're not supposed to.
9556 assert(DCI.isBeforeLegalize() ||
9557 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9558
Tim Northover3b0846e2014-05-24 12:50:23 +00009559 // First perform a vector comparison, where lane 0 is the one we're interested
9560 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009561 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009562 SDValue LHS =
9563 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9564 SDValue RHS =
9565 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9566 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9567
9568 // Now duplicate the comparison mask we want across all other lanes.
9569 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9570 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009571 Mask = DAG.getNode(ISD::BITCAST, DL,
9572 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009573
9574 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9575}
9576
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009577/// Get rid of unnecessary NVCASTs (that don't change the type).
9578static SDValue performNVCASTCombine(SDNode *N) {
9579 if (N->getValueType(0) == N->getOperand(0).getValueType())
9580 return N->getOperand(0);
9581
9582 return SDValue();
9583}
9584
Tim Northover3b0846e2014-05-24 12:50:23 +00009585SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9586 DAGCombinerInfo &DCI) const {
9587 SelectionDAG &DAG = DCI.DAG;
9588 switch (N->getOpcode()) {
9589 default:
9590 break;
9591 case ISD::ADD:
9592 case ISD::SUB:
9593 return performAddSubLongCombine(N, DCI, DAG);
9594 case ISD::XOR:
9595 return performXorCombine(N, DAG, DCI, Subtarget);
9596 case ISD::MUL:
9597 return performMulCombine(N, DAG, DCI, Subtarget);
9598 case ISD::SINT_TO_FP:
9599 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009600 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009601 case ISD::FP_TO_SINT:
9602 case ISD::FP_TO_UINT:
9603 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009604 case ISD::FDIV:
9605 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009606 case ISD::OR:
9607 return performORCombine(N, DCI, Subtarget);
9608 case ISD::INTRINSIC_WO_CHAIN:
9609 return performIntrinsicCombine(N, DCI, Subtarget);
9610 case ISD::ANY_EXTEND:
9611 case ISD::ZERO_EXTEND:
9612 case ISD::SIGN_EXTEND:
9613 return performExtendCombine(N, DCI, DAG);
9614 case ISD::BITCAST:
9615 return performBitcastCombine(N, DCI, DAG);
9616 case ISD::CONCAT_VECTORS:
9617 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009618 case ISD::SELECT: {
9619 SDValue RV = performSelectCombine(N, DCI);
9620 if (!RV.getNode())
9621 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9622 return RV;
9623 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009624 case ISD::VSELECT:
9625 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009626 case ISD::LOAD:
9627 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9628 return SDValue(N, 0);
9629 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009630 case ISD::STORE:
9631 return performSTORECombine(N, DCI, DAG, Subtarget);
9632 case AArch64ISD::BRCOND:
9633 return performBRCONDCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009634 case AArch64ISD::CSEL:
9635 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009636 case AArch64ISD::DUP:
9637 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009638 case AArch64ISD::NVCAST:
9639 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009640 case ISD::INSERT_VECTOR_ELT:
9641 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009642 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009643 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009644 case ISD::INTRINSIC_VOID:
9645 case ISD::INTRINSIC_W_CHAIN:
9646 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9647 case Intrinsic::aarch64_neon_ld2:
9648 case Intrinsic::aarch64_neon_ld3:
9649 case Intrinsic::aarch64_neon_ld4:
9650 case Intrinsic::aarch64_neon_ld1x2:
9651 case Intrinsic::aarch64_neon_ld1x3:
9652 case Intrinsic::aarch64_neon_ld1x4:
9653 case Intrinsic::aarch64_neon_ld2lane:
9654 case Intrinsic::aarch64_neon_ld3lane:
9655 case Intrinsic::aarch64_neon_ld4lane:
9656 case Intrinsic::aarch64_neon_ld2r:
9657 case Intrinsic::aarch64_neon_ld3r:
9658 case Intrinsic::aarch64_neon_ld4r:
9659 case Intrinsic::aarch64_neon_st2:
9660 case Intrinsic::aarch64_neon_st3:
9661 case Intrinsic::aarch64_neon_st4:
9662 case Intrinsic::aarch64_neon_st1x2:
9663 case Intrinsic::aarch64_neon_st1x3:
9664 case Intrinsic::aarch64_neon_st1x4:
9665 case Intrinsic::aarch64_neon_st2lane:
9666 case Intrinsic::aarch64_neon_st3lane:
9667 case Intrinsic::aarch64_neon_st4lane:
9668 return performNEONPostLDSTCombine(N, DCI, DAG);
9669 default:
9670 break;
9671 }
9672 }
9673 return SDValue();
9674}
9675
9676// Check if the return value is used as only a return value, as otherwise
9677// we can't perform a tail-call. In particular, we need to check for
9678// target ISD nodes that are returns and any other "odd" constructs
9679// that the generic analysis code won't necessarily catch.
9680bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9681 SDValue &Chain) const {
9682 if (N->getNumValues() != 1)
9683 return false;
9684 if (!N->hasNUsesOfValue(1, 0))
9685 return false;
9686
9687 SDValue TCChain = Chain;
9688 SDNode *Copy = *N->use_begin();
9689 if (Copy->getOpcode() == ISD::CopyToReg) {
9690 // If the copy has a glue operand, we conservatively assume it isn't safe to
9691 // perform a tail call.
9692 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9693 MVT::Glue)
9694 return false;
9695 TCChain = Copy->getOperand(0);
9696 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9697 return false;
9698
9699 bool HasRet = false;
9700 for (SDNode *Node : Copy->uses()) {
9701 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9702 return false;
9703 HasRet = true;
9704 }
9705
9706 if (!HasRet)
9707 return false;
9708
9709 Chain = TCChain;
9710 return true;
9711}
9712
9713// Return whether the an instruction can potentially be optimized to a tail
9714// call. This will cause the optimizers to attempt to move, or duplicate,
9715// return instructions to help enable tail call optimizations for this
9716// instruction.
9717bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9718 if (!CI->isTailCall())
9719 return false;
9720
9721 return true;
9722}
9723
9724bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9725 SDValue &Offset,
9726 ISD::MemIndexedMode &AM,
9727 bool &IsInc,
9728 SelectionDAG &DAG) const {
9729 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9730 return false;
9731
9732 Base = Op->getOperand(0);
9733 // All of the indexed addressing mode instructions take a signed
9734 // 9 bit immediate offset.
9735 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9736 int64_t RHSC = (int64_t)RHS->getZExtValue();
9737 if (RHSC >= 256 || RHSC <= -256)
9738 return false;
9739 IsInc = (Op->getOpcode() == ISD::ADD);
9740 Offset = Op->getOperand(1);
9741 return true;
9742 }
9743 return false;
9744}
9745
9746bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9747 SDValue &Offset,
9748 ISD::MemIndexedMode &AM,
9749 SelectionDAG &DAG) const {
9750 EVT VT;
9751 SDValue Ptr;
9752 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9753 VT = LD->getMemoryVT();
9754 Ptr = LD->getBasePtr();
9755 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9756 VT = ST->getMemoryVT();
9757 Ptr = ST->getBasePtr();
9758 } else
9759 return false;
9760
9761 bool IsInc;
9762 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9763 return false;
9764 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9765 return true;
9766}
9767
9768bool AArch64TargetLowering::getPostIndexedAddressParts(
9769 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9770 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9771 EVT VT;
9772 SDValue Ptr;
9773 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9774 VT = LD->getMemoryVT();
9775 Ptr = LD->getBasePtr();
9776 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9777 VT = ST->getMemoryVT();
9778 Ptr = ST->getBasePtr();
9779 } else
9780 return false;
9781
9782 bool IsInc;
9783 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9784 return false;
9785 // Post-indexing updates the base, so it's not a valid transform
9786 // if that's not the same as the load's pointer.
9787 if (Ptr != Base)
9788 return false;
9789 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9790 return true;
9791}
9792
Tim Northoverf8bfe212014-07-18 13:07:05 +00009793static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9794 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00009795 SDLoc DL(N);
9796 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00009797
9798 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9799 return;
9800
Tim Northoverf8bfe212014-07-18 13:07:05 +00009801 Op = SDValue(
9802 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9803 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009804 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00009805 0);
9806 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9807 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9808}
9809
Charlie Turner434d4592015-10-16 15:38:25 +00009810static void ReplaceReductionResults(SDNode *N,
9811 SmallVectorImpl<SDValue> &Results,
9812 SelectionDAG &DAG, unsigned InterOp,
9813 unsigned AcrossOp) {
9814 EVT LoVT, HiVT;
9815 SDValue Lo, Hi;
9816 SDLoc dl(N);
9817 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9818 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9819 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9820 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9821 Results.push_back(SplitVal);
9822}
9823
Tim Northover3b0846e2014-05-24 12:50:23 +00009824void AArch64TargetLowering::ReplaceNodeResults(
9825 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9826 switch (N->getOpcode()) {
9827 default:
9828 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00009829 case ISD::BITCAST:
9830 ReplaceBITCASTResults(N, Results, DAG);
9831 return;
Charlie Turner434d4592015-10-16 15:38:25 +00009832 case AArch64ISD::SADDV:
9833 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9834 return;
9835 case AArch64ISD::UADDV:
9836 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9837 return;
9838 case AArch64ISD::SMINV:
9839 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9840 return;
9841 case AArch64ISD::UMINV:
9842 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9843 return;
9844 case AArch64ISD::SMAXV:
9845 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9846 return;
9847 case AArch64ISD::UMAXV:
9848 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9849 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00009850 case ISD::FP_TO_UINT:
9851 case ISD::FP_TO_SINT:
9852 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9853 // Let normal code take care of it by not adding anything to Results.
9854 return;
9855 }
9856}
9857
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00009858bool AArch64TargetLowering::useLoadStackGuardNode() const {
9859 return true;
9860}
9861
Sanjay Patel1dd15592015-07-28 23:05:48 +00009862unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +00009863 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9864 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +00009865 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +00009866}
9867
Chandler Carruth9d010ff2014-07-03 00:23:43 +00009868TargetLoweringBase::LegalizeTypeAction
9869AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9870 MVT SVT = VT.getSimpleVT();
9871 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9872 // v4i16, v2i32 instead of to promote.
9873 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9874 || SVT == MVT::v1f32)
9875 return TypeWidenVector;
9876
9877 return TargetLoweringBase::getPreferredVectorAction(VT);
9878}
9879
Robin Morisseted3d48f2014-09-03 21:29:59 +00009880// Loads and stores less than 128-bits are already atomic; ones above that
9881// are doomed anyway, so defer to the default libcall and blame the OS when
9882// things go wrong.
9883bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9884 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9885 return Size == 128;
9886}
9887
9888// Loads and stores less than 128-bits are already atomic; ones above that
9889// are doomed anyway, so defer to the default libcall and blame the OS when
9890// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +00009891TargetLowering::AtomicExpansionKind
9892AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +00009893 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +00009894 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +00009895}
9896
9897// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +00009898TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +00009899AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +00009900 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +00009901 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +00009902}
9903
Ahmed Bougacha52468672015-09-11 17:08:28 +00009904bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9905 AtomicCmpXchgInst *AI) const {
Robin Morisset25c8e312014-09-17 00:06:58 +00009906 return true;
9907}
9908
Tim Northover3b0846e2014-05-24 12:50:23 +00009909Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9910 AtomicOrdering Ord) const {
9911 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9912 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +00009913 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009914
9915 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9916 // intrinsic must return {i64, i64} and we have to recombine them into a
9917 // single i128 here.
9918 if (ValTy->getPrimitiveSizeInBits() == 128) {
9919 Intrinsic::ID Int =
9920 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9921 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9922
9923 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9924 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9925
9926 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9927 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9928 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9929 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9930 return Builder.CreateOr(
9931 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9932 }
9933
9934 Type *Tys[] = { Addr->getType() };
9935 Intrinsic::ID Int =
9936 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9937 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9938
9939 return Builder.CreateTruncOrBitCast(
9940 Builder.CreateCall(Ldxr, Addr),
9941 cast<PointerType>(Addr->getType())->getElementType());
9942}
9943
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00009944void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9945 IRBuilder<> &Builder) const {
9946 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9947 Builder.CreateCall(
9948 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9949}
9950
Tim Northover3b0846e2014-05-24 12:50:23 +00009951Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9952 Value *Val, Value *Addr,
9953 AtomicOrdering Ord) const {
9954 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +00009955 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009956
9957 // Since the intrinsics must have legal type, the i128 intrinsics take two
9958 // parameters: "i64, i64". We must marshal Val into the appropriate form
9959 // before the call.
9960 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9961 Intrinsic::ID Int =
9962 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9963 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9964 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9965
9966 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9967 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9968 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +00009969 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009970 }
9971
9972 Intrinsic::ID Int =
9973 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9974 Type *Tys[] = { Addr->getType() };
9975 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9976
David Blaikieff6409d2015-05-18 22:13:54 +00009977 return Builder.CreateCall(Stxr,
9978 {Builder.CreateZExtOrBitCast(
9979 Val, Stxr->getFunctionType()->getParamType(0)),
9980 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009981}
Tim Northover3c55cca2014-11-27 21:02:42 +00009982
9983bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9984 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9985 return Ty->isArrayTy();
9986}
Matthias Braunaf7d7702015-07-16 20:02:37 +00009987
9988bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9989 EVT) const {
9990 return false;
9991}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +00009992
9993Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
9994 if (!Subtarget->isTargetAndroid())
9995 return TargetLowering::getSafeStackPointerLocation(IRB);
9996
9997 // Android provides a fixed TLS slot for the SafeStack pointer. See the
9998 // definition of TLS_SLOT_SAFESTACK in
9999 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10000 const unsigned TlsOffset = 0x48;
10001 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10002 Function *ThreadPointerFunc =
10003 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10004 return IRB.CreatePointerCast(
10005 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10006 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10007}