blob: 98cbbc01a5707fb3182c6a92177bc3f1ec10c8a0 [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);
Chad Rosierf3491492015-12-04 21:38:44 +0000240 for (MVT VT : MVT::vector_valuetypes()) {
241 setOperationAction(ISD::SDIVREM, VT, Expand);
242 setOperationAction(ISD::UDIVREM, VT, Expand);
243 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000244 setOperationAction(ISD::SREM, MVT::i32, Expand);
245 setOperationAction(ISD::SREM, MVT::i64, Expand);
246 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
247 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
248 setOperationAction(ISD::UREM, MVT::i32, Expand);
249 setOperationAction(ISD::UREM, MVT::i64, Expand);
250
251 // Custom lower Add/Sub/Mul with overflow.
252 setOperationAction(ISD::SADDO, MVT::i32, Custom);
253 setOperationAction(ISD::SADDO, MVT::i64, Custom);
254 setOperationAction(ISD::UADDO, MVT::i32, Custom);
255 setOperationAction(ISD::UADDO, MVT::i64, Custom);
256 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
257 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
258 setOperationAction(ISD::USUBO, MVT::i32, Custom);
259 setOperationAction(ISD::USUBO, MVT::i64, Custom);
260 setOperationAction(ISD::SMULO, MVT::i32, Custom);
261 setOperationAction(ISD::SMULO, MVT::i64, Custom);
262 setOperationAction(ISD::UMULO, MVT::i32, Custom);
263 setOperationAction(ISD::UMULO, MVT::i64, Custom);
264
265 setOperationAction(ISD::FSIN, MVT::f32, Expand);
266 setOperationAction(ISD::FSIN, MVT::f64, Expand);
267 setOperationAction(ISD::FCOS, MVT::f32, Expand);
268 setOperationAction(ISD::FCOS, MVT::f64, Expand);
269 setOperationAction(ISD::FPOW, MVT::f32, Expand);
270 setOperationAction(ISD::FPOW, MVT::f64, Expand);
271 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
272 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
273
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000274 // f16 is a storage-only type, always promote it to f32.
275 setOperationAction(ISD::SETCC, MVT::f16, Promote);
276 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
277 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
278 setOperationAction(ISD::SELECT, MVT::f16, Promote);
279 setOperationAction(ISD::FADD, MVT::f16, Promote);
280 setOperationAction(ISD::FSUB, MVT::f16, Promote);
281 setOperationAction(ISD::FMUL, MVT::f16, Promote);
282 setOperationAction(ISD::FDIV, MVT::f16, Promote);
283 setOperationAction(ISD::FREM, MVT::f16, Promote);
284 setOperationAction(ISD::FMA, MVT::f16, Promote);
285 setOperationAction(ISD::FNEG, MVT::f16, Promote);
286 setOperationAction(ISD::FABS, MVT::f16, Promote);
287 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
288 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
289 setOperationAction(ISD::FCOS, MVT::f16, Promote);
290 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
291 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
292 setOperationAction(ISD::FPOW, MVT::f16, Promote);
293 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
294 setOperationAction(ISD::FRINT, MVT::f16, Promote);
295 setOperationAction(ISD::FSIN, MVT::f16, Promote);
296 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
297 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
298 setOperationAction(ISD::FEXP, MVT::f16, Promote);
299 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
300 setOperationAction(ISD::FLOG, MVT::f16, Promote);
301 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
302 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
303 setOperationAction(ISD::FROUND, MVT::f16, Promote);
304 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
305 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
306 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000307 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
308 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000309
Oliver Stannard89d15422014-08-27 16:16:04 +0000310 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
311 // known to be safe.
312 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
313 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
314 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
315 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
316 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
317 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
318 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
320 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
321 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
322 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
323 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
324
325 // Expand all other v4f16 operations.
326 // FIXME: We could generate better code by promoting some operations to
327 // a pair of v4f32s
328 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
329 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
330 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
331 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
332 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
333 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
334 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
335 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
336 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
337 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
338 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
339 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
340 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
341 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
342 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
343 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
344 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
345 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
346 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
347 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
348 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
349 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
350 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
351 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
352 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
353 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
354
355
356 // v8f16 is also a storage-only type, so expand it.
357 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
358 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
359 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
360 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
363 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
364 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
365 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
366 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
367 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
368 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
369 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
370 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
371 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
372 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
374 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
375 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
376 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
377 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
378 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
379 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
380 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
381 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
382 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
383 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
384 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
385 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
386 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
387 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
388
Tim Northover3b0846e2014-05-24 12:50:23 +0000389 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000390 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000391 setOperationAction(ISD::FFLOOR, Ty, Legal);
392 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
393 setOperationAction(ISD::FCEIL, Ty, Legal);
394 setOperationAction(ISD::FRINT, Ty, Legal);
395 setOperationAction(ISD::FTRUNC, Ty, Legal);
396 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000397 setOperationAction(ISD::FMINNUM, Ty, Legal);
398 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000399 setOperationAction(ISD::FMINNAN, Ty, Legal);
400 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000401 }
402
403 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
404
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000405 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
406 // This requires the Performance Monitors extension.
407 if (Subtarget->hasPerfMon())
408 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
409
Tim Northover3b0846e2014-05-24 12:50:23 +0000410 if (Subtarget->isTargetMachO()) {
411 // For iOS, we don't want to the normal expansion of a libcall to
412 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
413 // traffic.
414 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
415 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
416 } else {
417 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
418 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
419 }
420
Juergen Ributzka23266502014-12-10 19:43:32 +0000421 // Make floating-point constants legal for the large code model, so they don't
422 // become loads from the constant pool.
423 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
424 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
425 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
426 }
427
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 // AArch64 does not have floating-point extending loads, i1 sign-extending
429 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000430 for (MVT VT : MVT::fp_valuetypes()) {
431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
434 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
435 }
436 for (MVT VT : MVT::integer_valuetypes())
437 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
438
Tim Northover3b0846e2014-05-24 12:50:23 +0000439 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
442 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
443 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
444 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
445 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000446
447 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
448 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
449
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 // Indexed loads and stores are supported.
451 for (unsigned im = (unsigned)ISD::PRE_INC;
452 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453 setIndexedLoadAction(im, MVT::i8, Legal);
454 setIndexedLoadAction(im, MVT::i16, Legal);
455 setIndexedLoadAction(im, MVT::i32, Legal);
456 setIndexedLoadAction(im, MVT::i64, Legal);
457 setIndexedLoadAction(im, MVT::f64, Legal);
458 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000459 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000460 setIndexedStoreAction(im, MVT::i8, Legal);
461 setIndexedStoreAction(im, MVT::i16, Legal);
462 setIndexedStoreAction(im, MVT::i32, Legal);
463 setIndexedStoreAction(im, MVT::i64, Legal);
464 setIndexedStoreAction(im, MVT::f64, Legal);
465 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000466 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000467 }
468
469 // Trap.
470 setOperationAction(ISD::TRAP, MVT::Other, Legal);
471
472 // We combine OR nodes for bitfield operations.
473 setTargetDAGCombine(ISD::OR);
474
475 // Vector add and sub nodes may conceal a high-half opportunity.
476 // Also, try to fold ADD into CSINC/CSINV..
477 setTargetDAGCombine(ISD::ADD);
478 setTargetDAGCombine(ISD::SUB);
479
480 setTargetDAGCombine(ISD::XOR);
481 setTargetDAGCombine(ISD::SINT_TO_FP);
482 setTargetDAGCombine(ISD::UINT_TO_FP);
483
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000484 setTargetDAGCombine(ISD::FP_TO_SINT);
485 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000486 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000487
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
489
490 setTargetDAGCombine(ISD::ANY_EXTEND);
491 setTargetDAGCombine(ISD::ZERO_EXTEND);
492 setTargetDAGCombine(ISD::SIGN_EXTEND);
493 setTargetDAGCombine(ISD::BITCAST);
494 setTargetDAGCombine(ISD::CONCAT_VECTORS);
495 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000496 if (Subtarget->supportsAddressTopByteIgnored())
497 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000498
499 setTargetDAGCombine(ISD::MUL);
500
501 setTargetDAGCombine(ISD::SELECT);
502 setTargetDAGCombine(ISD::VSELECT);
503
504 setTargetDAGCombine(ISD::INTRINSIC_VOID);
505 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
506 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000507 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000508
509 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
510 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
511 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
512
513 setStackPointerRegisterToSaveRestore(AArch64::SP);
514
515 setSchedulingPreference(Sched::Hybrid);
516
517 // Enable TBZ/TBNZ
518 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000519 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000520
521 setMinFunctionAlignment(2);
522
Tim Northover3b0846e2014-05-24 12:50:23 +0000523 setHasExtractBitsInsn(true);
524
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000525 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
526
Tim Northover3b0846e2014-05-24 12:50:23 +0000527 if (Subtarget->hasNEON()) {
528 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
529 // silliness like this:
530 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
531 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
532 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
533 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
534 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
535 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
536 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
537 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
538 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
539 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
540 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
541 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
542 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
543 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
544 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
545 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
546 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
547 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
548 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
549 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
550 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
551 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
552 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
553 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
554 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
555
556 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
557 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
558 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
559 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
560 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
561
562 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
563
564 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
565 // elements smaller than i32, so promote the input to i32 first.
566 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
567 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
569 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000570 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
571 // -> v8f16 conversions.
572 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
574 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
575 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000576 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
577 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
578 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
579 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
580 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000581 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
582 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
583 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
584 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000585
586 // AArch64 doesn't have MUL.2d:
587 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000588 // Custom handling for some quad-vector types to detect MULL.
589 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
590 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
591 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
592
Tim Northover3b0846e2014-05-24 12:50:23 +0000593 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
594 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
595 // Likewise, narrowing and extending vector loads/stores aren't handled
596 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000597 for (MVT VT : MVT::vector_valuetypes()) {
598 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000599
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000600 setOperationAction(ISD::MULHS, VT, Expand);
601 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
602 setOperationAction(ISD::MULHU, VT, Expand);
603 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000604
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000605 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000606
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000607 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000608 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000609 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
610 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
611 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
612 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000613 }
614
615 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000616 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000617 setOperationAction(ISD::FFLOOR, Ty, Legal);
618 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
619 setOperationAction(ISD::FCEIL, Ty, Legal);
620 setOperationAction(ISD::FRINT, Ty, Legal);
621 setOperationAction(ISD::FTRUNC, Ty, Legal);
622 setOperationAction(ISD::FROUND, Ty, Legal);
623 }
624 }
James Molloyf089ab72014-08-06 10:42:18 +0000625
626 // Prefer likely predicted branches to selects on out-of-order cores.
627 if (Subtarget->isCortexA57())
628 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000629}
630
631void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000632 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
634 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
635
636 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
637 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000638 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000639 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
640 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
641
642 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
643 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
644 }
645
646 // Mark vector float intrinsics as expand.
647 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
648 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
649 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
650 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
651 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
652 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
653 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
654 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
655 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
656 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000657
658 // But we do support custom-lowering for FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000660 }
661
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
663 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
664 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
666 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
667 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
668 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
669 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
670 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
671 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
672 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
673 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
674
675 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
677 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000678 for (MVT InnerVT : MVT::all_valuetypes())
679 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000680
681 // CNT supports only B element sizes.
682 if (VT != MVT::v8i8 && VT != MVT::v16i8)
683 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
684
685 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
686 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
687 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
688 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
689 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
690
691 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
692 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
693
Hal Finkelcd8664c2015-12-11 23:11:52 +0000694 // [SU][MIN|MAX] are available for all NEON types apart from i64.
James Molloycfb04432015-05-15 16:15:57 +0000695 if (!VT.isFloatingPoint() &&
696 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000697 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
James Molloycfb04432015-05-15 16:15:57 +0000698 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
699
James Molloy63be1982015-08-14 09:08:50 +0000700 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
701 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000702 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
703 ISD::FMINNUM, ISD::FMAXNUM})
James Molloyedf38f02015-08-11 12:06:33 +0000704 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
705
Tim Northover3b0846e2014-05-24 12:50:23 +0000706 if (Subtarget->isLittleEndian()) {
707 for (unsigned im = (unsigned)ISD::PRE_INC;
708 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
709 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
710 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
711 }
712 }
713}
714
715void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
716 addRegisterClass(VT, &AArch64::FPR64RegClass);
717 addTypeForNEON(VT, MVT::v2i32);
718}
719
720void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
721 addRegisterClass(VT, &AArch64::FPR128RegClass);
722 addTypeForNEON(VT, MVT::v4i32);
723}
724
Mehdi Amini44ede332015-07-09 02:09:04 +0000725EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
726 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000727 if (!VT.isVector())
728 return MVT::i32;
729 return VT.changeVectorElementTypeToInteger();
730}
731
732/// computeKnownBitsForTargetNode - Determine which of the bits specified in
733/// Mask are known to be either zero or one and return them in the
734/// KnownZero/KnownOne bitsets.
735void AArch64TargetLowering::computeKnownBitsForTargetNode(
736 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
737 const SelectionDAG &DAG, unsigned Depth) const {
738 switch (Op.getOpcode()) {
739 default:
740 break;
741 case AArch64ISD::CSEL: {
742 APInt KnownZero2, KnownOne2;
743 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
744 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
745 KnownZero &= KnownZero2;
746 KnownOne &= KnownOne2;
747 break;
748 }
749 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000750 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000751 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
752 switch (IntID) {
753 default: return;
754 case Intrinsic::aarch64_ldaxr:
755 case Intrinsic::aarch64_ldxr: {
756 unsigned BitWidth = KnownOne.getBitWidth();
757 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
758 unsigned MemBits = VT.getScalarType().getSizeInBits();
759 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
760 return;
761 }
762 }
763 break;
764 }
765 case ISD::INTRINSIC_WO_CHAIN:
766 case ISD::INTRINSIC_VOID: {
767 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
768 switch (IntNo) {
769 default:
770 break;
771 case Intrinsic::aarch64_neon_umaxv:
772 case Intrinsic::aarch64_neon_uminv: {
773 // Figure out the datatype of the vector operand. The UMINV instruction
774 // will zero extend the result, so we can mark as known zero all the
775 // bits larger than the element datatype. 32-bit or larget doesn't need
776 // this as those are legal types and will be handled by isel directly.
777 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
778 unsigned BitWidth = KnownZero.getBitWidth();
779 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
780 assert(BitWidth >= 8 && "Unexpected width!");
781 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
782 KnownZero |= Mask;
783 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
784 assert(BitWidth >= 16 && "Unexpected width!");
785 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
786 KnownZero |= Mask;
787 }
788 break;
789 } break;
790 }
791 }
792 }
793}
794
Mehdi Aminieaabc512015-07-09 15:12:23 +0000795MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
796 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000797 return MVT::i64;
798}
799
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000800bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
801 unsigned AddrSpace,
802 unsigned Align,
803 bool *Fast) const {
804 if (Subtarget->requiresStrictAlign())
805 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000806
807 // FIXME: This is mostly true for Cyclone, but not necessarily others.
808 if (Fast) {
809 // FIXME: Define an attribute for slow unaligned accesses instead of
810 // relying on the CPU type as a proxy.
811 // On Cyclone, unaligned 128-bit stores are slow.
812 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
813 // See comments in performSTORECombine() for more details about
814 // these conditions.
815
816 // Code that uses clang vector extensions can mark that it
817 // wants unaligned accesses to be treated as fast by
818 // underspecifying alignment to be 1 or 2.
819 Align <= 2 ||
820
821 // Disregard v2i64. Memcpy lowering produces those and splitting
822 // them regresses performance on micro-benchmarks and olden/bh.
823 VT == MVT::v2i64;
824 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000825 return true;
826}
827
Tim Northover3b0846e2014-05-24 12:50:23 +0000828FastISel *
829AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
830 const TargetLibraryInfo *libInfo) const {
831 return AArch64::createFastISel(funcInfo, libInfo);
832}
833
834const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000835 switch ((AArch64ISD::NodeType)Opcode) {
836 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000837 case AArch64ISD::CALL: return "AArch64ISD::CALL";
838 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
839 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
840 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
841 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
842 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
843 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
844 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
845 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
846 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
847 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
848 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000849 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000850 case AArch64ISD::ADC: return "AArch64ISD::ADC";
851 case AArch64ISD::SBC: return "AArch64ISD::SBC";
852 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
853 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
854 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
855 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
856 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000857 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
858 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
859 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000860 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000861 case AArch64ISD::DUP: return "AArch64ISD::DUP";
862 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
863 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
864 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
865 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
866 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
867 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
868 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
869 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
870 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
871 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
872 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
873 case AArch64ISD::BICi: return "AArch64ISD::BICi";
874 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
875 case AArch64ISD::BSL: return "AArch64ISD::BSL";
876 case AArch64ISD::NEG: return "AArch64ISD::NEG";
877 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
878 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
879 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
880 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
881 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
882 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
883 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
884 case AArch64ISD::REV16: return "AArch64ISD::REV16";
885 case AArch64ISD::REV32: return "AArch64ISD::REV32";
886 case AArch64ISD::REV64: return "AArch64ISD::REV64";
887 case AArch64ISD::EXT: return "AArch64ISD::EXT";
888 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
889 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
890 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
891 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
892 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
893 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
894 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
895 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
896 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
897 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
898 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
899 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
900 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
901 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
902 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
903 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
904 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
905 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
906 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
907 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
908 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000909 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
910 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
911 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
912 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
913 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
914 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000915 case AArch64ISD::NOT: return "AArch64ISD::NOT";
916 case AArch64ISD::BIT: return "AArch64ISD::BIT";
917 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
918 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
919 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
920 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
921 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000922 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000923 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
924 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000925 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000926 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
927 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
928 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
929 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
930 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
931 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
932 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
933 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
934 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
935 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
936 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
937 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
938 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
939 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
940 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
941 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
942 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
943 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
944 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
945 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
946 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
947 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
948 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
949 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
950 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
951 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
952 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
953 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
954 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000955 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
956 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000957 }
Matthias Braund04893f2015-05-07 21:33:59 +0000958 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000959}
960
961MachineBasicBlock *
962AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
963 MachineBasicBlock *MBB) const {
964 // We materialise the F128CSEL pseudo-instruction as some control flow and a
965 // phi node:
966
967 // OrigBB:
968 // [... previous instrs leading to comparison ...]
969 // b.ne TrueBB
970 // b EndBB
971 // TrueBB:
972 // ; Fallthrough
973 // EndBB:
974 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
975
Tim Northover3b0846e2014-05-24 12:50:23 +0000976 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000977 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000978 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
979 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000980 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000981
982 unsigned DestReg = MI->getOperand(0).getReg();
983 unsigned IfTrueReg = MI->getOperand(1).getReg();
984 unsigned IfFalseReg = MI->getOperand(2).getReg();
985 unsigned CondCode = MI->getOperand(3).getImm();
986 bool NZCVKilled = MI->getOperand(4).isKill();
987
988 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
989 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
990 MF->insert(It, TrueBB);
991 MF->insert(It, EndBB);
992
993 // Transfer rest of current basic-block to EndBB
994 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
995 MBB->end());
996 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
997
998 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
999 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1000 MBB->addSuccessor(TrueBB);
1001 MBB->addSuccessor(EndBB);
1002
1003 // TrueBB falls through to the end.
1004 TrueBB->addSuccessor(EndBB);
1005
1006 if (!NZCVKilled) {
1007 TrueBB->addLiveIn(AArch64::NZCV);
1008 EndBB->addLiveIn(AArch64::NZCV);
1009 }
1010
1011 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1012 .addReg(IfTrueReg)
1013 .addMBB(TrueBB)
1014 .addReg(IfFalseReg)
1015 .addMBB(MBB);
1016
1017 MI->eraseFromParent();
1018 return EndBB;
1019}
1020
1021MachineBasicBlock *
1022AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1023 MachineBasicBlock *BB) const {
1024 switch (MI->getOpcode()) {
1025 default:
1026#ifndef NDEBUG
1027 MI->dump();
1028#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001029 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001030
1031 case AArch64::F128CSEL:
1032 return EmitF128CSEL(MI, BB);
1033
1034 case TargetOpcode::STACKMAP:
1035 case TargetOpcode::PATCHPOINT:
1036 return emitPatchPoint(MI, BB);
1037 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001038}
1039
1040//===----------------------------------------------------------------------===//
1041// AArch64 Lowering private implementation.
1042//===----------------------------------------------------------------------===//
1043
1044//===----------------------------------------------------------------------===//
1045// Lowering Code
1046//===----------------------------------------------------------------------===//
1047
1048/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1049/// CC
1050static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1051 switch (CC) {
1052 default:
1053 llvm_unreachable("Unknown condition code!");
1054 case ISD::SETNE:
1055 return AArch64CC::NE;
1056 case ISD::SETEQ:
1057 return AArch64CC::EQ;
1058 case ISD::SETGT:
1059 return AArch64CC::GT;
1060 case ISD::SETGE:
1061 return AArch64CC::GE;
1062 case ISD::SETLT:
1063 return AArch64CC::LT;
1064 case ISD::SETLE:
1065 return AArch64CC::LE;
1066 case ISD::SETUGT:
1067 return AArch64CC::HI;
1068 case ISD::SETUGE:
1069 return AArch64CC::HS;
1070 case ISD::SETULT:
1071 return AArch64CC::LO;
1072 case ISD::SETULE:
1073 return AArch64CC::LS;
1074 }
1075}
1076
1077/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1078static void changeFPCCToAArch64CC(ISD::CondCode CC,
1079 AArch64CC::CondCode &CondCode,
1080 AArch64CC::CondCode &CondCode2) {
1081 CondCode2 = AArch64CC::AL;
1082 switch (CC) {
1083 default:
1084 llvm_unreachable("Unknown FP condition!");
1085 case ISD::SETEQ:
1086 case ISD::SETOEQ:
1087 CondCode = AArch64CC::EQ;
1088 break;
1089 case ISD::SETGT:
1090 case ISD::SETOGT:
1091 CondCode = AArch64CC::GT;
1092 break;
1093 case ISD::SETGE:
1094 case ISD::SETOGE:
1095 CondCode = AArch64CC::GE;
1096 break;
1097 case ISD::SETOLT:
1098 CondCode = AArch64CC::MI;
1099 break;
1100 case ISD::SETOLE:
1101 CondCode = AArch64CC::LS;
1102 break;
1103 case ISD::SETONE:
1104 CondCode = AArch64CC::MI;
1105 CondCode2 = AArch64CC::GT;
1106 break;
1107 case ISD::SETO:
1108 CondCode = AArch64CC::VC;
1109 break;
1110 case ISD::SETUO:
1111 CondCode = AArch64CC::VS;
1112 break;
1113 case ISD::SETUEQ:
1114 CondCode = AArch64CC::EQ;
1115 CondCode2 = AArch64CC::VS;
1116 break;
1117 case ISD::SETUGT:
1118 CondCode = AArch64CC::HI;
1119 break;
1120 case ISD::SETUGE:
1121 CondCode = AArch64CC::PL;
1122 break;
1123 case ISD::SETLT:
1124 case ISD::SETULT:
1125 CondCode = AArch64CC::LT;
1126 break;
1127 case ISD::SETLE:
1128 case ISD::SETULE:
1129 CondCode = AArch64CC::LE;
1130 break;
1131 case ISD::SETNE:
1132 case ISD::SETUNE:
1133 CondCode = AArch64CC::NE;
1134 break;
1135 }
1136}
1137
1138/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1139/// CC usable with the vector instructions. Fewer operations are available
1140/// without a real NZCV register, so we have to use less efficient combinations
1141/// to get the same effect.
1142static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1143 AArch64CC::CondCode &CondCode,
1144 AArch64CC::CondCode &CondCode2,
1145 bool &Invert) {
1146 Invert = false;
1147 switch (CC) {
1148 default:
1149 // Mostly the scalar mappings work fine.
1150 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1151 break;
1152 case ISD::SETUO:
1153 Invert = true; // Fallthrough
1154 case ISD::SETO:
1155 CondCode = AArch64CC::MI;
1156 CondCode2 = AArch64CC::GE;
1157 break;
1158 case ISD::SETUEQ:
1159 case ISD::SETULT:
1160 case ISD::SETULE:
1161 case ISD::SETUGT:
1162 case ISD::SETUGE:
1163 // All of the compare-mask comparisons are ordered, but we can switch
1164 // between the two by a double inversion. E.g. ULE == !OGT.
1165 Invert = true;
1166 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1167 break;
1168 }
1169}
1170
1171static bool isLegalArithImmed(uint64_t C) {
1172 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1173 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1174}
1175
1176static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1177 SDLoc dl, SelectionDAG &DAG) {
1178 EVT VT = LHS.getValueType();
1179
1180 if (VT.isFloatingPoint())
1181 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1182
1183 // The CMP instruction is just an alias for SUBS, and representing it as
1184 // SUBS means that it's possible to get CSE with subtract operations.
1185 // A later phase can perform the optimization of setting the destination
1186 // register to WZR/XZR if it ends up being unused.
1187 unsigned Opcode = AArch64ISD::SUBS;
1188
Artyom Skrobov314ee042015-11-25 19:41:11 +00001189 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001190 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1191 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1192 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1193 // can be set differently by this operation. It comes down to whether
1194 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1195 // everything is fine. If not then the optimization is wrong. Thus general
1196 // comparisons are only valid if op2 != 0.
1197
1198 // So, finally, the only LLVM-native comparisons that don't mention C and V
1199 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1200 // the absence of information about op2.
1201 Opcode = AArch64ISD::ADDS;
1202 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001203 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001204 !isUnsignedIntSetCC(CC)) {
1205 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1206 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1207 // of the signed comparisons.
1208 Opcode = AArch64ISD::ANDS;
1209 RHS = LHS.getOperand(1);
1210 LHS = LHS.getOperand(0);
1211 }
1212
Matthias Braunaf7d7702015-07-16 20:02:37 +00001213 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001214 .getValue(1);
1215}
1216
Matthias Braunaf7d7702015-07-16 20:02:37 +00001217/// \defgroup AArch64CCMP CMP;CCMP matching
1218///
1219/// These functions deal with the formation of CMP;CCMP;... sequences.
1220/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1221/// a comparison. They set the NZCV flags to a predefined value if their
1222/// predicate is false. This allows to express arbitrary conjunctions, for
1223/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1224/// expressed as:
1225/// cmp A
1226/// ccmp B, inv(CB), CA
1227/// check for CB flags
1228///
1229/// In general we can create code for arbitrary "... (and (and A B) C)"
1230/// sequences. We can also implement some "or" expressions, because "(or A B)"
1231/// is equivalent to "not (and (not A) (not B))" and we can implement some
1232/// negation operations:
1233/// We can negate the results of a single comparison by inverting the flags
1234/// used when the predicate fails and inverting the flags tested in the next
1235/// instruction; We can also negate the results of the whole previous
1236/// conditional compare sequence by inverting the flags tested in the next
1237/// instruction. However there is no way to negate the result of a partial
1238/// sequence.
1239///
1240/// Therefore on encountering an "or" expression we can negate the subtree on
1241/// one side and have to be able to push the negate to the leafs of the subtree
1242/// on the other side (see also the comments in code). As complete example:
1243/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1244/// (and (setCC (cmp C)) (setCD (cmp D)))"
1245/// is transformed to
1246/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1247/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1248/// and implemented as:
1249/// cmp C
1250/// ccmp D, inv(CD), CC
1251/// ccmp A, CA, inv(CD)
1252/// ccmp B, CB, inv(CA)
1253/// check for CB flags
1254/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1255/// by conditional compare sequences.
1256/// @{
1257
Geoff Berrye41c2df2015-07-20 22:03:52 +00001258/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001259static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1260 ISD::CondCode CC, SDValue CCOp,
1261 SDValue Condition, unsigned NZCV,
1262 SDLoc DL, SelectionDAG &DAG) {
1263 unsigned Opcode = 0;
1264 if (LHS.getValueType().isFloatingPoint())
1265 Opcode = AArch64ISD::FCCMP;
1266 else if (RHS.getOpcode() == ISD::SUB) {
1267 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001268 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001269 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1270 Opcode = AArch64ISD::CCMN;
1271 RHS = RHS.getOperand(1);
1272 }
1273 }
1274 if (Opcode == 0)
1275 Opcode = AArch64ISD::CCMP;
1276
1277 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1278 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1279}
1280
1281/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1282/// CanPushNegate is set to true if we can push a negate operation through
1283/// the tree in a was that we are left with AND operations and negate operations
1284/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1285/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1286/// brought into such a form.
1287static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1288 unsigned Depth = 0) {
1289 if (!Val.hasOneUse())
1290 return false;
1291 unsigned Opcode = Val->getOpcode();
1292 if (Opcode == ISD::SETCC) {
1293 CanPushNegate = true;
1294 return true;
1295 }
1296 // Protect against stack overflow.
1297 if (Depth > 15)
1298 return false;
1299 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1300 SDValue O0 = Val->getOperand(0);
1301 SDValue O1 = Val->getOperand(1);
1302 bool CanPushNegateL;
1303 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1304 return false;
1305 bool CanPushNegateR;
1306 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1307 return false;
1308 // We cannot push a negate through an AND operation (it would become an OR),
1309 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1310 // push the negate through the x/y subtrees.
1311 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1312 return true;
1313 }
1314 return false;
1315}
1316
1317/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1318/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1319/// Tries to transform the given i1 producing node @p Val to a series compare
1320/// and conditional compare operations. @returns an NZCV flags producing node
1321/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1322/// transformation was not possible.
1323/// On recursive invocations @p PushNegate may be set to true to have negation
1324/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1325/// for the comparisons in the current subtree; @p Depth limits the search
1326/// depth to avoid stack overflow.
1327static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1328 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1329 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1330 unsigned Depth = 0) {
1331 // We're at a tree leaf, produce a conditional comparison operation.
1332 unsigned Opcode = Val->getOpcode();
1333 if (Opcode == ISD::SETCC) {
1334 SDValue LHS = Val->getOperand(0);
1335 SDValue RHS = Val->getOperand(1);
1336 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1337 bool isInteger = LHS.getValueType().isInteger();
1338 if (PushNegate)
1339 CC = getSetCCInverse(CC, isInteger);
1340 SDLoc DL(Val);
1341 // Determine OutCC and handle FP special case.
1342 if (isInteger) {
1343 OutCC = changeIntCCToAArch64CC(CC);
1344 } else {
1345 assert(LHS.getValueType().isFloatingPoint());
1346 AArch64CC::CondCode ExtraCC;
1347 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1348 // Surpisingly some floating point conditions can't be tested with a
1349 // single condition code. Construct an additional comparison in this case.
1350 // See comment below on how we deal with OR conditions.
1351 if (ExtraCC != AArch64CC::AL) {
1352 SDValue ExtraCmp;
1353 if (!CCOp.getNode())
1354 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1355 else {
1356 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1357 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1358 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1359 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1360 NZCV, DL, DAG);
1361 }
1362 CCOp = ExtraCmp;
1363 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1364 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1365 }
1366 }
1367
1368 // Produce a normal comparison if we are first in the chain
1369 if (!CCOp.getNode())
1370 return emitComparison(LHS, RHS, CC, DL, DAG);
1371 // Otherwise produce a ccmp.
1372 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1373 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1374 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1375 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1376 DAG);
Matthias Braun266204b2015-08-20 23:33:31 +00001377 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
Matthias Braunaf7d7702015-07-16 20:02:37 +00001378 return SDValue();
1379
1380 assert((Opcode == ISD::OR || !PushNegate)
1381 && "Can only push negate through OR operation");
1382
1383 // Check if both sides can be transformed.
1384 SDValue LHS = Val->getOperand(0);
1385 SDValue RHS = Val->getOperand(1);
1386 bool CanPushNegateL;
1387 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1388 return SDValue();
1389 bool CanPushNegateR;
1390 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1391 return SDValue();
1392
1393 // Do we need to negate our operands?
1394 bool NegateOperands = Opcode == ISD::OR;
1395 // We can negate the results of all previous operations by inverting the
1396 // predicate flags giving us a free negation for one side. For the other side
1397 // we need to be able to push the negation to the leafs of the tree.
1398 if (NegateOperands) {
1399 if (!CanPushNegateL && !CanPushNegateR)
1400 return SDValue();
1401 // Order the side where we can push the negate through to LHS.
Matthias Braun46e56392015-08-20 23:33:34 +00001402 if (!CanPushNegateL && CanPushNegateR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001403 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001404 } else {
1405 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1406 bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1407 if (NeedsNegOutL && NeedsNegOutR)
1408 return SDValue();
1409 // Order the side where we need to negate the output flags to RHS so it
1410 // gets emitted first.
1411 if (NeedsNegOutL)
1412 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001413 }
1414
1415 // Emit RHS. If we want to negate the tree we only need to push a negate
1416 // through if we are already in a PushNegate case, otherwise we can negate
1417 // the "flags to test" afterwards.
1418 AArch64CC::CondCode RHSCC;
1419 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1420 CCOp, Predicate, Depth+1);
Ahmed Bougacha6345b9e2016-01-22 19:43:43 +00001421 assert(CmpR && "Transform legality should have been checked already!");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001422 if (NegateOperands && !PushNegate)
1423 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1424 // Emit LHS. We must push the negate through if we need to negate it.
1425 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1426 CmpR, RHSCC, Depth+1);
Ahmed Bougacha6345b9e2016-01-22 19:43:43 +00001427 assert(CmpL && "Transform legality should have been checked already!");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001428 // If we transformed an OR to and AND then we have to negate the result
1429 // (or absorb a PushNegate resulting in a double negation).
1430 if (Opcode == ISD::OR && !PushNegate)
1431 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1432 return CmpL;
1433}
1434
1435/// @}
1436
Tim Northover3b0846e2014-05-24 12:50:23 +00001437static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1438 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1439 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1440 EVT VT = RHS.getValueType();
1441 uint64_t C = RHSC->getZExtValue();
1442 if (!isLegalArithImmed(C)) {
1443 // Constant does not fit, try adjusting it by one?
1444 switch (CC) {
1445 default:
1446 break;
1447 case ISD::SETLT:
1448 case ISD::SETGE:
1449 if ((VT == MVT::i32 && C != 0x80000000 &&
1450 isLegalArithImmed((uint32_t)(C - 1))) ||
1451 (VT == MVT::i64 && C != 0x80000000ULL &&
1452 isLegalArithImmed(C - 1ULL))) {
1453 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1454 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001455 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001456 }
1457 break;
1458 case ISD::SETULT:
1459 case ISD::SETUGE:
1460 if ((VT == MVT::i32 && C != 0 &&
1461 isLegalArithImmed((uint32_t)(C - 1))) ||
1462 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1463 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1464 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001465 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001466 }
1467 break;
1468 case ISD::SETLE:
1469 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001470 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001471 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001472 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001473 isLegalArithImmed(C + 1ULL))) {
1474 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1475 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001476 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001477 }
1478 break;
1479 case ISD::SETULE:
1480 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001481 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001482 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001483 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001484 isLegalArithImmed(C + 1ULL))) {
1485 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1486 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001487 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001488 }
1489 break;
1490 }
1491 }
1492 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001493 SDValue Cmp;
1494 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001495 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001496 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1497
1498 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1499 // For the i8 operand, the largest immediate is 255, so this can be easily
1500 // encoded in the compare instruction. For the i16 operand, however, the
1501 // largest immediate cannot be encoded in the compare.
1502 // Therefore, use a sign extending load and cmn to avoid materializing the
1503 // -1 constant. For example,
1504 // movz w1, #65535
1505 // ldrh w0, [x0, #0]
1506 // cmp w0, w1
1507 // >
1508 // ldrsh w0, [x0, #0]
1509 // cmn w0, #1
1510 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1511 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001512 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001513 // transformation is profitable.
1514 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1515 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1516 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1517 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1518 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1519 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1520 SDValue SExt =
1521 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1522 DAG.getValueType(MVT::i16));
1523 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1524 RHS.getValueType()),
1525 CC, dl, DAG);
1526 AArch64CC = changeIntCCToAArch64CC(CC);
1527 }
1528 }
1529
1530 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1531 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1532 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1533 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001534 }
1535 }
1536 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001537
1538 if (!Cmp) {
1539 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1540 AArch64CC = changeIntCCToAArch64CC(CC);
1541 }
1542 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001543 return Cmp;
1544}
1545
1546static std::pair<SDValue, SDValue>
1547getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1548 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1549 "Unsupported value type");
1550 SDValue Value, Overflow;
1551 SDLoc DL(Op);
1552 SDValue LHS = Op.getOperand(0);
1553 SDValue RHS = Op.getOperand(1);
1554 unsigned Opc = 0;
1555 switch (Op.getOpcode()) {
1556 default:
1557 llvm_unreachable("Unknown overflow instruction!");
1558 case ISD::SADDO:
1559 Opc = AArch64ISD::ADDS;
1560 CC = AArch64CC::VS;
1561 break;
1562 case ISD::UADDO:
1563 Opc = AArch64ISD::ADDS;
1564 CC = AArch64CC::HS;
1565 break;
1566 case ISD::SSUBO:
1567 Opc = AArch64ISD::SUBS;
1568 CC = AArch64CC::VS;
1569 break;
1570 case ISD::USUBO:
1571 Opc = AArch64ISD::SUBS;
1572 CC = AArch64CC::LO;
1573 break;
1574 // Multiply needs a little bit extra work.
1575 case ISD::SMULO:
1576 case ISD::UMULO: {
1577 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001578 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001579 if (Op.getValueType() == MVT::i32) {
1580 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1581 // For a 32 bit multiply with overflow check we want the instruction
1582 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1583 // need to generate the following pattern:
1584 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1585 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1586 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1587 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1588 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001589 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001590 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1591 // operation. We need to clear out the upper 32 bits, because we used a
1592 // widening multiply that wrote all 64 bits. In the end this should be a
1593 // noop.
1594 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1595 if (IsSigned) {
1596 // The signed overflow check requires more than just a simple check for
1597 // any bit set in the upper 32 bits of the result. These bits could be
1598 // just the sign bits of a negative number. To perform the overflow
1599 // check we have to arithmetic shift right the 32nd bit of the result by
1600 // 31 bits. Then we compare the result to the upper 32 bits.
1601 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001602 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001603 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1604 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001605 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001606 // It is important that LowerBits is last, otherwise the arithmetic
1607 // shift will not be folded into the compare (SUBS).
1608 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1609 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1610 .getValue(1);
1611 } else {
1612 // The overflow check for unsigned multiply is easy. We only need to
1613 // check if any of the upper 32 bits are set. This can be done with a
1614 // CMP (shifted register). For that we need to generate the following
1615 // pattern:
1616 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1617 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001618 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001619 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1620 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001621 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1622 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001623 UpperBits).getValue(1);
1624 }
1625 break;
1626 }
1627 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1628 // For the 64 bit multiply
1629 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1630 if (IsSigned) {
1631 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1632 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001633 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001634 // It is important that LowerBits is last, otherwise the arithmetic
1635 // shift will not be folded into the compare (SUBS).
1636 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1637 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1638 .getValue(1);
1639 } else {
1640 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1641 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1642 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001643 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1644 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001645 UpperBits).getValue(1);
1646 }
1647 break;
1648 }
1649 } // switch (...)
1650
1651 if (Opc) {
1652 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1653
1654 // Emit the AArch64 operation with overflow check.
1655 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1656 Overflow = Value.getValue(1);
1657 }
1658 return std::make_pair(Value, Overflow);
1659}
1660
1661SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1662 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001663 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001664 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001665}
1666
1667static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1668 SDValue Sel = Op.getOperand(0);
1669 SDValue Other = Op.getOperand(1);
1670
1671 // If neither operand is a SELECT_CC, give up.
1672 if (Sel.getOpcode() != ISD::SELECT_CC)
1673 std::swap(Sel, Other);
1674 if (Sel.getOpcode() != ISD::SELECT_CC)
1675 return Op;
1676
1677 // The folding we want to perform is:
1678 // (xor x, (select_cc a, b, cc, 0, -1) )
1679 // -->
1680 // (csel x, (xor x, -1), cc ...)
1681 //
1682 // The latter will get matched to a CSINV instruction.
1683
1684 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1685 SDValue LHS = Sel.getOperand(0);
1686 SDValue RHS = Sel.getOperand(1);
1687 SDValue TVal = Sel.getOperand(2);
1688 SDValue FVal = Sel.getOperand(3);
1689 SDLoc dl(Sel);
1690
1691 // FIXME: This could be generalized to non-integer comparisons.
1692 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1693 return Op;
1694
1695 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1696 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1697
Eric Christopher572e03a2015-06-19 01:53:21 +00001698 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001699 if (!CFVal || !CTVal)
1700 return Op;
1701
1702 // We can commute the SELECT_CC by inverting the condition. This
1703 // might be needed to make this fit into a CSINV pattern.
1704 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1705 std::swap(TVal, FVal);
1706 std::swap(CTVal, CFVal);
1707 CC = ISD::getSetCCInverse(CC, true);
1708 }
1709
1710 // If the constants line up, perform the transform!
1711 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1712 SDValue CCVal;
1713 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1714
1715 FVal = Other;
1716 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001717 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001718
1719 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1720 CCVal, Cmp);
1721 }
1722
1723 return Op;
1724}
1725
1726static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1727 EVT VT = Op.getValueType();
1728
1729 // Let legalize expand this if it isn't a legal type yet.
1730 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1731 return SDValue();
1732
1733 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1734
1735 unsigned Opc;
1736 bool ExtraOp = false;
1737 switch (Op.getOpcode()) {
1738 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001739 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001740 case ISD::ADDC:
1741 Opc = AArch64ISD::ADDS;
1742 break;
1743 case ISD::SUBC:
1744 Opc = AArch64ISD::SUBS;
1745 break;
1746 case ISD::ADDE:
1747 Opc = AArch64ISD::ADCS;
1748 ExtraOp = true;
1749 break;
1750 case ISD::SUBE:
1751 Opc = AArch64ISD::SBCS;
1752 ExtraOp = true;
1753 break;
1754 }
1755
1756 if (!ExtraOp)
1757 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1758 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1759 Op.getOperand(2));
1760}
1761
1762static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1763 // Let legalize expand this if it isn't a legal type yet.
1764 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1765 return SDValue();
1766
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001767 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001768 AArch64CC::CondCode CC;
1769 // The actual operation that sets the overflow or carry flag.
1770 SDValue Value, Overflow;
1771 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1772
1773 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001774 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1775 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001776
1777 // We use an inverted condition, because the conditional select is inverted
1778 // too. This will allow it to be selected to a single instruction:
1779 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001780 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1781 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001782 CCVal, Overflow);
1783
1784 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001785 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001786}
1787
1788// Prefetch operands are:
1789// 1: Address to prefetch
1790// 2: bool isWrite
1791// 3: int locality (0 = no locality ... 3 = extreme locality)
1792// 4: bool isDataCache
1793static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1794 SDLoc DL(Op);
1795 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1796 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001797 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001798
1799 bool IsStream = !Locality;
1800 // When the locality number is set
1801 if (Locality) {
1802 // The front-end should have filtered out the out-of-range values
1803 assert(Locality <= 3 && "Prefetch locality out-of-range");
1804 // The locality degree is the opposite of the cache speed.
1805 // Put the number the other way around.
1806 // The encoding starts at 0 for level 1
1807 Locality = 3 - Locality;
1808 }
1809
1810 // built the mask value encoding the expected behavior.
1811 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001812 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001813 (Locality << 1) | // Cache level bits
1814 (unsigned)IsStream; // Stream bit
1815 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001816 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001817}
1818
1819SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1820 SelectionDAG &DAG) const {
1821 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1822
1823 RTLIB::Libcall LC;
1824 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1825
1826 return LowerF128Call(Op, DAG, LC);
1827}
1828
1829SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1830 SelectionDAG &DAG) const {
1831 if (Op.getOperand(0).getValueType() != MVT::f128) {
1832 // It's legal except when f128 is involved
1833 return Op;
1834 }
1835
1836 RTLIB::Libcall LC;
1837 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1838
1839 // FP_ROUND node has a second operand indicating whether it is known to be
1840 // precise. That doesn't take part in the LibCall so we can't directly use
1841 // LowerF128Call.
1842 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001843 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1844 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001845}
1846
1847static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1848 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1849 // Any additional optimization in this function should be recorded
1850 // in the cost tables.
1851 EVT InVT = Op.getOperand(0).getValueType();
1852 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001853 unsigned NumElts = InVT.getVectorNumElements();
1854
1855 // f16 vectors are promoted to f32 before a conversion.
1856 if (InVT.getVectorElementType() == MVT::f16) {
1857 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1858 SDLoc dl(Op);
1859 return DAG.getNode(
1860 Op.getOpcode(), dl, Op.getValueType(),
1861 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1862 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001863
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001864 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001865 SDLoc dl(Op);
1866 SDValue Cv =
1867 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1868 Op.getOperand(0));
1869 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001870 }
1871
1872 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001873 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001874 MVT ExtVT =
1875 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1876 VT.getVectorNumElements());
1877 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001878 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1879 }
1880
1881 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001882 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001883}
1884
1885SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1886 SelectionDAG &DAG) const {
1887 if (Op.getOperand(0).getValueType().isVector())
1888 return LowerVectorFP_TO_INT(Op, DAG);
1889
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001890 // f16 conversions are promoted to f32.
1891 if (Op.getOperand(0).getValueType() == MVT::f16) {
1892 SDLoc dl(Op);
1893 return DAG.getNode(
1894 Op.getOpcode(), dl, Op.getValueType(),
1895 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1896 }
1897
Tim Northover3b0846e2014-05-24 12:50:23 +00001898 if (Op.getOperand(0).getValueType() != MVT::f128) {
1899 // It's legal except when f128 is involved
1900 return Op;
1901 }
1902
1903 RTLIB::Libcall LC;
1904 if (Op.getOpcode() == ISD::FP_TO_SINT)
1905 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1906 else
1907 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1908
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001909 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001910 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001911}
1912
1913static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1914 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1915 // Any additional optimization in this function should be recorded
1916 // in the cost tables.
1917 EVT VT = Op.getValueType();
1918 SDLoc dl(Op);
1919 SDValue In = Op.getOperand(0);
1920 EVT InVT = In.getValueType();
1921
Tim Northoveref0d7602014-06-15 09:27:06 +00001922 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1923 MVT CastVT =
1924 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1925 InVT.getVectorNumElements());
1926 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001927 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001928 }
1929
Tim Northoveref0d7602014-06-15 09:27:06 +00001930 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1931 unsigned CastOpc =
1932 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1933 EVT CastVT = VT.changeVectorElementTypeToInteger();
1934 In = DAG.getNode(CastOpc, dl, CastVT, In);
1935 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001936 }
1937
Tim Northoveref0d7602014-06-15 09:27:06 +00001938 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001939}
1940
1941SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1942 SelectionDAG &DAG) const {
1943 if (Op.getValueType().isVector())
1944 return LowerVectorINT_TO_FP(Op, DAG);
1945
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001946 // f16 conversions are promoted to f32.
1947 if (Op.getValueType() == MVT::f16) {
1948 SDLoc dl(Op);
1949 return DAG.getNode(
1950 ISD::FP_ROUND, dl, MVT::f16,
1951 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001952 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001953 }
1954
Tim Northover3b0846e2014-05-24 12:50:23 +00001955 // i128 conversions are libcalls.
1956 if (Op.getOperand(0).getValueType() == MVT::i128)
1957 return SDValue();
1958
1959 // Other conversions are legal, unless it's to the completely software-based
1960 // fp128.
1961 if (Op.getValueType() != MVT::f128)
1962 return Op;
1963
1964 RTLIB::Libcall LC;
1965 if (Op.getOpcode() == ISD::SINT_TO_FP)
1966 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1967 else
1968 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1969
1970 return LowerF128Call(Op, DAG, LC);
1971}
1972
1973SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1974 SelectionDAG &DAG) const {
1975 // For iOS, we want to call an alternative entry point: __sincos_stret,
1976 // which returns the values in two S / D registers.
1977 SDLoc dl(Op);
1978 SDValue Arg = Op.getOperand(0);
1979 EVT ArgVT = Arg.getValueType();
1980 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1981
1982 ArgListTy Args;
1983 ArgListEntry Entry;
1984
1985 Entry.Node = Arg;
1986 Entry.Ty = ArgTy;
1987 Entry.isSExt = false;
1988 Entry.isZExt = false;
1989 Args.push_back(Entry);
1990
1991 const char *LibcallName =
1992 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00001993 SDValue Callee =
1994 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001995
Reid Kleckner343c3952014-11-20 23:51:47 +00001996 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00001997 TargetLowering::CallLoweringInfo CLI(DAG);
1998 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00001999 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002000
2001 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2002 return CallResult.first;
2003}
2004
Tim Northoverf8bfe212014-07-18 13:07:05 +00002005static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2006 if (Op.getValueType() != MVT::f16)
2007 return SDValue();
2008
2009 assert(Op.getOperand(0).getValueType() == MVT::i16);
2010 SDLoc DL(Op);
2011
2012 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2013 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2014 return SDValue(
2015 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002016 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002017 0);
2018}
2019
Chad Rosierd9d0f862014-10-08 02:31:24 +00002020static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2021 if (OrigVT.getSizeInBits() >= 64)
2022 return OrigVT;
2023
2024 assert(OrigVT.isSimple() && "Expecting a simple value type");
2025
2026 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2027 switch (OrigSimpleTy) {
2028 default: llvm_unreachable("Unexpected Vector Type");
2029 case MVT::v2i8:
2030 case MVT::v2i16:
2031 return MVT::v2i32;
2032 case MVT::v4i8:
2033 return MVT::v4i16;
2034 }
2035}
2036
2037static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2038 const EVT &OrigTy,
2039 const EVT &ExtTy,
2040 unsigned ExtOpcode) {
2041 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2042 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2043 // 64-bits we need to insert a new extension so that it will be 64-bits.
2044 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2045 if (OrigTy.getSizeInBits() >= 64)
2046 return N;
2047
2048 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2049 EVT NewVT = getExtensionTo64Bits(OrigTy);
2050
2051 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2052}
2053
2054static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2055 bool isSigned) {
2056 EVT VT = N->getValueType(0);
2057
2058 if (N->getOpcode() != ISD::BUILD_VECTOR)
2059 return false;
2060
Pete Cooper3af9a252015-06-26 18:17:36 +00002061 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002062 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2063 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2064 unsigned HalfSize = EltSize / 2;
2065 if (isSigned) {
2066 if (!isIntN(HalfSize, C->getSExtValue()))
2067 return false;
2068 } else {
2069 if (!isUIntN(HalfSize, C->getZExtValue()))
2070 return false;
2071 }
2072 continue;
2073 }
2074 return false;
2075 }
2076
2077 return true;
2078}
2079
2080static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2081 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2082 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2083 N->getOperand(0)->getValueType(0),
2084 N->getValueType(0),
2085 N->getOpcode());
2086
2087 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2088 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002089 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002090 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2091 unsigned NumElts = VT.getVectorNumElements();
2092 MVT TruncVT = MVT::getIntegerVT(EltSize);
2093 SmallVector<SDValue, 8> Ops;
2094 for (unsigned i = 0; i != NumElts; ++i) {
2095 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2096 const APInt &CInt = C->getAPIntValue();
2097 // Element types smaller than 32 bits are not legal, so use i32 elements.
2098 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002099 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002100 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002101 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002102 MVT::getVectorVT(TruncVT, NumElts), Ops);
2103}
2104
2105static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2106 if (N->getOpcode() == ISD::SIGN_EXTEND)
2107 return true;
2108 if (isExtendedBUILD_VECTOR(N, DAG, true))
2109 return true;
2110 return false;
2111}
2112
2113static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2114 if (N->getOpcode() == ISD::ZERO_EXTEND)
2115 return true;
2116 if (isExtendedBUILD_VECTOR(N, DAG, false))
2117 return true;
2118 return false;
2119}
2120
2121static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2122 unsigned Opcode = N->getOpcode();
2123 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2124 SDNode *N0 = N->getOperand(0).getNode();
2125 SDNode *N1 = N->getOperand(1).getNode();
2126 return N0->hasOneUse() && N1->hasOneUse() &&
2127 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2128 }
2129 return false;
2130}
2131
2132static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2133 unsigned Opcode = N->getOpcode();
2134 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2135 SDNode *N0 = N->getOperand(0).getNode();
2136 SDNode *N1 = N->getOperand(1).getNode();
2137 return N0->hasOneUse() && N1->hasOneUse() &&
2138 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2139 }
2140 return false;
2141}
2142
2143static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2144 // Multiplications are only custom-lowered for 128-bit vectors so that
2145 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2146 EVT VT = Op.getValueType();
2147 assert(VT.is128BitVector() && VT.isInteger() &&
2148 "unexpected type for custom-lowering ISD::MUL");
2149 SDNode *N0 = Op.getOperand(0).getNode();
2150 SDNode *N1 = Op.getOperand(1).getNode();
2151 unsigned NewOpc = 0;
2152 bool isMLA = false;
2153 bool isN0SExt = isSignExtended(N0, DAG);
2154 bool isN1SExt = isSignExtended(N1, DAG);
2155 if (isN0SExt && isN1SExt)
2156 NewOpc = AArch64ISD::SMULL;
2157 else {
2158 bool isN0ZExt = isZeroExtended(N0, DAG);
2159 bool isN1ZExt = isZeroExtended(N1, DAG);
2160 if (isN0ZExt && isN1ZExt)
2161 NewOpc = AArch64ISD::UMULL;
2162 else if (isN1SExt || isN1ZExt) {
2163 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2164 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2165 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2166 NewOpc = AArch64ISD::SMULL;
2167 isMLA = true;
2168 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2169 NewOpc = AArch64ISD::UMULL;
2170 isMLA = true;
2171 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2172 std::swap(N0, N1);
2173 NewOpc = AArch64ISD::UMULL;
2174 isMLA = true;
2175 }
2176 }
2177
2178 if (!NewOpc) {
2179 if (VT == MVT::v2i64)
2180 // Fall through to expand this. It is not legal.
2181 return SDValue();
2182 else
2183 // Other vector multiplications are legal.
2184 return Op;
2185 }
2186 }
2187
2188 // Legalize to a S/UMULL instruction
2189 SDLoc DL(Op);
2190 SDValue Op0;
2191 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2192 if (!isMLA) {
2193 Op0 = skipExtensionForVectorMULL(N0, DAG);
2194 assert(Op0.getValueType().is64BitVector() &&
2195 Op1.getValueType().is64BitVector() &&
2196 "unexpected types for extended operands to VMULL");
2197 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2198 }
2199 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2200 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2201 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2202 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2203 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2204 EVT Op1VT = Op1.getValueType();
2205 return DAG.getNode(N0->getOpcode(), DL, VT,
2206 DAG.getNode(NewOpc, DL, VT,
2207 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2208 DAG.getNode(NewOpc, DL, VT,
2209 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2210}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002211
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002212SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2213 SelectionDAG &DAG) const {
2214 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2215 SDLoc dl(Op);
2216 switch (IntNo) {
2217 default: return SDValue(); // Don't custom lower most intrinsics.
2218 case Intrinsic::aarch64_thread_pointer: {
2219 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2220 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2221 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002222 case Intrinsic::aarch64_neon_smax:
2223 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2224 Op.getOperand(1), Op.getOperand(2));
2225 case Intrinsic::aarch64_neon_umax:
2226 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2227 Op.getOperand(1), Op.getOperand(2));
2228 case Intrinsic::aarch64_neon_smin:
2229 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2230 Op.getOperand(1), Op.getOperand(2));
2231 case Intrinsic::aarch64_neon_umin:
2232 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2233 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002234 }
2235}
2236
Tim Northover3b0846e2014-05-24 12:50:23 +00002237SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2238 SelectionDAG &DAG) const {
2239 switch (Op.getOpcode()) {
2240 default:
2241 llvm_unreachable("unimplemented operand");
2242 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002243 case ISD::BITCAST:
2244 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002245 case ISD::GlobalAddress:
2246 return LowerGlobalAddress(Op, DAG);
2247 case ISD::GlobalTLSAddress:
2248 return LowerGlobalTLSAddress(Op, DAG);
2249 case ISD::SETCC:
2250 return LowerSETCC(Op, DAG);
2251 case ISD::BR_CC:
2252 return LowerBR_CC(Op, DAG);
2253 case ISD::SELECT:
2254 return LowerSELECT(Op, DAG);
2255 case ISD::SELECT_CC:
2256 return LowerSELECT_CC(Op, DAG);
2257 case ISD::JumpTable:
2258 return LowerJumpTable(Op, DAG);
2259 case ISD::ConstantPool:
2260 return LowerConstantPool(Op, DAG);
2261 case ISD::BlockAddress:
2262 return LowerBlockAddress(Op, DAG);
2263 case ISD::VASTART:
2264 return LowerVASTART(Op, DAG);
2265 case ISD::VACOPY:
2266 return LowerVACOPY(Op, DAG);
2267 case ISD::VAARG:
2268 return LowerVAARG(Op, DAG);
2269 case ISD::ADDC:
2270 case ISD::ADDE:
2271 case ISD::SUBC:
2272 case ISD::SUBE:
2273 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2274 case ISD::SADDO:
2275 case ISD::UADDO:
2276 case ISD::SSUBO:
2277 case ISD::USUBO:
2278 case ISD::SMULO:
2279 case ISD::UMULO:
2280 return LowerXALUO(Op, DAG);
2281 case ISD::FADD:
2282 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2283 case ISD::FSUB:
2284 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2285 case ISD::FMUL:
2286 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2287 case ISD::FDIV:
2288 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2289 case ISD::FP_ROUND:
2290 return LowerFP_ROUND(Op, DAG);
2291 case ISD::FP_EXTEND:
2292 return LowerFP_EXTEND(Op, DAG);
2293 case ISD::FRAMEADDR:
2294 return LowerFRAMEADDR(Op, DAG);
2295 case ISD::RETURNADDR:
2296 return LowerRETURNADDR(Op, DAG);
2297 case ISD::INSERT_VECTOR_ELT:
2298 return LowerINSERT_VECTOR_ELT(Op, DAG);
2299 case ISD::EXTRACT_VECTOR_ELT:
2300 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2301 case ISD::BUILD_VECTOR:
2302 return LowerBUILD_VECTOR(Op, DAG);
2303 case ISD::VECTOR_SHUFFLE:
2304 return LowerVECTOR_SHUFFLE(Op, DAG);
2305 case ISD::EXTRACT_SUBVECTOR:
2306 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2307 case ISD::SRA:
2308 case ISD::SRL:
2309 case ISD::SHL:
2310 return LowerVectorSRA_SRL_SHL(Op, DAG);
2311 case ISD::SHL_PARTS:
2312 return LowerShiftLeftParts(Op, DAG);
2313 case ISD::SRL_PARTS:
2314 case ISD::SRA_PARTS:
2315 return LowerShiftRightParts(Op, DAG);
2316 case ISD::CTPOP:
2317 return LowerCTPOP(Op, DAG);
2318 case ISD::FCOPYSIGN:
2319 return LowerFCOPYSIGN(Op, DAG);
2320 case ISD::AND:
2321 return LowerVectorAND(Op, DAG);
2322 case ISD::OR:
2323 return LowerVectorOR(Op, DAG);
2324 case ISD::XOR:
2325 return LowerXOR(Op, DAG);
2326 case ISD::PREFETCH:
2327 return LowerPREFETCH(Op, DAG);
2328 case ISD::SINT_TO_FP:
2329 case ISD::UINT_TO_FP:
2330 return LowerINT_TO_FP(Op, DAG);
2331 case ISD::FP_TO_SINT:
2332 case ISD::FP_TO_UINT:
2333 return LowerFP_TO_INT(Op, DAG);
2334 case ISD::FSINCOS:
2335 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002336 case ISD::MUL:
2337 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002338 case ISD::INTRINSIC_WO_CHAIN:
2339 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002340 }
2341}
2342
Tim Northover3b0846e2014-05-24 12:50:23 +00002343//===----------------------------------------------------------------------===//
2344// Calling Convention Implementation
2345//===----------------------------------------------------------------------===//
2346
2347#include "AArch64GenCallingConv.inc"
2348
Robin Morisset039781e2014-08-29 21:53:01 +00002349/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002350CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2351 bool IsVarArg) const {
2352 switch (CC) {
2353 default:
2354 llvm_unreachable("Unsupported calling convention.");
2355 case CallingConv::WebKit_JS:
2356 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002357 case CallingConv::GHC:
2358 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002359 case CallingConv::C:
2360 case CallingConv::Fast:
2361 if (!Subtarget->isTargetDarwin())
2362 return CC_AArch64_AAPCS;
2363 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2364 }
2365}
2366
2367SDValue AArch64TargetLowering::LowerFormalArguments(
2368 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2369 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2370 SmallVectorImpl<SDValue> &InVals) const {
2371 MachineFunction &MF = DAG.getMachineFunction();
2372 MachineFrameInfo *MFI = MF.getFrameInfo();
2373
2374 // Assign locations to all of the incoming arguments.
2375 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002376 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2377 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002378
2379 // At this point, Ins[].VT may already be promoted to i32. To correctly
2380 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2381 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2382 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2383 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2384 // LocVT.
2385 unsigned NumArgs = Ins.size();
2386 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2387 unsigned CurArgIdx = 0;
2388 for (unsigned i = 0; i != NumArgs; ++i) {
2389 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002390 if (Ins[i].isOrigArg()) {
2391 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2392 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002393
Andrew Trick05938a52015-02-16 18:10:47 +00002394 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002395 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2396 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002397 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2398 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2399 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2400 ValVT = MVT::i8;
2401 else if (ActualMVT == MVT::i16)
2402 ValVT = MVT::i16;
2403 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002404 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2405 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002406 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002407 assert(!Res && "Call operand has unhandled type");
2408 (void)Res;
2409 }
2410 assert(ArgLocs.size() == Ins.size());
2411 SmallVector<SDValue, 16> ArgValues;
2412 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2413 CCValAssign &VA = ArgLocs[i];
2414
2415 if (Ins[i].Flags.isByVal()) {
2416 // Byval is used for HFAs in the PCS, but the system should work in a
2417 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002418 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002419 int Size = Ins[i].Flags.getByValSize();
2420 unsigned NumRegs = (Size + 7) / 8;
2421
2422 // FIXME: This works on big-endian for composite byvals, which are the common
2423 // case. It should also work for fundamental types too.
2424 unsigned FrameIdx =
2425 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002426 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002427 InVals.push_back(FrameIdxN);
2428
2429 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002430 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002431
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002432 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002433 // Arguments stored in registers.
2434 EVT RegVT = VA.getLocVT();
2435
2436 SDValue ArgValue;
2437 const TargetRegisterClass *RC;
2438
2439 if (RegVT == MVT::i32)
2440 RC = &AArch64::GPR32RegClass;
2441 else if (RegVT == MVT::i64)
2442 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002443 else if (RegVT == MVT::f16)
2444 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002445 else if (RegVT == MVT::f32)
2446 RC = &AArch64::FPR32RegClass;
2447 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2448 RC = &AArch64::FPR64RegClass;
2449 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2450 RC = &AArch64::FPR128RegClass;
2451 else
2452 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2453
2454 // Transform the arguments in physical registers into virtual ones.
2455 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2456 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2457
2458 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2459 // to 64 bits. Insert an assert[sz]ext to capture this, then
2460 // truncate to the right size.
2461 switch (VA.getLocInfo()) {
2462 default:
2463 llvm_unreachable("Unknown loc info!");
2464 case CCValAssign::Full:
2465 break;
2466 case CCValAssign::BCvt:
2467 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2468 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002469 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002470 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002471 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002472 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2473 // nodes after our lowering.
2474 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002475 break;
2476 }
2477
2478 InVals.push_back(ArgValue);
2479
2480 } else { // VA.isRegLoc()
2481 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2482 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002483 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002484
2485 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002486 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2487 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002488 BEAlign = 8 - ArgSize;
2489
2490 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2491
2492 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002493 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002494 SDValue ArgValue;
2495
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002496 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002497 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002498 MVT MemVT = VA.getValVT();
2499
Tim Northover47e003c2014-05-26 17:21:53 +00002500 switch (VA.getLocInfo()) {
2501 default:
2502 break;
Tim Northover6890add2014-06-03 13:54:53 +00002503 case CCValAssign::BCvt:
2504 MemVT = VA.getLocVT();
2505 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002506 case CCValAssign::SExt:
2507 ExtType = ISD::SEXTLOAD;
2508 break;
2509 case CCValAssign::ZExt:
2510 ExtType = ISD::ZEXTLOAD;
2511 break;
2512 case CCValAssign::AExt:
2513 ExtType = ISD::EXTLOAD;
2514 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002515 }
2516
Alex Lorenze40c8a22015-08-11 23:09:45 +00002517 ArgValue = DAG.getExtLoad(
2518 ExtType, DL, VA.getLocVT(), Chain, FIN,
2519 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2520 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002521
Tim Northover3b0846e2014-05-24 12:50:23 +00002522 InVals.push_back(ArgValue);
2523 }
2524 }
2525
2526 // varargs
2527 if (isVarArg) {
2528 if (!Subtarget->isTargetDarwin()) {
2529 // The AAPCS variadic function ABI is identical to the non-variadic
2530 // one. As a result there may be more arguments in registers and we should
2531 // save them for future reference.
2532 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2533 }
2534
2535 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2536 // This will point to the next argument passed via stack.
2537 unsigned StackOffset = CCInfo.getNextStackOffset();
2538 // We currently pass all varargs at 8-byte alignment.
2539 StackOffset = ((StackOffset + 7) & ~7);
2540 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2541 }
2542
2543 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2544 unsigned StackArgSize = CCInfo.getNextStackOffset();
2545 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2546 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2547 // This is a non-standard ABI so by fiat I say we're allowed to make full
2548 // use of the stack area to be popped, which must be aligned to 16 bytes in
2549 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002550 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002551
2552 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2553 // a multiple of 16.
2554 FuncInfo->setArgumentStackToRestore(StackArgSize);
2555
2556 // This realignment carries over to the available bytes below. Our own
2557 // callers will guarantee the space is free by giving an aligned value to
2558 // CALLSEQ_START.
2559 }
2560 // Even if we're not expected to free up the space, it's useful to know how
2561 // much is there while considering tail calls (because we can reuse it).
2562 FuncInfo->setBytesInStackArgArea(StackArgSize);
2563
2564 return Chain;
2565}
2566
2567void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2568 SelectionDAG &DAG, SDLoc DL,
2569 SDValue &Chain) const {
2570 MachineFunction &MF = DAG.getMachineFunction();
2571 MachineFrameInfo *MFI = MF.getFrameInfo();
2572 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002573 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002574
2575 SmallVector<SDValue, 8> MemOps;
2576
2577 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2578 AArch64::X3, AArch64::X4, AArch64::X5,
2579 AArch64::X6, AArch64::X7 };
2580 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002581 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002582
2583 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2584 int GPRIdx = 0;
2585 if (GPRSaveSize != 0) {
2586 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2587
Mehdi Amini44ede332015-07-09 02:09:04 +00002588 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002589
2590 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2591 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2592 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002593 SDValue Store = DAG.getStore(
2594 Val.getValue(1), DL, Val, FIN,
2595 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2596 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002597 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002598 FIN =
2599 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002600 }
2601 }
2602 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2603 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2604
2605 if (Subtarget->hasFPARMv8()) {
2606 static const MCPhysReg FPRArgRegs[] = {
2607 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2608 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2609 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002610 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002611
2612 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2613 int FPRIdx = 0;
2614 if (FPRSaveSize != 0) {
2615 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2616
Mehdi Amini44ede332015-07-09 02:09:04 +00002617 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002618
2619 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2620 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2621 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2622
Alex Lorenze40c8a22015-08-11 23:09:45 +00002623 SDValue Store = DAG.getStore(
2624 Val.getValue(1), DL, Val, FIN,
2625 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2626 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002627 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002628 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2629 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002630 }
2631 }
2632 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2633 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2634 }
2635
2636 if (!MemOps.empty()) {
2637 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2638 }
2639}
2640
2641/// LowerCallResult - Lower the result values of a call into the
2642/// appropriate copies out of appropriate physical registers.
2643SDValue AArch64TargetLowering::LowerCallResult(
2644 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2645 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2646 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2647 SDValue ThisVal) const {
2648 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2649 ? RetCC_AArch64_WebKit_JS
2650 : RetCC_AArch64_AAPCS;
2651 // Assign locations to each value returned by this call.
2652 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002653 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2654 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002655 CCInfo.AnalyzeCallResult(Ins, RetCC);
2656
2657 // Copy all of the result registers out of their specified physreg.
2658 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2659 CCValAssign VA = RVLocs[i];
2660
2661 // Pass 'this' value directly from the argument to return value, to avoid
2662 // reg unit interference
2663 if (i == 0 && isThisReturn) {
2664 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2665 "unexpected return calling convention register assignment");
2666 InVals.push_back(ThisVal);
2667 continue;
2668 }
2669
2670 SDValue Val =
2671 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2672 Chain = Val.getValue(1);
2673 InFlag = Val.getValue(2);
2674
2675 switch (VA.getLocInfo()) {
2676 default:
2677 llvm_unreachable("Unknown loc info!");
2678 case CCValAssign::Full:
2679 break;
2680 case CCValAssign::BCvt:
2681 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2682 break;
2683 }
2684
2685 InVals.push_back(Val);
2686 }
2687
2688 return Chain;
2689}
2690
2691bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2692 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2693 bool isCalleeStructRet, bool isCallerStructRet,
2694 const SmallVectorImpl<ISD::OutputArg> &Outs,
2695 const SmallVectorImpl<SDValue> &OutVals,
2696 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2697 // For CallingConv::C this function knows whether the ABI needs
2698 // changing. That's not true for other conventions so they will have to opt in
2699 // manually.
2700 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2701 return false;
2702
2703 const MachineFunction &MF = DAG.getMachineFunction();
2704 const Function *CallerF = MF.getFunction();
2705 CallingConv::ID CallerCC = CallerF->getCallingConv();
2706 bool CCMatch = CallerCC == CalleeCC;
2707
2708 // Byval parameters hand the function a pointer directly into the stack area
2709 // we want to reuse during a tail call. Working around this *is* possible (see
2710 // X86) but less efficient and uglier in LowerCall.
2711 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2712 e = CallerF->arg_end();
2713 i != e; ++i)
2714 if (i->hasByValAttr())
2715 return false;
2716
2717 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2718 if (IsTailCallConvention(CalleeCC) && CCMatch)
2719 return true;
2720 return false;
2721 }
2722
Oliver Stannard12993dd2014-08-18 12:42:15 +00002723 // Externally-defined functions with weak linkage should not be
2724 // tail-called on AArch64 when the OS does not support dynamic
2725 // pre-emption of symbols, as the AAELF spec requires normal calls
2726 // to undefined weak functions to be replaced with a NOP or jump to the
2727 // next instruction. The behaviour of branch instructions in this
2728 // situation (as used for tail calls) is implementation-defined, so we
2729 // cannot rely on the linker replacing the tail call with a return.
2730 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2731 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002732 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002733 if (GV->hasExternalWeakLinkage() &&
2734 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002735 return false;
2736 }
2737
Tim Northover3b0846e2014-05-24 12:50:23 +00002738 // Now we search for cases where we can use a tail call without changing the
2739 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2740 // concept.
2741
2742 // I want anyone implementing a new calling convention to think long and hard
2743 // about this assert.
2744 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2745 "Unexpected variadic calling convention");
2746
2747 if (isVarArg && !Outs.empty()) {
2748 // At least two cases here: if caller is fastcc then we can't have any
2749 // memory arguments (we'd be expected to clean up the stack afterwards). If
2750 // caller is C then we could potentially use its argument area.
2751
2752 // FIXME: for now we take the most conservative of these in both cases:
2753 // disallow all variadic memory operands.
2754 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002755 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2756 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002757
2758 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002759 for (const CCValAssign &ArgLoc : ArgLocs)
2760 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002761 return false;
2762 }
2763
2764 // If the calling conventions do not match, then we'd better make sure the
2765 // results are returned in the same way as what the caller expects.
2766 if (!CCMatch) {
2767 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002768 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2769 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002770 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2771
2772 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002773 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2774 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002775 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2776
2777 if (RVLocs1.size() != RVLocs2.size())
2778 return false;
2779 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2780 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2781 return false;
2782 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2783 return false;
2784 if (RVLocs1[i].isRegLoc()) {
2785 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2786 return false;
2787 } else {
2788 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2789 return false;
2790 }
2791 }
2792 }
2793
2794 // Nothing more to check if the callee is taking no arguments
2795 if (Outs.empty())
2796 return true;
2797
2798 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002799 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2800 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002801
2802 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2803
2804 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2805
2806 // If the stack arguments for this call would fit into our own save area then
2807 // the call can be made tail.
2808 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2809}
2810
2811SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2812 SelectionDAG &DAG,
2813 MachineFrameInfo *MFI,
2814 int ClobberedFI) const {
2815 SmallVector<SDValue, 8> ArgChains;
2816 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2817 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2818
2819 // Include the original chain at the beginning of the list. When this is
2820 // used by target LowerCall hooks, this helps legalize find the
2821 // CALLSEQ_BEGIN node.
2822 ArgChains.push_back(Chain);
2823
2824 // Add a chain value for each stack argument corresponding
2825 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2826 UE = DAG.getEntryNode().getNode()->use_end();
2827 U != UE; ++U)
2828 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2829 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2830 if (FI->getIndex() < 0) {
2831 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2832 int64_t InLastByte = InFirstByte;
2833 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2834
2835 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2836 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2837 ArgChains.push_back(SDValue(L, 1));
2838 }
2839
2840 // Build a tokenfactor for all the chains.
2841 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2842}
2843
2844bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2845 bool TailCallOpt) const {
2846 return CallCC == CallingConv::Fast && TailCallOpt;
2847}
2848
2849bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2850 return CallCC == CallingConv::Fast;
2851}
2852
2853/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2854/// and add input and output parameter nodes.
2855SDValue
2856AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2857 SmallVectorImpl<SDValue> &InVals) const {
2858 SelectionDAG &DAG = CLI.DAG;
2859 SDLoc &DL = CLI.DL;
2860 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2861 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2862 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2863 SDValue Chain = CLI.Chain;
2864 SDValue Callee = CLI.Callee;
2865 bool &IsTailCall = CLI.IsTailCall;
2866 CallingConv::ID CallConv = CLI.CallConv;
2867 bool IsVarArg = CLI.IsVarArg;
2868
2869 MachineFunction &MF = DAG.getMachineFunction();
2870 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2871 bool IsThisReturn = false;
2872
2873 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2874 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2875 bool IsSibCall = false;
2876
2877 if (IsTailCall) {
2878 // Check if it's really possible to do a tail call.
2879 IsTailCall = isEligibleForTailCallOptimization(
2880 Callee, CallConv, IsVarArg, IsStructRet,
2881 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2882 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2883 report_fatal_error("failed to perform tail call elimination on a call "
2884 "site marked musttail");
2885
2886 // A sibling call is one where we're under the usual C ABI and not planning
2887 // to change that but can still do a tail call:
2888 if (!TailCallOpt && IsTailCall)
2889 IsSibCall = true;
2890
2891 if (IsTailCall)
2892 ++NumTailCalls;
2893 }
2894
2895 // Analyze operands of the call, assigning locations to each operand.
2896 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002897 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2898 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002899
2900 if (IsVarArg) {
2901 // Handle fixed and variable vector arguments differently.
2902 // Variable vector arguments always go into memory.
2903 unsigned NumArgs = Outs.size();
2904
2905 for (unsigned i = 0; i != NumArgs; ++i) {
2906 MVT ArgVT = Outs[i].VT;
2907 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2908 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2909 /*IsVarArg=*/ !Outs[i].IsFixed);
2910 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2911 assert(!Res && "Call operand has unhandled type");
2912 (void)Res;
2913 }
2914 } else {
2915 // At this point, Outs[].VT may already be promoted to i32. To correctly
2916 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2917 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2918 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2919 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2920 // LocVT.
2921 unsigned NumArgs = Outs.size();
2922 for (unsigned i = 0; i != NumArgs; ++i) {
2923 MVT ValVT = Outs[i].VT;
2924 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002925 EVT ActualVT = getValueType(DAG.getDataLayout(),
2926 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002927 /*AllowUnknown*/ true);
2928 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2929 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2930 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002931 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002932 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002933 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002934 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002935
2936 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002937 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002938 assert(!Res && "Call operand has unhandled type");
2939 (void)Res;
2940 }
2941 }
2942
2943 // Get a count of how many bytes are to be pushed on the stack.
2944 unsigned NumBytes = CCInfo.getNextStackOffset();
2945
2946 if (IsSibCall) {
2947 // Since we're not changing the ABI to make this a tail call, the memory
2948 // operands are already available in the caller's incoming argument space.
2949 NumBytes = 0;
2950 }
2951
2952 // FPDiff is the byte offset of the call's argument area from the callee's.
2953 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2954 // by this amount for a tail call. In a sibling call it must be 0 because the
2955 // caller will deallocate the entire stack and the callee still expects its
2956 // arguments to begin at SP+0. Completely unused for non-tail calls.
2957 int FPDiff = 0;
2958
2959 if (IsTailCall && !IsSibCall) {
2960 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2961
2962 // Since callee will pop argument stack as a tail call, we must keep the
2963 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002964 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002965
2966 // FPDiff will be negative if this tail call requires more space than we
2967 // would automatically have in our incoming argument space. Positive if we
2968 // can actually shrink the stack.
2969 FPDiff = NumReusableBytes - NumBytes;
2970
2971 // The stack pointer must be 16-byte aligned at all times it's used for a
2972 // memory operation, which in practice means at *all* times and in
2973 // particular across call boundaries. Therefore our own arguments started at
2974 // a 16-byte aligned SP and the delta applied for the tail call should
2975 // satisfy the same constraint.
2976 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2977 }
2978
2979 // Adjust the stack pointer for the new arguments...
2980 // These operations are automatically eliminated by the prolog/epilog pass
2981 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002982 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2983 true),
2984 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002985
Mehdi Amini44ede332015-07-09 02:09:04 +00002986 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2987 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002988
2989 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2990 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00002991 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002992
2993 // Walk the register/memloc assignments, inserting copies/loads.
2994 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2995 ++i, ++realArgIdx) {
2996 CCValAssign &VA = ArgLocs[i];
2997 SDValue Arg = OutVals[realArgIdx];
2998 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2999
3000 // Promote the value if needed.
3001 switch (VA.getLocInfo()) {
3002 default:
3003 llvm_unreachable("Unknown loc info!");
3004 case CCValAssign::Full:
3005 break;
3006 case CCValAssign::SExt:
3007 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3008 break;
3009 case CCValAssign::ZExt:
3010 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3011 break;
3012 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003013 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3014 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3015 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3016 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3017 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003018 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3019 break;
3020 case CCValAssign::BCvt:
3021 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3022 break;
3023 case CCValAssign::FPExt:
3024 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3025 break;
3026 }
3027
3028 if (VA.isRegLoc()) {
3029 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3030 assert(VA.getLocVT() == MVT::i64 &&
3031 "unexpected calling convention register assignment");
3032 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3033 "unexpected use of 'returned'");
3034 IsThisReturn = true;
3035 }
3036 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3037 } else {
3038 assert(VA.isMemLoc());
3039
3040 SDValue DstAddr;
3041 MachinePointerInfo DstInfo;
3042
3043 // FIXME: This works on big-endian for composite byvals, which are the
3044 // common case. It should also work for fundamental types too.
3045 uint32_t BEAlign = 0;
3046 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003047 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003048 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003049 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3050 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003051 if (OpSize < 8)
3052 BEAlign = 8 - OpSize;
3053 }
3054 unsigned LocMemOffset = VA.getLocMemOffset();
3055 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003056 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003057 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003058
3059 if (IsTailCall) {
3060 Offset = Offset + FPDiff;
3061 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3062
Mehdi Amini44ede332015-07-09 02:09:04 +00003063 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003064 DstInfo =
3065 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003066
3067 // Make sure any stack arguments overlapping with where we're storing
3068 // are loaded before this eventual operation. Otherwise they'll be
3069 // clobbered.
3070 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3071 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003072 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003073
Mehdi Amini44ede332015-07-09 02:09:04 +00003074 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003075 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3076 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003077 }
3078
3079 if (Outs[i].Flags.isByVal()) {
3080 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003081 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003082 SDValue Cpy = DAG.getMemcpy(
3083 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003084 /*isVol = */ false, /*AlwaysInline = */ false,
3085 /*isTailCall = */ false,
3086 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003087
3088 MemOpChains.push_back(Cpy);
3089 } else {
3090 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3091 // promoted to a legal register type i32, we should truncate Arg back to
3092 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003093 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3094 VA.getValVT() == MVT::i16)
3095 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003096
3097 SDValue Store =
3098 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3099 MemOpChains.push_back(Store);
3100 }
3101 }
3102 }
3103
3104 if (!MemOpChains.empty())
3105 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3106
3107 // Build a sequence of copy-to-reg nodes chained together with token chain
3108 // and flag operands which copy the outgoing args into the appropriate regs.
3109 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003110 for (auto &RegToPass : RegsToPass) {
3111 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3112 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003113 InFlag = Chain.getValue(1);
3114 }
3115
3116 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3117 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3118 // node so that legalize doesn't hack it.
3119 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3120 Subtarget->isTargetMachO()) {
3121 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3122 const GlobalValue *GV = G->getGlobal();
3123 bool InternalLinkage = GV->hasInternalLinkage();
3124 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003125 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003126 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003127 Callee =
3128 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3129 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003130 }
3131 } else if (ExternalSymbolSDNode *S =
3132 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3133 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003134 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3135 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003136 }
3137 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3138 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003139 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003140 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3141 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003142 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003143 }
3144
3145 // We don't usually want to end the call-sequence here because we would tidy
3146 // the frame up *after* the call, however in the ABI-changing tail-call case
3147 // we've carefully laid out the parameters so that when sp is reset they'll be
3148 // in the correct location.
3149 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003150 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3151 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003152 InFlag = Chain.getValue(1);
3153 }
3154
3155 std::vector<SDValue> Ops;
3156 Ops.push_back(Chain);
3157 Ops.push_back(Callee);
3158
3159 if (IsTailCall) {
3160 // Each tail call may have to adjust the stack by a different amount, so
3161 // this information must travel along with the operation for eventual
3162 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003163 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003164 }
3165
3166 // Add argument registers to the end of the list so that they are known live
3167 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003168 for (auto &RegToPass : RegsToPass)
3169 Ops.push_back(DAG.getRegister(RegToPass.first,
3170 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003171
3172 // Add a register mask operand representing the call-preserved registers.
3173 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003174 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003175 if (IsThisReturn) {
3176 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003177 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003178 if (!Mask) {
3179 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003180 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003181 }
3182 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003183 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003184
3185 assert(Mask && "Missing call preserved mask for calling convention");
3186 Ops.push_back(DAG.getRegisterMask(Mask));
3187
3188 if (InFlag.getNode())
3189 Ops.push_back(InFlag);
3190
3191 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3192
3193 // If we're doing a tall call, use a TC_RETURN here rather than an
3194 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003195 if (IsTailCall) {
3196 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003197 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003198 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003199
3200 // Returns a chain and a flag for retval copy to use.
3201 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3202 InFlag = Chain.getValue(1);
3203
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003204 uint64_t CalleePopBytes =
3205 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003206
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003207 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3208 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003209 InFlag, DL);
3210 if (!Ins.empty())
3211 InFlag = Chain.getValue(1);
3212
3213 // Handle result values, copying them out of physregs into vregs that we
3214 // return.
3215 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3216 InVals, IsThisReturn,
3217 IsThisReturn ? OutVals[0] : SDValue());
3218}
3219
3220bool AArch64TargetLowering::CanLowerReturn(
3221 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3222 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3223 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3224 ? RetCC_AArch64_WebKit_JS
3225 : RetCC_AArch64_AAPCS;
3226 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003227 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003228 return CCInfo.CheckReturn(Outs, RetCC);
3229}
3230
3231SDValue
3232AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3233 bool isVarArg,
3234 const SmallVectorImpl<ISD::OutputArg> &Outs,
3235 const SmallVectorImpl<SDValue> &OutVals,
3236 SDLoc DL, SelectionDAG &DAG) const {
3237 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3238 ? RetCC_AArch64_WebKit_JS
3239 : RetCC_AArch64_AAPCS;
3240 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003241 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3242 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003243 CCInfo.AnalyzeReturn(Outs, RetCC);
3244
3245 // Copy the result values into the output registers.
3246 SDValue Flag;
3247 SmallVector<SDValue, 4> RetOps(1, Chain);
3248 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3249 ++i, ++realRVLocIdx) {
3250 CCValAssign &VA = RVLocs[i];
3251 assert(VA.isRegLoc() && "Can only return in registers!");
3252 SDValue Arg = OutVals[realRVLocIdx];
3253
3254 switch (VA.getLocInfo()) {
3255 default:
3256 llvm_unreachable("Unknown loc info!");
3257 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003258 if (Outs[i].ArgVT == MVT::i1) {
3259 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3260 // value. This is strictly redundant on Darwin (which uses "zeroext
3261 // i1"), but will be optimised out before ISel.
3262 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3263 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3264 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003265 break;
3266 case CCValAssign::BCvt:
3267 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3268 break;
3269 }
3270
3271 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3272 Flag = Chain.getValue(1);
3273 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3274 }
Manman Rencbe4f942015-12-16 21:04:19 +00003275 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3276 const MCPhysReg *I =
3277 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3278 if (I) {
3279 for (; *I; ++I) {
3280 if (AArch64::GPR64RegClass.contains(*I))
3281 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3282 else if (AArch64::FPR64RegClass.contains(*I))
3283 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3284 else
3285 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3286 }
3287 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003288
3289 RetOps[0] = Chain; // Update chain.
3290
3291 // Add the flag if we have it.
3292 if (Flag.getNode())
3293 RetOps.push_back(Flag);
3294
3295 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3296}
3297
3298//===----------------------------------------------------------------------===//
3299// Other Lowering Code
3300//===----------------------------------------------------------------------===//
3301
3302SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3303 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003304 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003305 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003306 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3307 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003308 unsigned char OpFlags =
3309 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3310
3311 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3312 "unexpected offset in global node");
3313
3314 // This also catched the large code model case for Darwin.
3315 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3316 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3317 // FIXME: Once remat is capable of dealing with instructions with register
3318 // operands, expand this into two nodes instead of using a wrapper node.
3319 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3320 }
3321
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003322 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3323 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3324 "use of MO_CONSTPOOL only supported on small model");
3325 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3326 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3327 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3328 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3329 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003330 SDValue GlobalAddr = DAG.getLoad(
3331 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3332 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3333 /*isVolatile=*/false,
3334 /*isNonTemporal=*/true,
3335 /*isInvariant=*/true, 8);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003336 if (GN->getOffset() != 0)
3337 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003338 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003339 return GlobalAddr;
3340 }
3341
Tim Northover3b0846e2014-05-24 12:50:23 +00003342 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3343 const unsigned char MO_NC = AArch64II::MO_NC;
3344 return DAG.getNode(
3345 AArch64ISD::WrapperLarge, DL, PtrVT,
3346 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3347 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3348 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3349 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3350 } else {
3351 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3352 // the only correct model on Darwin.
3353 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3354 OpFlags | AArch64II::MO_PAGE);
3355 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3356 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3357
3358 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3359 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3360 }
3361}
3362
3363/// \brief Convert a TLS address reference into the correct sequence of loads
3364/// and calls to compute the variable's address (for Darwin, currently) and
3365/// return an SDValue containing the final node.
3366
3367/// Darwin only has one TLS scheme which must be capable of dealing with the
3368/// fully general situation, in the worst case. This means:
3369/// + "extern __thread" declaration.
3370/// + Defined in a possibly unknown dynamic library.
3371///
3372/// The general system is that each __thread variable has a [3 x i64] descriptor
3373/// which contains information used by the runtime to calculate the address. The
3374/// only part of this the compiler needs to know about is the first xword, which
3375/// contains a function pointer that must be called with the address of the
3376/// entire descriptor in "x0".
3377///
3378/// Since this descriptor may be in a different unit, in general even the
3379/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3380/// is:
3381/// adrp x0, _var@TLVPPAGE
3382/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3383/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3384/// ; the function pointer
3385/// blr x1 ; Uses descriptor address in x0
3386/// ; Address of _var is now in x0.
3387///
3388/// If the address of _var's descriptor *is* known to the linker, then it can
3389/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3390/// a slight efficiency gain.
3391SDValue
3392AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3393 SelectionDAG &DAG) const {
3394 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3395
3396 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003397 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003398 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3399
3400 SDValue TLVPAddr =
3401 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3402 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3403
3404 // The first entry in the descriptor is a function pointer that we must call
3405 // to obtain the address of the variable.
3406 SDValue Chain = DAG.getEntryNode();
3407 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003408 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3409 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3410 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003411 Chain = FuncTLVGet.getValue(1);
3412
3413 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3414 MFI->setAdjustsStack(true);
3415
3416 // TLS calls preserve all registers except those that absolutely must be
3417 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3418 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003419 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003420 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003421
3422 // Finally, we can make the call. This is just a degenerate version of a
3423 // normal AArch64 call node: x0 takes the address of the descriptor, and
3424 // returns the address of the variable in this thread.
3425 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3426 Chain =
3427 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3428 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3429 DAG.getRegisterMask(Mask), Chain.getValue(1));
3430 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3431}
3432
3433/// When accessing thread-local variables under either the general-dynamic or
3434/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3435/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003436/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003437///
Kristof Beylsaea84612015-03-04 09:12:08 +00003438/// The sequence is:
3439/// adrp x0, :tlsdesc:var
3440/// ldr x1, [x0, #:tlsdesc_lo12:var]
3441/// add x0, x0, #:tlsdesc_lo12:var
3442/// .tlsdesccall var
3443/// blr x1
3444/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003445///
Kristof Beylsaea84612015-03-04 09:12:08 +00003446/// The above sequence must be produced unscheduled, to enable the linker to
3447/// optimize/relax this sequence.
3448/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3449/// above sequence, and expanded really late in the compilation flow, to ensure
3450/// the sequence is produced as per above.
3451SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3452 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003453 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003454
Kristof Beylsaea84612015-03-04 09:12:08 +00003455 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003456 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003457
3458 SmallVector<SDValue, 2> Ops;
3459 Ops.push_back(Chain);
3460 Ops.push_back(SymAddr);
3461
3462 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3463 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003464
3465 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3466}
3467
3468SDValue
3469AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3470 SelectionDAG &DAG) const {
3471 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3472 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3473 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003474 // Different choices can be made for the maximum size of the TLS area for a
3475 // module. For the small address model, the default TLS size is 16MiB and the
3476 // maximum TLS size is 4GiB.
3477 // FIXME: add -mtls-size command line option and make it control the 16MiB
3478 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003479 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3480
3481 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003482
3483 if (DAG.getTarget().Options.EmulatedTLS)
3484 return LowerToTLSEmulatedModel(GA, DAG);
3485
Kristof Beylsaea84612015-03-04 09:12:08 +00003486 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3487 if (Model == TLSModel::LocalDynamic)
3488 Model = TLSModel::GeneralDynamic;
3489 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003490
3491 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003492 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003493 SDLoc DL(Op);
3494 const GlobalValue *GV = GA->getGlobal();
3495
3496 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3497
3498 if (Model == TLSModel::LocalExec) {
3499 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003500 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003501 SDValue LoVar = DAG.getTargetGlobalAddress(
3502 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003503 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003504
Kristof Beylsaea84612015-03-04 09:12:08 +00003505 SDValue TPWithOff_lo =
3506 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003507 HiVar,
3508 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003509 0);
3510 SDValue TPWithOff =
3511 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003512 LoVar,
3513 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003514 0);
3515 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003516 } else if (Model == TLSModel::InitialExec) {
3517 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3518 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3519 } else if (Model == TLSModel::LocalDynamic) {
3520 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3521 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3522 // the beginning of the module's TLS region, followed by a DTPREL offset
3523 // calculation.
3524
3525 // These accesses will need deduplicating if there's more than one.
3526 AArch64FunctionInfo *MFI =
3527 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3528 MFI->incNumLocalDynamicTLSAccesses();
3529
Tim Northover3b0846e2014-05-24 12:50:23 +00003530 // The call needs a relocation too for linker relaxation. It doesn't make
3531 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3532 // the address.
3533 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3534 AArch64II::MO_TLS);
3535
3536 // Now we can calculate the offset from TPIDR_EL0 to this module's
3537 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003538 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003539
3540 // Now use :dtprel_whatever: operations to calculate this variable's offset
3541 // in its thread-storage area.
3542 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003543 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003544 SDValue LoVar = DAG.getTargetGlobalAddress(
3545 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003546 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3547
Kristof Beylsaea84612015-03-04 09:12:08 +00003548 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003549 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003550 0);
3551 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003552 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003553 0);
3554 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003555 // The call needs a relocation too for linker relaxation. It doesn't make
3556 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3557 // the address.
3558 SDValue SymAddr =
3559 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3560
3561 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003562 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003563 } else
3564 llvm_unreachable("Unsupported ELF TLS access model");
3565
3566 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3567}
3568
3569SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3570 SelectionDAG &DAG) const {
3571 if (Subtarget->isTargetDarwin())
3572 return LowerDarwinGlobalTLSAddress(Op, DAG);
3573 else if (Subtarget->isTargetELF())
3574 return LowerELFGlobalTLSAddress(Op, DAG);
3575
3576 llvm_unreachable("Unexpected platform trying to use TLS");
3577}
3578SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3579 SDValue Chain = Op.getOperand(0);
3580 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3581 SDValue LHS = Op.getOperand(2);
3582 SDValue RHS = Op.getOperand(3);
3583 SDValue Dest = Op.getOperand(4);
3584 SDLoc dl(Op);
3585
3586 // Handle f128 first, since lowering it will result in comparing the return
3587 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3588 // is expecting to deal with.
3589 if (LHS.getValueType() == MVT::f128) {
3590 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3591
3592 // If softenSetCCOperands returned a scalar, we need to compare the result
3593 // against zero to select between true and false values.
3594 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003595 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003596 CC = ISD::SETNE;
3597 }
3598 }
3599
3600 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3601 // instruction.
3602 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003603 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003604 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3605 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3606 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3607 "Unexpected condition code.");
3608 // Only lower legal XALUO ops.
3609 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3610 return SDValue();
3611
3612 // The actual operation with overflow check.
3613 AArch64CC::CondCode OFCC;
3614 SDValue Value, Overflow;
3615 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3616
3617 if (CC == ISD::SETNE)
3618 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003619 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003620
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003621 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3622 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003623 }
3624
3625 if (LHS.getValueType().isInteger()) {
3626 assert((LHS.getValueType() == RHS.getValueType()) &&
3627 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3628
3629 // If the RHS of the comparison is zero, we can potentially fold this
3630 // to a specialized branch.
3631 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3632 if (RHSC && RHSC->getZExtValue() == 0) {
3633 if (CC == ISD::SETEQ) {
3634 // See if we can use a TBZ to fold in an AND as well.
3635 // TBZ has a smaller branch displacement than CBZ. If the offset is
3636 // out of bounds, a late MI-layer pass rewrites branches.
3637 // 403.gcc is an example that hits this case.
3638 if (LHS.getOpcode() == ISD::AND &&
3639 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3640 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3641 SDValue Test = LHS.getOperand(0);
3642 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003643 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003644 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3645 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003646 }
3647
3648 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3649 } else if (CC == ISD::SETNE) {
3650 // See if we can use a TBZ to fold in an AND as well.
3651 // TBZ has a smaller branch displacement than CBZ. If the offset is
3652 // out of bounds, a late MI-layer pass rewrites branches.
3653 // 403.gcc is an example that hits this case.
3654 if (LHS.getOpcode() == ISD::AND &&
3655 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3656 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3657 SDValue Test = LHS.getOperand(0);
3658 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003659 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003660 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3661 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003662 }
3663
3664 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003665 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3666 // Don't combine AND since emitComparison converts the AND to an ANDS
3667 // (a.k.a. TST) and the test in the test bit and branch instruction
3668 // becomes redundant. This would also increase register pressure.
3669 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3670 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003671 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003672 }
3673 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003674 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3675 LHS.getOpcode() != ISD::AND) {
3676 // Don't combine AND since emitComparison converts the AND to an ANDS
3677 // (a.k.a. TST) and the test in the test bit and branch instruction
3678 // becomes redundant. This would also increase register pressure.
3679 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3680 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003681 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003682 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003683
3684 SDValue CCVal;
3685 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3686 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3687 Cmp);
3688 }
3689
3690 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3691
3692 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3693 // clean. Some of them require two branches to implement.
3694 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3695 AArch64CC::CondCode CC1, CC2;
3696 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003697 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003698 SDValue BR1 =
3699 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3700 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003701 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003702 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3703 Cmp);
3704 }
3705
3706 return BR1;
3707}
3708
3709SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3710 SelectionDAG &DAG) const {
3711 EVT VT = Op.getValueType();
3712 SDLoc DL(Op);
3713
3714 SDValue In1 = Op.getOperand(0);
3715 SDValue In2 = Op.getOperand(1);
3716 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003717
3718 if (SrcVT.bitsLT(VT))
3719 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3720 else if (SrcVT.bitsGT(VT))
3721 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003722
3723 EVT VecVT;
3724 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003725 uint64_t EltMask;
3726 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003727 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3728 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003729 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003730 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003731
3732 if (!VT.isVector()) {
3733 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3734 DAG.getUNDEF(VecVT), In1);
3735 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3736 DAG.getUNDEF(VecVT), In2);
3737 } else {
3738 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3739 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3740 }
3741 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3742 EltVT = MVT::i64;
3743 VecVT = MVT::v2i64;
3744
Eric Christopher572e03a2015-06-19 01:53:21 +00003745 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003746 // immediate moves cannot materialize that in a single instruction for
3747 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003748 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003749
3750 if (!VT.isVector()) {
3751 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3752 DAG.getUNDEF(VecVT), In1);
3753 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3754 DAG.getUNDEF(VecVT), In2);
3755 } else {
3756 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3757 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3758 }
3759 } else {
3760 llvm_unreachable("Invalid type for copysign!");
3761 }
3762
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003763 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003764
3765 // If we couldn't materialize the mask above, then the mask vector will be
3766 // the zero vector, and we need to negate it here.
3767 if (VT == MVT::f64 || VT == MVT::v2f64) {
3768 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3769 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3770 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3771 }
3772
3773 SDValue Sel =
3774 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3775
3776 if (VT == MVT::f32)
3777 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3778 else if (VT == MVT::f64)
3779 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3780 else
3781 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3782}
3783
3784SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003785 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3786 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003787 return SDValue();
3788
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003789 if (!Subtarget->hasNEON())
3790 return SDValue();
3791
Tim Northover3b0846e2014-05-24 12:50:23 +00003792 // While there is no integer popcount instruction, it can
3793 // be more efficiently lowered to the following sequence that uses
3794 // AdvSIMD registers/instructions as long as the copies to/from
3795 // the AdvSIMD registers are cheap.
3796 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3797 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3798 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3799 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3800 SDValue Val = Op.getOperand(0);
3801 SDLoc DL(Op);
3802 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003803
Hao Liue0335d72015-01-30 02:13:53 +00003804 if (VT == MVT::i32)
3805 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3806 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003807
Hao Liue0335d72015-01-30 02:13:53 +00003808 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003809 SDValue UaddLV = DAG.getNode(
3810 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003811 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003812
3813 if (VT == MVT::i64)
3814 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3815 return UaddLV;
3816}
3817
3818SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3819
3820 if (Op.getValueType().isVector())
3821 return LowerVSETCC(Op, DAG);
3822
3823 SDValue LHS = Op.getOperand(0);
3824 SDValue RHS = Op.getOperand(1);
3825 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3826 SDLoc dl(Op);
3827
3828 // We chose ZeroOrOneBooleanContents, so use zero and one.
3829 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003830 SDValue TVal = DAG.getConstant(1, dl, VT);
3831 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003832
3833 // Handle f128 first, since one possible outcome is a normal integer
3834 // comparison which gets picked up by the next if statement.
3835 if (LHS.getValueType() == MVT::f128) {
3836 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3837
3838 // If softenSetCCOperands returned a scalar, use it.
3839 if (!RHS.getNode()) {
3840 assert(LHS.getValueType() == Op.getValueType() &&
3841 "Unexpected setcc expansion!");
3842 return LHS;
3843 }
3844 }
3845
3846 if (LHS.getValueType().isInteger()) {
3847 SDValue CCVal;
3848 SDValue Cmp =
3849 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3850
3851 // Note that we inverted the condition above, so we reverse the order of
3852 // the true and false operands here. This will allow the setcc to be
3853 // matched to a single CSINC instruction.
3854 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3855 }
3856
3857 // Now we know we're dealing with FP values.
3858 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3859
3860 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3861 // and do the comparison.
3862 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3863
3864 AArch64CC::CondCode CC1, CC2;
3865 changeFPCCToAArch64CC(CC, CC1, CC2);
3866 if (CC2 == AArch64CC::AL) {
3867 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003868 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003869
3870 // Note that we inverted the condition above, so we reverse the order of
3871 // the true and false operands here. This will allow the setcc to be
3872 // matched to a single CSINC instruction.
3873 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3874 } else {
3875 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3876 // totally clean. Some of them require two CSELs to implement. As is in
3877 // this case, we emit the first CSEL and then emit a second using the output
3878 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3879
3880 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003881 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003882 SDValue CS1 =
3883 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3884
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003885 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003886 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3887 }
3888}
3889
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003890SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3891 SDValue RHS, SDValue TVal,
3892 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003893 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003894 // Handle f128 first, because it will result in a comparison of some RTLIB
3895 // call result against zero.
3896 if (LHS.getValueType() == MVT::f128) {
3897 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3898
3899 // If softenSetCCOperands returned a scalar, we need to compare the result
3900 // against zero to select between true and false values.
3901 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003902 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003903 CC = ISD::SETNE;
3904 }
3905 }
3906
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003907 // Also handle f16, for which we need to do a f32 comparison.
3908 if (LHS.getValueType() == MVT::f16) {
3909 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3910 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3911 }
3912
3913 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003914 if (LHS.getValueType().isInteger()) {
3915 assert((LHS.getValueType() == RHS.getValueType()) &&
3916 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3917
3918 unsigned Opcode = AArch64ISD::CSEL;
3919
3920 // If both the TVal and the FVal are constants, see if we can swap them in
3921 // order to for a CSINV or CSINC out of them.
3922 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3923 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3924
3925 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3926 std::swap(TVal, FVal);
3927 std::swap(CTVal, CFVal);
3928 CC = ISD::getSetCCInverse(CC, true);
3929 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3930 std::swap(TVal, FVal);
3931 std::swap(CTVal, CFVal);
3932 CC = ISD::getSetCCInverse(CC, true);
3933 } else if (TVal.getOpcode() == ISD::XOR) {
3934 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3935 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003936 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003937 std::swap(TVal, FVal);
3938 std::swap(CTVal, CFVal);
3939 CC = ISD::getSetCCInverse(CC, true);
3940 }
3941 } else if (TVal.getOpcode() == ISD::SUB) {
3942 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3943 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003944 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003945 std::swap(TVal, FVal);
3946 std::swap(CTVal, CFVal);
3947 CC = ISD::getSetCCInverse(CC, true);
3948 }
3949 } else if (CTVal && CFVal) {
3950 const int64_t TrueVal = CTVal->getSExtValue();
3951 const int64_t FalseVal = CFVal->getSExtValue();
3952 bool Swap = false;
3953
3954 // If both TVal and FVal are constants, see if FVal is the
3955 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3956 // instead of a CSEL in that case.
3957 if (TrueVal == ~FalseVal) {
3958 Opcode = AArch64ISD::CSINV;
3959 } else if (TrueVal == -FalseVal) {
3960 Opcode = AArch64ISD::CSNEG;
3961 } else if (TVal.getValueType() == MVT::i32) {
3962 // If our operands are only 32-bit wide, make sure we use 32-bit
3963 // arithmetic for the check whether we can use CSINC. This ensures that
3964 // the addition in the check will wrap around properly in case there is
3965 // an overflow (which would not be the case if we do the check with
3966 // 64-bit arithmetic).
3967 const uint32_t TrueVal32 = CTVal->getZExtValue();
3968 const uint32_t FalseVal32 = CFVal->getZExtValue();
3969
3970 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3971 Opcode = AArch64ISD::CSINC;
3972
3973 if (TrueVal32 > FalseVal32) {
3974 Swap = true;
3975 }
3976 }
3977 // 64-bit check whether we can use CSINC.
3978 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3979 Opcode = AArch64ISD::CSINC;
3980
3981 if (TrueVal > FalseVal) {
3982 Swap = true;
3983 }
3984 }
3985
3986 // Swap TVal and FVal if necessary.
3987 if (Swap) {
3988 std::swap(TVal, FVal);
3989 std::swap(CTVal, CFVal);
3990 CC = ISD::getSetCCInverse(CC, true);
3991 }
3992
3993 if (Opcode != AArch64ISD::CSEL) {
3994 // Drop FVal since we can get its value by simply inverting/negating
3995 // TVal.
3996 FVal = TVal;
3997 }
3998 }
3999
4000 SDValue CCVal;
4001 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4002
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004003 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004004 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4005 }
4006
4007 // Now we know we're dealing with FP values.
4008 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4009 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004010 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004011 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4012
4013 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4014 // clean. Some of them require two CSELs to implement.
4015 AArch64CC::CondCode CC1, CC2;
4016 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004017 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004018 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4019
4020 // If we need a second CSEL, emit it, using the output of the first as the
4021 // RHS. We're effectively OR'ing the two CC's together.
4022 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004023 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004024 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4025 }
4026
4027 // Otherwise, return the output of the first CSEL.
4028 return CS1;
4029}
4030
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004031SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4032 SelectionDAG &DAG) const {
4033 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4034 SDValue LHS = Op.getOperand(0);
4035 SDValue RHS = Op.getOperand(1);
4036 SDValue TVal = Op.getOperand(2);
4037 SDValue FVal = Op.getOperand(3);
4038 SDLoc DL(Op);
4039 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4040}
4041
4042SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4043 SelectionDAG &DAG) const {
4044 SDValue CCVal = Op->getOperand(0);
4045 SDValue TVal = Op->getOperand(1);
4046 SDValue FVal = Op->getOperand(2);
4047 SDLoc DL(Op);
4048
4049 unsigned Opc = CCVal.getOpcode();
4050 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4051 // instruction.
4052 if (CCVal.getResNo() == 1 &&
4053 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4054 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4055 // Only lower legal XALUO ops.
4056 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4057 return SDValue();
4058
4059 AArch64CC::CondCode OFCC;
4060 SDValue Value, Overflow;
4061 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004062 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004063
4064 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4065 CCVal, Overflow);
4066 }
4067
4068 // Lower it the same way as we would lower a SELECT_CC node.
4069 ISD::CondCode CC;
4070 SDValue LHS, RHS;
4071 if (CCVal.getOpcode() == ISD::SETCC) {
4072 LHS = CCVal.getOperand(0);
4073 RHS = CCVal.getOperand(1);
4074 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4075 } else {
4076 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004077 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004078 CC = ISD::SETNE;
4079 }
4080 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4081}
4082
Tim Northover3b0846e2014-05-24 12:50:23 +00004083SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4084 SelectionDAG &DAG) const {
4085 // Jump table entries as PC relative offsets. No additional tweaking
4086 // is necessary here. Just get the address of the jump table.
4087 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004088 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004089 SDLoc DL(Op);
4090
4091 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4092 !Subtarget->isTargetMachO()) {
4093 const unsigned char MO_NC = AArch64II::MO_NC;
4094 return DAG.getNode(
4095 AArch64ISD::WrapperLarge, DL, PtrVT,
4096 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4097 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4098 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4099 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4100 AArch64II::MO_G0 | MO_NC));
4101 }
4102
4103 SDValue Hi =
4104 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4105 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4106 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4107 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4108 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4109}
4110
4111SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4112 SelectionDAG &DAG) const {
4113 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004114 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004115 SDLoc DL(Op);
4116
4117 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4118 // Use the GOT for the large code model on iOS.
4119 if (Subtarget->isTargetMachO()) {
4120 SDValue GotAddr = DAG.getTargetConstantPool(
4121 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4122 AArch64II::MO_GOT);
4123 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4124 }
4125
4126 const unsigned char MO_NC = AArch64II::MO_NC;
4127 return DAG.getNode(
4128 AArch64ISD::WrapperLarge, DL, PtrVT,
4129 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4130 CP->getOffset(), AArch64II::MO_G3),
4131 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4132 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4133 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4134 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4135 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4136 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4137 } else {
4138 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4139 // ELF, the only valid one on Darwin.
4140 SDValue Hi =
4141 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4142 CP->getOffset(), AArch64II::MO_PAGE);
4143 SDValue Lo = DAG.getTargetConstantPool(
4144 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4145 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4146
4147 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4148 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4149 }
4150}
4151
4152SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4153 SelectionDAG &DAG) const {
4154 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004155 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004156 SDLoc DL(Op);
4157 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4158 !Subtarget->isTargetMachO()) {
4159 const unsigned char MO_NC = AArch64II::MO_NC;
4160 return DAG.getNode(
4161 AArch64ISD::WrapperLarge, DL, PtrVT,
4162 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4163 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4164 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4165 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4166 } else {
4167 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4168 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4169 AArch64II::MO_NC);
4170 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4171 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4172 }
4173}
4174
4175SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4176 SelectionDAG &DAG) const {
4177 AArch64FunctionInfo *FuncInfo =
4178 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4179
4180 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004181 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4182 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004183 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4184 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4185 MachinePointerInfo(SV), false, false, 0);
4186}
4187
4188SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4189 SelectionDAG &DAG) const {
4190 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4191 // Standard, section B.3.
4192 MachineFunction &MF = DAG.getMachineFunction();
4193 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004194 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004195 SDLoc DL(Op);
4196
4197 SDValue Chain = Op.getOperand(0);
4198 SDValue VAList = Op.getOperand(1);
4199 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4200 SmallVector<SDValue, 4> MemOps;
4201
4202 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004203 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004204 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4205 MachinePointerInfo(SV), false, false, 8));
4206
4207 // void *__gr_top at offset 8
4208 int GPRSize = FuncInfo->getVarArgsGPRSize();
4209 if (GPRSize > 0) {
4210 SDValue GRTop, GRTopAddr;
4211
Mehdi Amini44ede332015-07-09 02:09:04 +00004212 GRTopAddr =
4213 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004214
Mehdi Amini44ede332015-07-09 02:09:04 +00004215 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4216 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4217 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004218
4219 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4220 MachinePointerInfo(SV, 8), false, false, 8));
4221 }
4222
4223 // void *__vr_top at offset 16
4224 int FPRSize = FuncInfo->getVarArgsFPRSize();
4225 if (FPRSize > 0) {
4226 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004227 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4228 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004229
Mehdi Amini44ede332015-07-09 02:09:04 +00004230 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4231 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4232 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004233
4234 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4235 MachinePointerInfo(SV, 16), false, false, 8));
4236 }
4237
4238 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004239 SDValue GROffsAddr =
4240 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004241 MemOps.push_back(DAG.getStore(Chain, DL,
4242 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004243 GROffsAddr, MachinePointerInfo(SV, 24), false,
4244 false, 4));
4245
4246 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004247 SDValue VROffsAddr =
4248 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004249 MemOps.push_back(DAG.getStore(Chain, DL,
4250 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004251 VROffsAddr, MachinePointerInfo(SV, 28), false,
4252 false, 4));
4253
4254 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4255}
4256
4257SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4258 SelectionDAG &DAG) const {
4259 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4260 : LowerAAPCS_VASTART(Op, DAG);
4261}
4262
4263SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4264 SelectionDAG &DAG) const {
4265 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4266 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004267 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004268 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4269 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4270 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4271
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004272 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4273 Op.getOperand(2),
4274 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004275 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004276 MachinePointerInfo(SrcSV));
4277}
4278
4279SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4280 assert(Subtarget->isTargetDarwin() &&
4281 "automatic va_arg instruction only works on Darwin");
4282
4283 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4284 EVT VT = Op.getValueType();
4285 SDLoc DL(Op);
4286 SDValue Chain = Op.getOperand(0);
4287 SDValue Addr = Op.getOperand(1);
4288 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004289 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004290
Mehdi Amini44ede332015-07-09 02:09:04 +00004291 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4292 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004293 Chain = VAList.getValue(1);
4294
4295 if (Align > 8) {
4296 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004297 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4298 DAG.getConstant(Align - 1, DL, PtrVT));
4299 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4300 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004301 }
4302
4303 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004304 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004305
4306 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4307 // up to 64 bits. At the very least, we have to increase the striding of the
4308 // vaargs list to match this, and for FP values we need to introduce
4309 // FP_ROUND nodes as well.
4310 if (VT.isInteger() && !VT.isVector())
4311 ArgSize = 8;
4312 bool NeedFPTrunc = false;
4313 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4314 ArgSize = 8;
4315 NeedFPTrunc = true;
4316 }
4317
4318 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004319 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4320 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004321 // Store the incremented VAList to the legalized pointer
4322 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4323 false, false, 0);
4324
4325 // Load the actual argument out of the pointer VAList
4326 if (NeedFPTrunc) {
4327 // Load the value as an f64.
4328 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4329 MachinePointerInfo(), false, false, false, 0);
4330 // Round the value down to an f32.
4331 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004332 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004333 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4334 // Merge the rounded value with the chain output of the load.
4335 return DAG.getMergeValues(Ops, DL);
4336 }
4337
4338 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4339 false, false, 0);
4340}
4341
4342SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4343 SelectionDAG &DAG) const {
4344 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4345 MFI->setFrameAddressIsTaken(true);
4346
4347 EVT VT = Op.getValueType();
4348 SDLoc DL(Op);
4349 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4350 SDValue FrameAddr =
4351 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4352 while (Depth--)
4353 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4354 MachinePointerInfo(), false, false, false, 0);
4355 return FrameAddr;
4356}
4357
4358// FIXME? Maybe this could be a TableGen attribute on some registers and
4359// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004360unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4361 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004362 unsigned Reg = StringSwitch<unsigned>(RegName)
4363 .Case("sp", AArch64::SP)
4364 .Default(0);
4365 if (Reg)
4366 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004367 report_fatal_error(Twine("Invalid register name \""
4368 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004369}
4370
4371SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4372 SelectionDAG &DAG) const {
4373 MachineFunction &MF = DAG.getMachineFunction();
4374 MachineFrameInfo *MFI = MF.getFrameInfo();
4375 MFI->setReturnAddressIsTaken(true);
4376
4377 EVT VT = Op.getValueType();
4378 SDLoc DL(Op);
4379 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4380 if (Depth) {
4381 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004382 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004383 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4384 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4385 MachinePointerInfo(), false, false, false, 0);
4386 }
4387
4388 // Return LR, which contains the return address. Mark it an implicit live-in.
4389 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4390 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4391}
4392
4393/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4394/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4395SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4396 SelectionDAG &DAG) const {
4397 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4398 EVT VT = Op.getValueType();
4399 unsigned VTBits = VT.getSizeInBits();
4400 SDLoc dl(Op);
4401 SDValue ShOpLo = Op.getOperand(0);
4402 SDValue ShOpHi = Op.getOperand(1);
4403 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004404 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4405
4406 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4407
4408 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004409 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004410 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4411
4412 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4413 // is "undef". We wanted 0, so CSEL it directly.
4414 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4415 ISD::SETEQ, dl, DAG);
4416 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4417 HiBitsForLo =
4418 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4419 HiBitsForLo, CCVal, Cmp);
4420
Tim Northover3b0846e2014-05-24 12:50:23 +00004421 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004422 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004423
Tim Northoverf3be9d52015-12-02 00:33:54 +00004424 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4425 SDValue LoForNormalShift =
4426 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004427
Tim Northoverf3be9d52015-12-02 00:33:54 +00004428 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4429 dl, DAG);
4430 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4431 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4432 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4433 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004434
4435 // AArch64 shifts larger than the register width are wrapped rather than
4436 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004437 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4438 SDValue HiForBigShift =
4439 Opc == ISD::SRA
4440 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4441 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4442 : DAG.getConstant(0, dl, VT);
4443 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4444 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004445
4446 SDValue Ops[2] = { Lo, Hi };
4447 return DAG.getMergeValues(Ops, dl);
4448}
4449
Tim Northoverf3be9d52015-12-02 00:33:54 +00004450
Tim Northover3b0846e2014-05-24 12:50:23 +00004451/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4452/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4453SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004454 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004455 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4456 EVT VT = Op.getValueType();
4457 unsigned VTBits = VT.getSizeInBits();
4458 SDLoc dl(Op);
4459 SDValue ShOpLo = Op.getOperand(0);
4460 SDValue ShOpHi = Op.getOperand(1);
4461 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004462
4463 assert(Op.getOpcode() == ISD::SHL_PARTS);
4464 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004465 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004466 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4467
4468 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4469 // is "undef". We wanted 0, so CSEL it directly.
4470 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4471 ISD::SETEQ, dl, DAG);
4472 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4473 LoBitsForHi =
4474 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4475 LoBitsForHi, CCVal, Cmp);
4476
Tim Northover3b0846e2014-05-24 12:50:23 +00004477 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004478 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004479 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4480 SDValue HiForNormalShift =
4481 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004482
Tim Northoverf3be9d52015-12-02 00:33:54 +00004483 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004484
Tim Northoverf3be9d52015-12-02 00:33:54 +00004485 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4486 dl, DAG);
4487 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4488 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4489 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004490
4491 // AArch64 shifts of larger than register sizes are wrapped rather than
4492 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004493 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4494 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4495 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4496 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004497
4498 SDValue Ops[2] = { Lo, Hi };
4499 return DAG.getMergeValues(Ops, dl);
4500}
4501
4502bool AArch64TargetLowering::isOffsetFoldingLegal(
4503 const GlobalAddressSDNode *GA) const {
4504 // The AArch64 target doesn't support folding offsets into global addresses.
4505 return false;
4506}
4507
4508bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4509 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4510 // FIXME: We should be able to handle f128 as well with a clever lowering.
4511 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4512 return true;
4513
4514 if (VT == MVT::f64)
4515 return AArch64_AM::getFP64Imm(Imm) != -1;
4516 else if (VT == MVT::f32)
4517 return AArch64_AM::getFP32Imm(Imm) != -1;
4518 return false;
4519}
4520
4521//===----------------------------------------------------------------------===//
4522// AArch64 Optimization Hooks
4523//===----------------------------------------------------------------------===//
4524
4525//===----------------------------------------------------------------------===//
4526// AArch64 Inline Assembly Support
4527//===----------------------------------------------------------------------===//
4528
4529// Table of Constraints
4530// TODO: This is the current set of constraints supported by ARM for the
4531// compiler, not all of them may make sense, e.g. S may be difficult to support.
4532//
4533// r - A general register
4534// w - An FP/SIMD register of some size in the range v0-v31
4535// x - An FP/SIMD register of some size in the range v0-v15
4536// I - Constant that can be used with an ADD instruction
4537// J - Constant that can be used with a SUB instruction
4538// K - Constant that can be used with a 32-bit logical instruction
4539// L - Constant that can be used with a 64-bit logical instruction
4540// M - Constant that can be used as a 32-bit MOV immediate
4541// N - Constant that can be used as a 64-bit MOV immediate
4542// Q - A memory reference with base register and no offset
4543// S - A symbolic address
4544// Y - Floating point constant zero
4545// Z - Integer constant zero
4546//
4547// Note that general register operands will be output using their 64-bit x
4548// register name, whatever the size of the variable, unless the asm operand
4549// is prefixed by the %w modifier. Floating-point and SIMD register operands
4550// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4551// %q modifier.
4552
4553/// getConstraintType - Given a constraint letter, return the type of
4554/// constraint it is for this target.
4555AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004556AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004557 if (Constraint.size() == 1) {
4558 switch (Constraint[0]) {
4559 default:
4560 break;
4561 case 'z':
4562 return C_Other;
4563 case 'x':
4564 case 'w':
4565 return C_RegisterClass;
4566 // An address with a single base register. Due to the way we
4567 // currently handle addresses it is the same as 'r'.
4568 case 'Q':
4569 return C_Memory;
4570 }
4571 }
4572 return TargetLowering::getConstraintType(Constraint);
4573}
4574
4575/// Examine constraint type and operand type and determine a weight value.
4576/// This object must already have been set up with the operand type
4577/// and the current alternative constraint selected.
4578TargetLowering::ConstraintWeight
4579AArch64TargetLowering::getSingleConstraintMatchWeight(
4580 AsmOperandInfo &info, const char *constraint) const {
4581 ConstraintWeight weight = CW_Invalid;
4582 Value *CallOperandVal = info.CallOperandVal;
4583 // If we don't have a value, we can't do a match,
4584 // but allow it at the lowest weight.
4585 if (!CallOperandVal)
4586 return CW_Default;
4587 Type *type = CallOperandVal->getType();
4588 // Look at the constraint type.
4589 switch (*constraint) {
4590 default:
4591 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4592 break;
4593 case 'x':
4594 case 'w':
4595 if (type->isFloatingPointTy() || type->isVectorTy())
4596 weight = CW_Register;
4597 break;
4598 case 'z':
4599 weight = CW_Constant;
4600 break;
4601 }
4602 return weight;
4603}
4604
4605std::pair<unsigned, const TargetRegisterClass *>
4606AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004607 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004608 if (Constraint.size() == 1) {
4609 switch (Constraint[0]) {
4610 case 'r':
4611 if (VT.getSizeInBits() == 64)
4612 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4613 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4614 case 'w':
4615 if (VT == MVT::f32)
4616 return std::make_pair(0U, &AArch64::FPR32RegClass);
4617 if (VT.getSizeInBits() == 64)
4618 return std::make_pair(0U, &AArch64::FPR64RegClass);
4619 if (VT.getSizeInBits() == 128)
4620 return std::make_pair(0U, &AArch64::FPR128RegClass);
4621 break;
4622 // The instructions that this constraint is designed for can
4623 // only take 128-bit registers so just use that regclass.
4624 case 'x':
4625 if (VT.getSizeInBits() == 128)
4626 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4627 break;
4628 }
4629 }
4630 if (StringRef("{cc}").equals_lower(Constraint))
4631 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4632
4633 // Use the default implementation in TargetLowering to convert the register
4634 // constraint into a member of a register class.
4635 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004636 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004637
4638 // Not found as a standard register?
4639 if (!Res.second) {
4640 unsigned Size = Constraint.size();
4641 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4642 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004643 int RegNo;
4644 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4645 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004646 // v0 - v31 are aliases of q0 - q31.
4647 // By default we'll emit v0-v31 for this unless there's a modifier where
4648 // we'll emit the correct register as well.
4649 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4650 Res.second = &AArch64::FPR128RegClass;
4651 }
4652 }
4653 }
4654
4655 return Res;
4656}
4657
4658/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4659/// vector. If it is invalid, don't add anything to Ops.
4660void AArch64TargetLowering::LowerAsmOperandForConstraint(
4661 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4662 SelectionDAG &DAG) const {
4663 SDValue Result;
4664
4665 // Currently only support length 1 constraints.
4666 if (Constraint.length() != 1)
4667 return;
4668
4669 char ConstraintLetter = Constraint[0];
4670 switch (ConstraintLetter) {
4671 default:
4672 break;
4673
4674 // This set of constraints deal with valid constants for various instructions.
4675 // Validate and return a target constant for them if we can.
4676 case 'z': {
4677 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004678 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004679 return;
4680
4681 if (Op.getValueType() == MVT::i64)
4682 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4683 else
4684 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4685 break;
4686 }
4687
4688 case 'I':
4689 case 'J':
4690 case 'K':
4691 case 'L':
4692 case 'M':
4693 case 'N':
4694 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4695 if (!C)
4696 return;
4697
4698 // Grab the value and do some validation.
4699 uint64_t CVal = C->getZExtValue();
4700 switch (ConstraintLetter) {
4701 // The I constraint applies only to simple ADD or SUB immediate operands:
4702 // i.e. 0 to 4095 with optional shift by 12
4703 // The J constraint applies only to ADD or SUB immediates that would be
4704 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4705 // instruction [or vice versa], in other words -1 to -4095 with optional
4706 // left shift by 12.
4707 case 'I':
4708 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4709 break;
4710 return;
4711 case 'J': {
4712 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004713 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4714 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004715 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004716 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004717 return;
4718 }
4719 // The K and L constraints apply *only* to logical immediates, including
4720 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4721 // been removed and MOV should be used). So these constraints have to
4722 // distinguish between bit patterns that are valid 32-bit or 64-bit
4723 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4724 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4725 // versa.
4726 case 'K':
4727 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4728 break;
4729 return;
4730 case 'L':
4731 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4732 break;
4733 return;
4734 // The M and N constraints are a superset of K and L respectively, for use
4735 // with the MOV (immediate) alias. As well as the logical immediates they
4736 // also match 32 or 64-bit immediates that can be loaded either using a
4737 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4738 // (M) or 64-bit 0x1234000000000000 (N) etc.
4739 // As a note some of this code is liberally stolen from the asm parser.
4740 case 'M': {
4741 if (!isUInt<32>(CVal))
4742 return;
4743 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4744 break;
4745 if ((CVal & 0xFFFF) == CVal)
4746 break;
4747 if ((CVal & 0xFFFF0000ULL) == CVal)
4748 break;
4749 uint64_t NCVal = ~(uint32_t)CVal;
4750 if ((NCVal & 0xFFFFULL) == NCVal)
4751 break;
4752 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4753 break;
4754 return;
4755 }
4756 case 'N': {
4757 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4758 break;
4759 if ((CVal & 0xFFFFULL) == CVal)
4760 break;
4761 if ((CVal & 0xFFFF0000ULL) == CVal)
4762 break;
4763 if ((CVal & 0xFFFF00000000ULL) == CVal)
4764 break;
4765 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4766 break;
4767 uint64_t NCVal = ~CVal;
4768 if ((NCVal & 0xFFFFULL) == NCVal)
4769 break;
4770 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4771 break;
4772 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4773 break;
4774 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4775 break;
4776 return;
4777 }
4778 default:
4779 return;
4780 }
4781
4782 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004783 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004784 break;
4785 }
4786
4787 if (Result.getNode()) {
4788 Ops.push_back(Result);
4789 return;
4790 }
4791
4792 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4793}
4794
4795//===----------------------------------------------------------------------===//
4796// AArch64 Advanced SIMD Support
4797//===----------------------------------------------------------------------===//
4798
4799/// WidenVector - Given a value in the V64 register class, produce the
4800/// equivalent value in the V128 register class.
4801static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4802 EVT VT = V64Reg.getValueType();
4803 unsigned NarrowSize = VT.getVectorNumElements();
4804 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4805 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4806 SDLoc DL(V64Reg);
4807
4808 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004809 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004810}
4811
4812/// getExtFactor - Determine the adjustment factor for the position when
4813/// generating an "extract from vector registers" instruction.
4814static unsigned getExtFactor(SDValue &V) {
4815 EVT EltType = V.getValueType().getVectorElementType();
4816 return EltType.getSizeInBits() / 8;
4817}
4818
4819/// NarrowVector - Given a value in the V128 register class, produce the
4820/// equivalent value in the V64 register class.
4821static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4822 EVT VT = V128Reg.getValueType();
4823 unsigned WideSize = VT.getVectorNumElements();
4824 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4825 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4826 SDLoc DL(V128Reg);
4827
4828 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4829}
4830
4831// Gather data to see if the operation can be modelled as a
4832// shuffle in combination with VEXTs.
4833SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4834 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004835 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004836 SDLoc dl(Op);
4837 EVT VT = Op.getValueType();
4838 unsigned NumElts = VT.getVectorNumElements();
4839
Tim Northover7324e842014-07-24 15:39:55 +00004840 struct ShuffleSourceInfo {
4841 SDValue Vec;
4842 unsigned MinElt;
4843 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004844
Tim Northover7324e842014-07-24 15:39:55 +00004845 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4846 // be compatible with the shuffle we intend to construct. As a result
4847 // ShuffleVec will be some sliding window into the original Vec.
4848 SDValue ShuffleVec;
4849
4850 // Code should guarantee that element i in Vec starts at element "WindowBase
4851 // + i * WindowScale in ShuffleVec".
4852 int WindowBase;
4853 int WindowScale;
4854
4855 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4856 ShuffleSourceInfo(SDValue Vec)
4857 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4858 WindowScale(1) {}
4859 };
4860
4861 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4862 // node.
4863 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004864 for (unsigned i = 0; i < NumElts; ++i) {
4865 SDValue V = Op.getOperand(i);
4866 if (V.getOpcode() == ISD::UNDEF)
4867 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004868 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4869 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004870 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004871 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00004872 return SDValue();
4873 }
4874
Tim Northover7324e842014-07-24 15:39:55 +00004875 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004876 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004877 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4878 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004879 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004880
Tim Northover7324e842014-07-24 15:39:55 +00004881 // Update the minimum and maximum lane number seen.
4882 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4883 Source->MinElt = std::min(Source->MinElt, EltNo);
4884 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004885 }
4886
4887 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004888 // are involved.
4889 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004890 return SDValue();
4891
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004892 // Find out the smallest element size among result and two sources, and use
4893 // it as element size to build the shuffle_vector.
4894 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004895 for (auto &Source : Sources) {
4896 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004897 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4898 SmallestEltTy = SrcEltTy;
4899 }
4900 }
4901 unsigned ResMultiplier =
4902 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004903 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4904 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004905
Tim Northover7324e842014-07-24 15:39:55 +00004906 // If the source vector is too wide or too narrow, we may nevertheless be able
4907 // to construct a compatible shuffle either by concatenating it with UNDEF or
4908 // extracting a suitable range of elements.
4909 for (auto &Src : Sources) {
4910 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004911
Tim Northover7324e842014-07-24 15:39:55 +00004912 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004913 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004914
4915 // This stage of the search produces a source with the same element type as
4916 // the original, but with a total width matching the BUILD_VECTOR output.
4917 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00004918 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4919 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00004920
4921 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4922 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004923 // We can pad out the smaller vector for free, so if it's part of a
4924 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004925 Src.ShuffleVec =
4926 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4927 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004928 continue;
4929 }
4930
Tim Northover7324e842014-07-24 15:39:55 +00004931 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004932
James Molloyf497d552014-10-17 17:06:31 +00004933 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004934 // Span too large for a VEXT to cope
4935 return SDValue();
4936 }
4937
James Molloyf497d552014-10-17 17:06:31 +00004938 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004939 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004940 Src.ShuffleVec =
4941 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004942 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00004943 Src.WindowBase = -NumSrcElts;
4944 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004945 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00004946 Src.ShuffleVec =
4947 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004948 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004949 } else {
4950 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00004951 SDValue VEXTSrc1 =
4952 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004953 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004954 SDValue VEXTSrc2 =
4955 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004956 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004957 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4958
4959 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004960 VEXTSrc2,
4961 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004962 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004963 }
4964 }
4965
Tim Northover7324e842014-07-24 15:39:55 +00004966 // Another possible incompatibility occurs from the vector element types. We
4967 // can fix this by bitcasting the source vectors to the same type we intend
4968 // for the shuffle.
4969 for (auto &Src : Sources) {
4970 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4971 if (SrcEltTy == SmallestEltTy)
4972 continue;
4973 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4974 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4975 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4976 Src.WindowBase *= Src.WindowScale;
4977 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004978
Tim Northover7324e842014-07-24 15:39:55 +00004979 // Final sanity check before we try to actually produce a shuffle.
4980 DEBUG(
4981 for (auto Src : Sources)
4982 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4983 );
4984
4985 // The stars all align, our next step is to produce the mask for the shuffle.
4986 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4987 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004988 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004989 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00004990 if (Entry.getOpcode() == ISD::UNDEF)
4991 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00004992
Tim Northover7324e842014-07-24 15:39:55 +00004993 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4994 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4995
4996 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4997 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4998 // segment.
4999 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5000 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5001 VT.getVectorElementType().getSizeInBits());
5002 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5003
5004 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5005 // starting at the appropriate offset.
5006 int *LaneMask = &Mask[i * ResMultiplier];
5007
5008 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5009 ExtractBase += NumElts * (Src - Sources.begin());
5010 for (int j = 0; j < LanesDefined; ++j)
5011 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005012 }
5013
5014 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005015 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5016 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005017
Tim Northover7324e842014-07-24 15:39:55 +00005018 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5019 for (unsigned i = 0; i < Sources.size(); ++i)
5020 ShuffleOps[i] = Sources[i].ShuffleVec;
5021
5022 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5023 ShuffleOps[1], &Mask[0]);
5024 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005025}
5026
5027// check if an EXT instruction can handle the shuffle mask when the
5028// vector sources of the shuffle are the same.
5029static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5030 unsigned NumElts = VT.getVectorNumElements();
5031
5032 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5033 if (M[0] < 0)
5034 return false;
5035
5036 Imm = M[0];
5037
5038 // If this is a VEXT shuffle, the immediate value is the index of the first
5039 // element. The other shuffle indices must be the successive elements after
5040 // the first one.
5041 unsigned ExpectedElt = Imm;
5042 for (unsigned i = 1; i < NumElts; ++i) {
5043 // Increment the expected index. If it wraps around, just follow it
5044 // back to index zero and keep going.
5045 ++ExpectedElt;
5046 if (ExpectedElt == NumElts)
5047 ExpectedElt = 0;
5048
5049 if (M[i] < 0)
5050 continue; // ignore UNDEF indices
5051 if (ExpectedElt != static_cast<unsigned>(M[i]))
5052 return false;
5053 }
5054
5055 return true;
5056}
5057
5058// check if an EXT instruction can handle the shuffle mask when the
5059// vector sources of the shuffle are different.
5060static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5061 unsigned &Imm) {
5062 // Look for the first non-undef element.
5063 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5064 [](int Elt) {return Elt >= 0;});
5065
5066 // Benefit form APInt to handle overflow when calculating expected element.
5067 unsigned NumElts = VT.getVectorNumElements();
5068 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5069 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5070 // The following shuffle indices must be the successive elements after the
5071 // first real element.
5072 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5073 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5074 if (FirstWrongElt != M.end())
5075 return false;
5076
5077 // The index of an EXT is the first element if it is not UNDEF.
5078 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005079 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005080 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5081 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5082 // ExpectedElt is the last mask index plus 1.
5083 Imm = ExpectedElt.getZExtValue();
5084
5085 // There are two difference cases requiring to reverse input vectors.
5086 // For example, for vector <4 x i32> we have the following cases,
5087 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5088 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5089 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5090 // to reverse two input vectors.
5091 if (Imm < NumElts)
5092 ReverseEXT = true;
5093 else
5094 Imm -= NumElts;
5095
5096 return true;
5097}
5098
5099/// isREVMask - Check if a vector shuffle corresponds to a REV
5100/// instruction with the specified blocksize. (The order of the elements
5101/// within each block of the vector is reversed.)
5102static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5103 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5104 "Only possible block sizes for REV are: 16, 32, 64");
5105
5106 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5107 if (EltSz == 64)
5108 return false;
5109
5110 unsigned NumElts = VT.getVectorNumElements();
5111 unsigned BlockElts = M[0] + 1;
5112 // If the first shuffle index is UNDEF, be optimistic.
5113 if (M[0] < 0)
5114 BlockElts = BlockSize / EltSz;
5115
5116 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5117 return false;
5118
5119 for (unsigned i = 0; i < NumElts; ++i) {
5120 if (M[i] < 0)
5121 continue; // ignore UNDEF indices
5122 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5123 return false;
5124 }
5125
5126 return true;
5127}
5128
5129static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5130 unsigned NumElts = VT.getVectorNumElements();
5131 WhichResult = (M[0] == 0 ? 0 : 1);
5132 unsigned Idx = WhichResult * NumElts / 2;
5133 for (unsigned i = 0; i != NumElts; i += 2) {
5134 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5135 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5136 return false;
5137 Idx += 1;
5138 }
5139
5140 return true;
5141}
5142
5143static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5144 unsigned NumElts = VT.getVectorNumElements();
5145 WhichResult = (M[0] == 0 ? 0 : 1);
5146 for (unsigned i = 0; i != NumElts; ++i) {
5147 if (M[i] < 0)
5148 continue; // ignore UNDEF indices
5149 if ((unsigned)M[i] != 2 * i + WhichResult)
5150 return false;
5151 }
5152
5153 return true;
5154}
5155
5156static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5157 unsigned NumElts = VT.getVectorNumElements();
5158 WhichResult = (M[0] == 0 ? 0 : 1);
5159 for (unsigned i = 0; i < NumElts; i += 2) {
5160 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5161 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5162 return false;
5163 }
5164 return true;
5165}
5166
5167/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5168/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5169/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5170static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5171 unsigned NumElts = VT.getVectorNumElements();
5172 WhichResult = (M[0] == 0 ? 0 : 1);
5173 unsigned Idx = WhichResult * NumElts / 2;
5174 for (unsigned i = 0; i != NumElts; i += 2) {
5175 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5176 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5177 return false;
5178 Idx += 1;
5179 }
5180
5181 return true;
5182}
5183
5184/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5185/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5186/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5187static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5188 unsigned Half = VT.getVectorNumElements() / 2;
5189 WhichResult = (M[0] == 0 ? 0 : 1);
5190 for (unsigned j = 0; j != 2; ++j) {
5191 unsigned Idx = WhichResult;
5192 for (unsigned i = 0; i != Half; ++i) {
5193 int MIdx = M[i + j * Half];
5194 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5195 return false;
5196 Idx += 2;
5197 }
5198 }
5199
5200 return true;
5201}
5202
5203/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5204/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5205/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5206static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5207 unsigned NumElts = VT.getVectorNumElements();
5208 WhichResult = (M[0] == 0 ? 0 : 1);
5209 for (unsigned i = 0; i < NumElts; i += 2) {
5210 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5211 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5212 return false;
5213 }
5214 return true;
5215}
5216
5217static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5218 bool &DstIsLeft, int &Anomaly) {
5219 if (M.size() != static_cast<size_t>(NumInputElements))
5220 return false;
5221
5222 int NumLHSMatch = 0, NumRHSMatch = 0;
5223 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5224
5225 for (int i = 0; i < NumInputElements; ++i) {
5226 if (M[i] == -1) {
5227 ++NumLHSMatch;
5228 ++NumRHSMatch;
5229 continue;
5230 }
5231
5232 if (M[i] == i)
5233 ++NumLHSMatch;
5234 else
5235 LastLHSMismatch = i;
5236
5237 if (M[i] == i + NumInputElements)
5238 ++NumRHSMatch;
5239 else
5240 LastRHSMismatch = i;
5241 }
5242
5243 if (NumLHSMatch == NumInputElements - 1) {
5244 DstIsLeft = true;
5245 Anomaly = LastLHSMismatch;
5246 return true;
5247 } else if (NumRHSMatch == NumInputElements - 1) {
5248 DstIsLeft = false;
5249 Anomaly = LastRHSMismatch;
5250 return true;
5251 }
5252
5253 return false;
5254}
5255
5256static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5257 if (VT.getSizeInBits() != 128)
5258 return false;
5259
5260 unsigned NumElts = VT.getVectorNumElements();
5261
5262 for (int I = 0, E = NumElts / 2; I != E; I++) {
5263 if (Mask[I] != I)
5264 return false;
5265 }
5266
5267 int Offset = NumElts / 2;
5268 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5269 if (Mask[I] != I + SplitLHS * Offset)
5270 return false;
5271 }
5272
5273 return true;
5274}
5275
5276static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5277 SDLoc DL(Op);
5278 EVT VT = Op.getValueType();
5279 SDValue V0 = Op.getOperand(0);
5280 SDValue V1 = Op.getOperand(1);
5281 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5282
5283 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5284 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5285 return SDValue();
5286
5287 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5288
5289 if (!isConcatMask(Mask, VT, SplitV0))
5290 return SDValue();
5291
5292 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5293 VT.getVectorNumElements() / 2);
5294 if (SplitV0) {
5295 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005296 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005297 }
5298 if (V1.getValueType().getSizeInBits() == 128) {
5299 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005300 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005301 }
5302 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5303}
5304
5305/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5306/// the specified operations to build the shuffle.
5307static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5308 SDValue RHS, SelectionDAG &DAG,
5309 SDLoc dl) {
5310 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5311 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5312 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5313
5314 enum {
5315 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5316 OP_VREV,
5317 OP_VDUP0,
5318 OP_VDUP1,
5319 OP_VDUP2,
5320 OP_VDUP3,
5321 OP_VEXT1,
5322 OP_VEXT2,
5323 OP_VEXT3,
5324 OP_VUZPL, // VUZP, left result
5325 OP_VUZPR, // VUZP, right result
5326 OP_VZIPL, // VZIP, left result
5327 OP_VZIPR, // VZIP, right result
5328 OP_VTRNL, // VTRN, left result
5329 OP_VTRNR // VTRN, right result
5330 };
5331
5332 if (OpNum == OP_COPY) {
5333 if (LHSID == (1 * 9 + 2) * 9 + 3)
5334 return LHS;
5335 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5336 return RHS;
5337 }
5338
5339 SDValue OpLHS, OpRHS;
5340 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5341 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5342 EVT VT = OpLHS.getValueType();
5343
5344 switch (OpNum) {
5345 default:
5346 llvm_unreachable("Unknown shuffle opcode!");
5347 case OP_VREV:
5348 // VREV divides the vector in half and swaps within the half.
5349 if (VT.getVectorElementType() == MVT::i32 ||
5350 VT.getVectorElementType() == MVT::f32)
5351 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5352 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005353 if (VT.getVectorElementType() == MVT::i16 ||
5354 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005355 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5356 // vrev <4 x i8> -> REV16
5357 assert(VT.getVectorElementType() == MVT::i8);
5358 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5359 case OP_VDUP0:
5360 case OP_VDUP1:
5361 case OP_VDUP2:
5362 case OP_VDUP3: {
5363 EVT EltTy = VT.getVectorElementType();
5364 unsigned Opcode;
5365 if (EltTy == MVT::i8)
5366 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005367 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005368 Opcode = AArch64ISD::DUPLANE16;
5369 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5370 Opcode = AArch64ISD::DUPLANE32;
5371 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5372 Opcode = AArch64ISD::DUPLANE64;
5373 else
5374 llvm_unreachable("Invalid vector element type?");
5375
5376 if (VT.getSizeInBits() == 64)
5377 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005378 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005379 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5380 }
5381 case OP_VEXT1:
5382 case OP_VEXT2:
5383 case OP_VEXT3: {
5384 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5385 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005386 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005387 }
5388 case OP_VUZPL:
5389 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5390 OpRHS);
5391 case OP_VUZPR:
5392 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5393 OpRHS);
5394 case OP_VZIPL:
5395 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5396 OpRHS);
5397 case OP_VZIPR:
5398 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5399 OpRHS);
5400 case OP_VTRNL:
5401 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5402 OpRHS);
5403 case OP_VTRNR:
5404 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5405 OpRHS);
5406 }
5407}
5408
5409static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5410 SelectionDAG &DAG) {
5411 // Check to see if we can use the TBL instruction.
5412 SDValue V1 = Op.getOperand(0);
5413 SDValue V2 = Op.getOperand(1);
5414 SDLoc DL(Op);
5415
5416 EVT EltVT = Op.getValueType().getVectorElementType();
5417 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5418
5419 SmallVector<SDValue, 8> TBLMask;
5420 for (int Val : ShuffleMask) {
5421 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5422 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005423 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005424 }
5425 }
5426
5427 MVT IndexVT = MVT::v8i8;
5428 unsigned IndexLen = 8;
5429 if (Op.getValueType().getSizeInBits() == 128) {
5430 IndexVT = MVT::v16i8;
5431 IndexLen = 16;
5432 }
5433
5434 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5435 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5436
5437 SDValue Shuffle;
5438 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5439 if (IndexLen == 8)
5440 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5441 Shuffle = DAG.getNode(
5442 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005443 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005444 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5445 makeArrayRef(TBLMask.data(), IndexLen)));
5446 } else {
5447 if (IndexLen == 8) {
5448 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5449 Shuffle = DAG.getNode(
5450 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005451 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005452 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5453 makeArrayRef(TBLMask.data(), IndexLen)));
5454 } else {
5455 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5456 // cannot currently represent the register constraints on the input
5457 // table registers.
5458 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5459 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5460 // &TBLMask[0], IndexLen));
5461 Shuffle = DAG.getNode(
5462 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005463 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5464 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005465 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5466 makeArrayRef(TBLMask.data(), IndexLen)));
5467 }
5468 }
5469 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5470}
5471
5472static unsigned getDUPLANEOp(EVT EltType) {
5473 if (EltType == MVT::i8)
5474 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005475 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005476 return AArch64ISD::DUPLANE16;
5477 if (EltType == MVT::i32 || EltType == MVT::f32)
5478 return AArch64ISD::DUPLANE32;
5479 if (EltType == MVT::i64 || EltType == MVT::f64)
5480 return AArch64ISD::DUPLANE64;
5481
5482 llvm_unreachable("Invalid vector element type?");
5483}
5484
5485SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5486 SelectionDAG &DAG) const {
5487 SDLoc dl(Op);
5488 EVT VT = Op.getValueType();
5489
5490 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5491
5492 // Convert shuffles that are directly supported on NEON to target-specific
5493 // DAG nodes, instead of keeping them as shuffles and matching them again
5494 // during code selection. This is more efficient and avoids the possibility
5495 // of inconsistencies between legalization and selection.
5496 ArrayRef<int> ShuffleMask = SVN->getMask();
5497
5498 SDValue V1 = Op.getOperand(0);
5499 SDValue V2 = Op.getOperand(1);
5500
5501 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5502 V1.getValueType().getSimpleVT())) {
5503 int Lane = SVN->getSplatIndex();
5504 // If this is undef splat, generate it via "just" vdup, if possible.
5505 if (Lane == -1)
5506 Lane = 0;
5507
5508 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5509 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5510 V1.getOperand(0));
5511 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5512 // constant. If so, we can just reference the lane's definition directly.
5513 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5514 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5515 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5516
5517 // Otherwise, duplicate from the lane of the input vector.
5518 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5519
5520 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5521 // to make a vector of the same size as this SHUFFLE. We can ignore the
5522 // extract entirely, and canonicalise the concat using WidenVector.
5523 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5524 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5525 V1 = V1.getOperand(0);
5526 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5527 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5528 Lane -= Idx * VT.getVectorNumElements() / 2;
5529 V1 = WidenVector(V1.getOperand(Idx), DAG);
5530 } else if (VT.getSizeInBits() == 64)
5531 V1 = WidenVector(V1, DAG);
5532
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005533 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005534 }
5535
5536 if (isREVMask(ShuffleMask, VT, 64))
5537 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5538 if (isREVMask(ShuffleMask, VT, 32))
5539 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5540 if (isREVMask(ShuffleMask, VT, 16))
5541 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5542
5543 bool ReverseEXT = false;
5544 unsigned Imm;
5545 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5546 if (ReverseEXT)
5547 std::swap(V1, V2);
5548 Imm *= getExtFactor(V1);
5549 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005550 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005551 } else if (V2->getOpcode() == ISD::UNDEF &&
5552 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5553 Imm *= getExtFactor(V1);
5554 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005555 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005556 }
5557
5558 unsigned WhichResult;
5559 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5560 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5561 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5562 }
5563 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5564 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5565 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5566 }
5567 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5568 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5569 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5570 }
5571
5572 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5573 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5574 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5575 }
5576 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5577 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5578 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5579 }
5580 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5581 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5582 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5583 }
5584
5585 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5586 if (Concat.getNode())
5587 return Concat;
5588
5589 bool DstIsLeft;
5590 int Anomaly;
5591 int NumInputElements = V1.getValueType().getVectorNumElements();
5592 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5593 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005594 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005595
5596 SDValue SrcVec = V1;
5597 int SrcLane = ShuffleMask[Anomaly];
5598 if (SrcLane >= NumInputElements) {
5599 SrcVec = V2;
5600 SrcLane -= VT.getVectorNumElements();
5601 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005602 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005603
5604 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005605
5606 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005607 ScalarVT = MVT::i32;
5608
5609 return DAG.getNode(
5610 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5611 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5612 DstLaneV);
5613 }
5614
5615 // If the shuffle is not directly supported and it has 4 elements, use
5616 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5617 unsigned NumElts = VT.getVectorNumElements();
5618 if (NumElts == 4) {
5619 unsigned PFIndexes[4];
5620 for (unsigned i = 0; i != 4; ++i) {
5621 if (ShuffleMask[i] < 0)
5622 PFIndexes[i] = 8;
5623 else
5624 PFIndexes[i] = ShuffleMask[i];
5625 }
5626
5627 // Compute the index in the perfect shuffle table.
5628 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5629 PFIndexes[2] * 9 + PFIndexes[3];
5630 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5631 unsigned Cost = (PFEntry >> 30);
5632
5633 if (Cost <= 4)
5634 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5635 }
5636
5637 return GenerateTBL(Op, ShuffleMask, DAG);
5638}
5639
5640static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5641 APInt &UndefBits) {
5642 EVT VT = BVN->getValueType(0);
5643 APInt SplatBits, SplatUndef;
5644 unsigned SplatBitSize;
5645 bool HasAnyUndefs;
5646 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5647 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5648
5649 for (unsigned i = 0; i < NumSplats; ++i) {
5650 CnstBits <<= SplatBitSize;
5651 UndefBits <<= SplatBitSize;
5652 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5653 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5654 }
5655
5656 return true;
5657 }
5658
5659 return false;
5660}
5661
5662SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5663 SelectionDAG &DAG) const {
5664 BuildVectorSDNode *BVN =
5665 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5666 SDValue LHS = Op.getOperand(0);
5667 SDLoc dl(Op);
5668 EVT VT = Op.getValueType();
5669
5670 if (!BVN)
5671 return Op;
5672
5673 APInt CnstBits(VT.getSizeInBits(), 0);
5674 APInt UndefBits(VT.getSizeInBits(), 0);
5675 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5676 // We only have BIC vector immediate instruction, which is and-not.
5677 CnstBits = ~CnstBits;
5678
5679 // We make use of a little bit of goto ickiness in order to avoid having to
5680 // duplicate the immediate matching logic for the undef toggled case.
5681 bool SecondTry = false;
5682 AttemptModImm:
5683
5684 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5685 CnstBits = CnstBits.zextOrTrunc(64);
5686 uint64_t CnstVal = CnstBits.getZExtValue();
5687
5688 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5689 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5690 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5691 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005692 DAG.getConstant(CnstVal, dl, MVT::i32),
5693 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005694 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005695 }
5696
5697 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5698 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5699 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5700 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005701 DAG.getConstant(CnstVal, dl, MVT::i32),
5702 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005703 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005704 }
5705
5706 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5707 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5708 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5709 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005710 DAG.getConstant(CnstVal, dl, MVT::i32),
5711 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005712 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005713 }
5714
5715 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5716 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5717 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5718 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005719 DAG.getConstant(CnstVal, dl, MVT::i32),
5720 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005721 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005722 }
5723
5724 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5725 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5726 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5727 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005728 DAG.getConstant(CnstVal, dl, MVT::i32),
5729 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005730 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005731 }
5732
5733 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5734 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5735 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5736 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005737 DAG.getConstant(CnstVal, dl, MVT::i32),
5738 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005739 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005740 }
5741 }
5742
5743 if (SecondTry)
5744 goto FailedModImm;
5745 SecondTry = true;
5746 CnstBits = ~UndefBits;
5747 goto AttemptModImm;
5748 }
5749
5750// We can always fall back to a non-immediate AND.
5751FailedModImm:
5752 return Op;
5753}
5754
5755// Specialized code to quickly find if PotentialBVec is a BuildVector that
5756// consists of only the same constant int value, returned in reference arg
5757// ConstVal
5758static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5759 uint64_t &ConstVal) {
5760 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5761 if (!Bvec)
5762 return false;
5763 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5764 if (!FirstElt)
5765 return false;
5766 EVT VT = Bvec->getValueType(0);
5767 unsigned NumElts = VT.getVectorNumElements();
5768 for (unsigned i = 1; i < NumElts; ++i)
5769 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5770 return false;
5771 ConstVal = FirstElt->getZExtValue();
5772 return true;
5773}
5774
5775static unsigned getIntrinsicID(const SDNode *N) {
5776 unsigned Opcode = N->getOpcode();
5777 switch (Opcode) {
5778 default:
5779 return Intrinsic::not_intrinsic;
5780 case ISD::INTRINSIC_WO_CHAIN: {
5781 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5782 if (IID < Intrinsic::num_intrinsics)
5783 return IID;
5784 return Intrinsic::not_intrinsic;
5785 }
5786 }
5787}
5788
5789// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5790// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5791// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5792// Also, logical shift right -> sri, with the same structure.
5793static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5794 EVT VT = N->getValueType(0);
5795
5796 if (!VT.isVector())
5797 return SDValue();
5798
5799 SDLoc DL(N);
5800
5801 // Is the first op an AND?
5802 const SDValue And = N->getOperand(0);
5803 if (And.getOpcode() != ISD::AND)
5804 return SDValue();
5805
5806 // Is the second op an shl or lshr?
5807 SDValue Shift = N->getOperand(1);
5808 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5809 // or AArch64ISD::VLSHR vector, #shift
5810 unsigned ShiftOpc = Shift.getOpcode();
5811 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5812 return SDValue();
5813 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5814
5815 // Is the shift amount constant?
5816 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5817 if (!C2node)
5818 return SDValue();
5819
5820 // Is the and mask vector all constant?
5821 uint64_t C1;
5822 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5823 return SDValue();
5824
5825 // Is C1 == ~C2, taking into account how much one can shift elements of a
5826 // particular size?
5827 uint64_t C2 = C2node->getZExtValue();
5828 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5829 if (C2 > ElemSizeInBits)
5830 return SDValue();
5831 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5832 if ((C1 & ElemMask) != (~C2 & ElemMask))
5833 return SDValue();
5834
5835 SDValue X = And.getOperand(0);
5836 SDValue Y = Shift.getOperand(0);
5837
5838 unsigned Intrin =
5839 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5840 SDValue ResultSLI =
5841 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005842 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5843 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005844
5845 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5846 DEBUG(N->dump(&DAG));
5847 DEBUG(dbgs() << "into: \n");
5848 DEBUG(ResultSLI->dump(&DAG));
5849
5850 ++NumShiftInserts;
5851 return ResultSLI;
5852}
5853
5854SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5855 SelectionDAG &DAG) const {
5856 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5857 if (EnableAArch64SlrGeneration) {
5858 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5859 if (Res.getNode())
5860 return Res;
5861 }
5862
5863 BuildVectorSDNode *BVN =
5864 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5865 SDValue LHS = Op.getOperand(1);
5866 SDLoc dl(Op);
5867 EVT VT = Op.getValueType();
5868
5869 // OR commutes, so try swapping the operands.
5870 if (!BVN) {
5871 LHS = Op.getOperand(0);
5872 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5873 }
5874 if (!BVN)
5875 return Op;
5876
5877 APInt CnstBits(VT.getSizeInBits(), 0);
5878 APInt UndefBits(VT.getSizeInBits(), 0);
5879 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5880 // We make use of a little bit of goto ickiness in order to avoid having to
5881 // duplicate the immediate matching logic for the undef toggled case.
5882 bool SecondTry = false;
5883 AttemptModImm:
5884
5885 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5886 CnstBits = CnstBits.zextOrTrunc(64);
5887 uint64_t CnstVal = CnstBits.getZExtValue();
5888
5889 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5890 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5891 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5892 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005893 DAG.getConstant(CnstVal, dl, MVT::i32),
5894 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005895 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005896 }
5897
5898 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5899 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5900 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5901 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005902 DAG.getConstant(CnstVal, dl, MVT::i32),
5903 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005904 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005905 }
5906
5907 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5908 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5909 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5910 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005911 DAG.getConstant(CnstVal, dl, MVT::i32),
5912 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005913 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005914 }
5915
5916 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5917 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5918 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5919 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005920 DAG.getConstant(CnstVal, dl, MVT::i32),
5921 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005922 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005923 }
5924
5925 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5926 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5927 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5928 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005929 DAG.getConstant(CnstVal, dl, MVT::i32),
5930 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005931 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005932 }
5933
5934 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5935 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5936 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5937 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005938 DAG.getConstant(CnstVal, dl, MVT::i32),
5939 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005940 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005941 }
5942 }
5943
5944 if (SecondTry)
5945 goto FailedModImm;
5946 SecondTry = true;
5947 CnstBits = UndefBits;
5948 goto AttemptModImm;
5949 }
5950
5951// We can always fall back to a non-immediate OR.
5952FailedModImm:
5953 return Op;
5954}
5955
Kevin Qin4473c192014-07-07 02:45:40 +00005956// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5957// be truncated to fit element width.
5958static SDValue NormalizeBuildVector(SDValue Op,
5959 SelectionDAG &DAG) {
5960 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005961 SDLoc dl(Op);
5962 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005963 EVT EltTy= VT.getVectorElementType();
5964
5965 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5966 return Op;
5967
5968 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005969 for (SDValue Lane : Op->ops()) {
5970 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00005971 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005972 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005973 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00005974 }
5975 Ops.push_back(Lane);
5976 }
5977 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5978}
5979
5980SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5981 SelectionDAG &DAG) const {
5982 SDLoc dl(Op);
5983 EVT VT = Op.getValueType();
5984 Op = NormalizeBuildVector(Op, DAG);
5985 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00005986
5987 APInt CnstBits(VT.getSizeInBits(), 0);
5988 APInt UndefBits(VT.getSizeInBits(), 0);
5989 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5990 // We make use of a little bit of goto ickiness in order to avoid having to
5991 // duplicate the immediate matching logic for the undef toggled case.
5992 bool SecondTry = false;
5993 AttemptModImm:
5994
5995 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5996 CnstBits = CnstBits.zextOrTrunc(64);
5997 uint64_t CnstVal = CnstBits.getZExtValue();
5998
5999 // Certain magic vector constants (used to express things like NOT
6000 // and NEG) are passed through unmodified. This allows codegen patterns
6001 // for these operations to match. Special-purpose patterns will lower
6002 // these immediates to MOVIs if it proves necessary.
6003 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6004 return Op;
6005
6006 // The many faces of MOVI...
6007 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6008 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6009 if (VT.getSizeInBits() == 128) {
6010 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006011 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006012 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006013 }
6014
6015 // Support the V64 version via subregister insertion.
6016 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006017 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006018 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006019 }
6020
6021 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6022 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6023 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6024 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006025 DAG.getConstant(CnstVal, dl, MVT::i32),
6026 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006027 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006028 }
6029
6030 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6031 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6032 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6033 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006034 DAG.getConstant(CnstVal, dl, MVT::i32),
6035 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006036 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006037 }
6038
6039 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6040 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6041 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6042 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006043 DAG.getConstant(CnstVal, dl, MVT::i32),
6044 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006045 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006046 }
6047
6048 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6049 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6050 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6051 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006052 DAG.getConstant(CnstVal, dl, MVT::i32),
6053 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006054 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006055 }
6056
6057 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6058 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6059 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6060 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006061 DAG.getConstant(CnstVal, dl, MVT::i32),
6062 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006063 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006064 }
6065
6066 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6067 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6068 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6069 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006070 DAG.getConstant(CnstVal, dl, MVT::i32),
6071 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006072 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006073 }
6074
6075 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6076 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6077 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6078 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006079 DAG.getConstant(CnstVal, dl, MVT::i32),
6080 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006081 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006082 }
6083
6084 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6085 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6086 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6087 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006088 DAG.getConstant(CnstVal, dl, MVT::i32),
6089 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006090 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006091 }
6092
6093 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6094 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6095 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6096 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006097 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006098 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006099 }
6100
6101 // The few faces of FMOV...
6102 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6103 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6104 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6105 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006106 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006107 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006108 }
6109
6110 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6111 VT.getSizeInBits() == 128) {
6112 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6113 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006114 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006115 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006116 }
6117
6118 // The many faces of MVNI...
6119 CnstVal = ~CnstVal;
6120 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6121 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6122 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6123 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006124 DAG.getConstant(CnstVal, dl, MVT::i32),
6125 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006126 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006127 }
6128
6129 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6130 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6131 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6132 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006133 DAG.getConstant(CnstVal, dl, MVT::i32),
6134 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006135 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006136 }
6137
6138 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6139 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6140 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6141 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006142 DAG.getConstant(CnstVal, dl, MVT::i32),
6143 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006144 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006145 }
6146
6147 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6148 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6149 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6150 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006151 DAG.getConstant(CnstVal, dl, MVT::i32),
6152 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006153 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006154 }
6155
6156 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6157 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6158 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6159 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006160 DAG.getConstant(CnstVal, dl, MVT::i32),
6161 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006162 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006163 }
6164
6165 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6166 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6167 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6168 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006169 DAG.getConstant(CnstVal, dl, MVT::i32),
6170 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006171 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006172 }
6173
6174 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6175 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6176 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6177 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006178 DAG.getConstant(CnstVal, dl, MVT::i32),
6179 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006180 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006181 }
6182
6183 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6184 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6185 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6186 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006187 DAG.getConstant(CnstVal, dl, MVT::i32),
6188 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006189 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006190 }
6191 }
6192
6193 if (SecondTry)
6194 goto FailedModImm;
6195 SecondTry = true;
6196 CnstBits = UndefBits;
6197 goto AttemptModImm;
6198 }
6199FailedModImm:
6200
6201 // Scan through the operands to find some interesting properties we can
6202 // exploit:
6203 // 1) If only one value is used, we can use a DUP, or
6204 // 2) if only the low element is not undef, we can just insert that, or
6205 // 3) if only one constant value is used (w/ some non-constant lanes),
6206 // we can splat the constant value into the whole vector then fill
6207 // in the non-constant lanes.
6208 // 4) FIXME: If different constant values are used, but we can intelligently
6209 // select the values we'll be overwriting for the non-constant
6210 // lanes such that we can directly materialize the vector
6211 // some other way (MOVI, e.g.), we can be sneaky.
6212 unsigned NumElts = VT.getVectorNumElements();
6213 bool isOnlyLowElement = true;
6214 bool usesOnlyOneValue = true;
6215 bool usesOnlyOneConstantValue = true;
6216 bool isConstant = true;
6217 unsigned NumConstantLanes = 0;
6218 SDValue Value;
6219 SDValue ConstantValue;
6220 for (unsigned i = 0; i < NumElts; ++i) {
6221 SDValue V = Op.getOperand(i);
6222 if (V.getOpcode() == ISD::UNDEF)
6223 continue;
6224 if (i > 0)
6225 isOnlyLowElement = false;
6226 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6227 isConstant = false;
6228
6229 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6230 ++NumConstantLanes;
6231 if (!ConstantValue.getNode())
6232 ConstantValue = V;
6233 else if (ConstantValue != V)
6234 usesOnlyOneConstantValue = false;
6235 }
6236
6237 if (!Value.getNode())
6238 Value = V;
6239 else if (V != Value)
6240 usesOnlyOneValue = false;
6241 }
6242
6243 if (!Value.getNode())
6244 return DAG.getUNDEF(VT);
6245
6246 if (isOnlyLowElement)
6247 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6248
6249 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6250 // i32 and try again.
6251 if (usesOnlyOneValue) {
6252 if (!isConstant) {
6253 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6254 Value.getValueType() != VT)
6255 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6256
6257 // This is actually a DUPLANExx operation, which keeps everything vectory.
6258
6259 // DUPLANE works on 128-bit vectors, widen it if necessary.
6260 SDValue Lane = Value.getOperand(1);
6261 Value = Value.getOperand(0);
6262 if (Value.getValueType().getSizeInBits() == 64)
6263 Value = WidenVector(Value, DAG);
6264
6265 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6266 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6267 }
6268
6269 if (VT.getVectorElementType().isFloatingPoint()) {
6270 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006271 EVT EltTy = VT.getVectorElementType();
6272 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6273 "Unsupported floating-point vector type");
6274 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006275 for (unsigned i = 0; i < NumElts; ++i)
6276 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6277 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6278 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6279 Val = LowerBUILD_VECTOR(Val, DAG);
6280 if (Val.getNode())
6281 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6282 }
6283 }
6284
6285 // If there was only one constant value used and for more than one lane,
6286 // start by splatting that value, then replace the non-constant lanes. This
6287 // is better than the default, which will perform a separate initialization
6288 // for each lane.
6289 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6290 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6291 // Now insert the non-constant lanes.
6292 for (unsigned i = 0; i < NumElts; ++i) {
6293 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006294 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006295 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6296 // Note that type legalization likely mucked about with the VT of the
6297 // source operand, so we may have to convert it here before inserting.
6298 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6299 }
6300 }
6301 return Val;
6302 }
6303
6304 // If all elements are constants and the case above didn't get hit, fall back
6305 // to the default expansion, which will generate a load from the constant
6306 // pool.
6307 if (isConstant)
6308 return SDValue();
6309
6310 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6311 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006312 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006313 return shuffle;
6314 }
6315
6316 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6317 // know the default expansion would otherwise fall back on something even
6318 // worse. For a vector with one or two non-undef values, that's
6319 // scalar_to_vector for the elements followed by a shuffle (provided the
6320 // shuffle is valid for the target) and materialization element by element
6321 // on the stack followed by a load for everything else.
6322 if (!isConstant && !usesOnlyOneValue) {
6323 SDValue Vec = DAG.getUNDEF(VT);
6324 SDValue Op0 = Op.getOperand(0);
6325 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6326 unsigned i = 0;
6327 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6328 // a) Avoid a RMW dependency on the full vector register, and
6329 // b) Allow the register coalescer to fold away the copy if the
6330 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006331 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6332 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6333 if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6334 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006335 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6336 MachineSDNode *N =
6337 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006338 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006339 Vec = SDValue(N, 0);
6340 ++i;
6341 }
6342 for (; i < NumElts; ++i) {
6343 SDValue V = Op.getOperand(i);
6344 if (V.getOpcode() == ISD::UNDEF)
6345 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006346 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006347 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6348 }
6349 return Vec;
6350 }
6351
6352 // Just use the default expansion. We failed to find a better alternative.
6353 return SDValue();
6354}
6355
6356SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6357 SelectionDAG &DAG) const {
6358 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6359
Tim Northovere4b8e132014-07-15 10:00:26 +00006360 // Check for non-constant or out of range lane.
6361 EVT VT = Op.getOperand(0).getValueType();
6362 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6363 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006364 return SDValue();
6365
Tim Northover3b0846e2014-05-24 12:50:23 +00006366
6367 // Insertion/extraction are legal for V128 types.
6368 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006369 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6370 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006371 return Op;
6372
6373 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006374 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006375 return SDValue();
6376
6377 // For V64 types, we perform insertion by expanding the value
6378 // to a V128 type and perform the insertion on that.
6379 SDLoc DL(Op);
6380 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6381 EVT WideTy = WideVec.getValueType();
6382
6383 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6384 Op.getOperand(1), Op.getOperand(2));
6385 // Re-narrow the resultant vector.
6386 return NarrowVector(Node, DAG);
6387}
6388
6389SDValue
6390AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6391 SelectionDAG &DAG) const {
6392 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6393
Tim Northovere4b8e132014-07-15 10:00:26 +00006394 // Check for non-constant or out of range lane.
6395 EVT VT = Op.getOperand(0).getValueType();
6396 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6397 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006398 return SDValue();
6399
Tim Northover3b0846e2014-05-24 12:50:23 +00006400
6401 // Insertion/extraction are legal for V128 types.
6402 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006403 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6404 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006405 return Op;
6406
6407 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006408 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006409 return SDValue();
6410
6411 // For V64 types, we perform extraction by expanding the value
6412 // to a V128 type and perform the extraction on that.
6413 SDLoc DL(Op);
6414 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6415 EVT WideTy = WideVec.getValueType();
6416
6417 EVT ExtrTy = WideTy.getVectorElementType();
6418 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6419 ExtrTy = MVT::i32;
6420
6421 // For extractions, we just return the result directly.
6422 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6423 Op.getOperand(1));
6424}
6425
6426SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6427 SelectionDAG &DAG) const {
6428 EVT VT = Op.getOperand(0).getValueType();
6429 SDLoc dl(Op);
6430 // Just in case...
6431 if (!VT.isVector())
6432 return SDValue();
6433
6434 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6435 if (!Cst)
6436 return SDValue();
6437 unsigned Val = Cst->getZExtValue();
6438
6439 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006440
6441 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6442 if (Val == 0)
6443 return Op;
6444
Tim Northover3b0846e2014-05-24 12:50:23 +00006445 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6446 // that directly.
6447 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6448 return Op;
6449
6450 return SDValue();
6451}
6452
6453bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6454 EVT VT) const {
6455 if (VT.getVectorNumElements() == 4 &&
6456 (VT.is128BitVector() || VT.is64BitVector())) {
6457 unsigned PFIndexes[4];
6458 for (unsigned i = 0; i != 4; ++i) {
6459 if (M[i] < 0)
6460 PFIndexes[i] = 8;
6461 else
6462 PFIndexes[i] = M[i];
6463 }
6464
6465 // Compute the index in the perfect shuffle table.
6466 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6467 PFIndexes[2] * 9 + PFIndexes[3];
6468 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6469 unsigned Cost = (PFEntry >> 30);
6470
6471 if (Cost <= 4)
6472 return true;
6473 }
6474
6475 bool DummyBool;
6476 int DummyInt;
6477 unsigned DummyUnsigned;
6478
6479 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6480 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6481 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6482 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6483 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6484 isZIPMask(M, VT, DummyUnsigned) ||
6485 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6486 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6487 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6488 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6489 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6490}
6491
6492/// getVShiftImm - Check if this is a valid build_vector for the immediate
6493/// operand of a vector shift operation, where all the elements of the
6494/// build_vector must have the same constant integer value.
6495static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6496 // Ignore bit_converts.
6497 while (Op.getOpcode() == ISD::BITCAST)
6498 Op = Op.getOperand(0);
6499 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6500 APInt SplatBits, SplatUndef;
6501 unsigned SplatBitSize;
6502 bool HasAnyUndefs;
6503 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6504 HasAnyUndefs, ElementBits) ||
6505 SplatBitSize > ElementBits)
6506 return false;
6507 Cnt = SplatBits.getSExtValue();
6508 return true;
6509}
6510
6511/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6512/// operand of a vector shift left operation. That value must be in the range:
6513/// 0 <= Value < ElementBits for a left shift; or
6514/// 0 <= Value <= ElementBits for a long left shift.
6515static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6516 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006517 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006518 if (!getVShiftImm(Op, ElementBits, Cnt))
6519 return false;
6520 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6521}
6522
6523/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006524/// operand of a vector shift right operation. The value must be in the range:
6525/// 1 <= Value <= ElementBits for a right shift; or
6526static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006527 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006528 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006529 if (!getVShiftImm(Op, ElementBits, Cnt))
6530 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006531 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6532}
6533
6534SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6535 SelectionDAG &DAG) const {
6536 EVT VT = Op.getValueType();
6537 SDLoc DL(Op);
6538 int64_t Cnt;
6539
6540 if (!Op.getOperand(1).getValueType().isVector())
6541 return Op;
6542 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6543
6544 switch (Op.getOpcode()) {
6545 default:
6546 llvm_unreachable("unexpected shift opcode");
6547
6548 case ISD::SHL:
6549 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006550 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6551 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006552 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006553 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6554 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006555 Op.getOperand(0), Op.getOperand(1));
6556 case ISD::SRA:
6557 case ISD::SRL:
6558 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006559 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006560 unsigned Opc =
6561 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006562 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6563 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006564 }
6565
6566 // Right shift register. Note, there is not a shift right register
6567 // instruction, but the shift left register instruction takes a signed
6568 // value, where negative numbers specify a right shift.
6569 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6570 : Intrinsic::aarch64_neon_ushl;
6571 // negate the shift amount
6572 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6573 SDValue NegShiftLeft =
6574 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006575 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6576 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006577 return NegShiftLeft;
6578 }
6579
6580 return SDValue();
6581}
6582
6583static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6584 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6585 SDLoc dl, SelectionDAG &DAG) {
6586 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006587 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6588 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006589
6590 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6591 APInt CnstBits(VT.getSizeInBits(), 0);
6592 APInt UndefBits(VT.getSizeInBits(), 0);
6593 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6594 bool IsZero = IsCnst && (CnstBits == 0);
6595
6596 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6597 switch (CC) {
6598 default:
6599 return SDValue();
6600 case AArch64CC::NE: {
6601 SDValue Fcmeq;
6602 if (IsZero)
6603 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6604 else
6605 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6606 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6607 }
6608 case AArch64CC::EQ:
6609 if (IsZero)
6610 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6611 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6612 case AArch64CC::GE:
6613 if (IsZero)
6614 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6615 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6616 case AArch64CC::GT:
6617 if (IsZero)
6618 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6619 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6620 case AArch64CC::LS:
6621 if (IsZero)
6622 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6623 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6624 case AArch64CC::LT:
6625 if (!NoNans)
6626 return SDValue();
6627 // If we ignore NaNs then we can use to the MI implementation.
6628 // Fallthrough.
6629 case AArch64CC::MI:
6630 if (IsZero)
6631 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6632 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6633 }
6634 }
6635
6636 switch (CC) {
6637 default:
6638 return SDValue();
6639 case AArch64CC::NE: {
6640 SDValue Cmeq;
6641 if (IsZero)
6642 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6643 else
6644 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6645 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6646 }
6647 case AArch64CC::EQ:
6648 if (IsZero)
6649 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6650 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6651 case AArch64CC::GE:
6652 if (IsZero)
6653 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6654 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6655 case AArch64CC::GT:
6656 if (IsZero)
6657 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6658 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6659 case AArch64CC::LE:
6660 if (IsZero)
6661 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6662 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6663 case AArch64CC::LS:
6664 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6665 case AArch64CC::LO:
6666 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6667 case AArch64CC::LT:
6668 if (IsZero)
6669 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6670 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6671 case AArch64CC::HI:
6672 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6673 case AArch64CC::HS:
6674 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6675 }
6676}
6677
6678SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6679 SelectionDAG &DAG) const {
6680 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6681 SDValue LHS = Op.getOperand(0);
6682 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006683 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006684 SDLoc dl(Op);
6685
6686 if (LHS.getValueType().getVectorElementType().isInteger()) {
6687 assert(LHS.getValueType() == RHS.getValueType());
6688 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006689 SDValue Cmp =
6690 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6691 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006692 }
6693
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006694 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6695 return SDValue();
6696
Tim Northover3b0846e2014-05-24 12:50:23 +00006697 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6698 LHS.getValueType().getVectorElementType() == MVT::f64);
6699
6700 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6701 // clean. Some of them require two branches to implement.
6702 AArch64CC::CondCode CC1, CC2;
6703 bool ShouldInvert;
6704 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6705
6706 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6707 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006708 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006709 if (!Cmp.getNode())
6710 return SDValue();
6711
6712 if (CC2 != AArch64CC::AL) {
6713 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006714 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006715 if (!Cmp2.getNode())
6716 return SDValue();
6717
Tim Northover45aa89c2015-02-08 00:50:47 +00006718 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006719 }
6720
Tim Northover45aa89c2015-02-08 00:50:47 +00006721 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6722
Tim Northover3b0846e2014-05-24 12:50:23 +00006723 if (ShouldInvert)
6724 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6725
6726 return Cmp;
6727}
6728
6729/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6730/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6731/// specified in the intrinsic calls.
6732bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6733 const CallInst &I,
6734 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006735 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006736 switch (Intrinsic) {
6737 case Intrinsic::aarch64_neon_ld2:
6738 case Intrinsic::aarch64_neon_ld3:
6739 case Intrinsic::aarch64_neon_ld4:
6740 case Intrinsic::aarch64_neon_ld1x2:
6741 case Intrinsic::aarch64_neon_ld1x3:
6742 case Intrinsic::aarch64_neon_ld1x4:
6743 case Intrinsic::aarch64_neon_ld2lane:
6744 case Intrinsic::aarch64_neon_ld3lane:
6745 case Intrinsic::aarch64_neon_ld4lane:
6746 case Intrinsic::aarch64_neon_ld2r:
6747 case Intrinsic::aarch64_neon_ld3r:
6748 case Intrinsic::aarch64_neon_ld4r: {
6749 Info.opc = ISD::INTRINSIC_W_CHAIN;
6750 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006751 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006752 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6753 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6754 Info.offset = 0;
6755 Info.align = 0;
6756 Info.vol = false; // volatile loads with NEON intrinsics not supported
6757 Info.readMem = true;
6758 Info.writeMem = false;
6759 return true;
6760 }
6761 case Intrinsic::aarch64_neon_st2:
6762 case Intrinsic::aarch64_neon_st3:
6763 case Intrinsic::aarch64_neon_st4:
6764 case Intrinsic::aarch64_neon_st1x2:
6765 case Intrinsic::aarch64_neon_st1x3:
6766 case Intrinsic::aarch64_neon_st1x4:
6767 case Intrinsic::aarch64_neon_st2lane:
6768 case Intrinsic::aarch64_neon_st3lane:
6769 case Intrinsic::aarch64_neon_st4lane: {
6770 Info.opc = ISD::INTRINSIC_VOID;
6771 // Conservatively set memVT to the entire set of vectors stored.
6772 unsigned NumElts = 0;
6773 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6774 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6775 if (!ArgTy->isVectorTy())
6776 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006777 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006778 }
6779 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6780 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6781 Info.offset = 0;
6782 Info.align = 0;
6783 Info.vol = false; // volatile stores with NEON intrinsics not supported
6784 Info.readMem = false;
6785 Info.writeMem = true;
6786 return true;
6787 }
6788 case Intrinsic::aarch64_ldaxr:
6789 case Intrinsic::aarch64_ldxr: {
6790 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6791 Info.opc = ISD::INTRINSIC_W_CHAIN;
6792 Info.memVT = MVT::getVT(PtrTy->getElementType());
6793 Info.ptrVal = I.getArgOperand(0);
6794 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006795 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006796 Info.vol = true;
6797 Info.readMem = true;
6798 Info.writeMem = false;
6799 return true;
6800 }
6801 case Intrinsic::aarch64_stlxr:
6802 case Intrinsic::aarch64_stxr: {
6803 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6804 Info.opc = ISD::INTRINSIC_W_CHAIN;
6805 Info.memVT = MVT::getVT(PtrTy->getElementType());
6806 Info.ptrVal = I.getArgOperand(1);
6807 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006808 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006809 Info.vol = true;
6810 Info.readMem = false;
6811 Info.writeMem = true;
6812 return true;
6813 }
6814 case Intrinsic::aarch64_ldaxp:
6815 case Intrinsic::aarch64_ldxp: {
6816 Info.opc = ISD::INTRINSIC_W_CHAIN;
6817 Info.memVT = MVT::i128;
6818 Info.ptrVal = I.getArgOperand(0);
6819 Info.offset = 0;
6820 Info.align = 16;
6821 Info.vol = true;
6822 Info.readMem = true;
6823 Info.writeMem = false;
6824 return true;
6825 }
6826 case Intrinsic::aarch64_stlxp:
6827 case Intrinsic::aarch64_stxp: {
6828 Info.opc = ISD::INTRINSIC_W_CHAIN;
6829 Info.memVT = MVT::i128;
6830 Info.ptrVal = I.getArgOperand(2);
6831 Info.offset = 0;
6832 Info.align = 16;
6833 Info.vol = true;
6834 Info.readMem = false;
6835 Info.writeMem = true;
6836 return true;
6837 }
6838 default:
6839 break;
6840 }
6841
6842 return false;
6843}
6844
6845// Truncations from 64-bit GPR to 32-bit GPR is free.
6846bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6847 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6848 return false;
6849 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6850 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006851 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006852}
6853bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006854 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006855 return false;
6856 unsigned NumBits1 = VT1.getSizeInBits();
6857 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006858 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006859}
6860
Chad Rosier54390052015-02-23 19:15:16 +00006861/// Check if it is profitable to hoist instruction in then/else to if.
6862/// Not profitable if I and it's user can form a FMA instruction
6863/// because we prefer FMSUB/FMADD.
6864bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6865 if (I->getOpcode() != Instruction::FMul)
6866 return true;
6867
6868 if (I->getNumUses() != 1)
6869 return true;
6870
6871 Instruction *User = I->user_back();
6872
6873 if (User &&
6874 !(User->getOpcode() == Instruction::FSub ||
6875 User->getOpcode() == Instruction::FAdd))
6876 return true;
6877
6878 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006879 const DataLayout &DL = I->getModule()->getDataLayout();
6880 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006881
6882 if (isFMAFasterThanFMulAndFAdd(VT) &&
6883 isOperationLegalOrCustom(ISD::FMA, VT) &&
6884 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6885 return false;
6886
6887 return true;
6888}
6889
Tim Northover3b0846e2014-05-24 12:50:23 +00006890// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6891// 64-bit GPR.
6892bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6893 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6894 return false;
6895 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6896 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006897 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006898}
6899bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006900 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006901 return false;
6902 unsigned NumBits1 = VT1.getSizeInBits();
6903 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006904 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006905}
6906
6907bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6908 EVT VT1 = Val.getValueType();
6909 if (isZExtFree(VT1, VT2)) {
6910 return true;
6911 }
6912
6913 if (Val.getOpcode() != ISD::LOAD)
6914 return false;
6915
6916 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006917 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6918 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6919 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006920}
6921
Quentin Colombet6843ac42015-03-31 20:52:32 +00006922bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6923 if (isa<FPExtInst>(Ext))
6924 return false;
6925
6926 // Vector types are next free.
6927 if (Ext->getType()->isVectorTy())
6928 return false;
6929
6930 for (const Use &U : Ext->uses()) {
6931 // The extension is free if we can fold it with a left shift in an
6932 // addressing mode or an arithmetic operation: add, sub, and cmp.
6933
6934 // Is there a shift?
6935 const Instruction *Instr = cast<Instruction>(U.getUser());
6936
6937 // Is this a constant shift?
6938 switch (Instr->getOpcode()) {
6939 case Instruction::Shl:
6940 if (!isa<ConstantInt>(Instr->getOperand(1)))
6941 return false;
6942 break;
6943 case Instruction::GetElementPtr: {
6944 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006945 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00006946 std::advance(GTI, U.getOperandNo());
6947 Type *IdxTy = *GTI;
6948 // This extension will end up with a shift because of the scaling factor.
6949 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6950 // Get the shift amount based on the scaling factor:
6951 // log2(sizeof(IdxTy)) - log2(8).
6952 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006953 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00006954 // Is the constant foldable in the shift of the addressing mode?
6955 // I.e., shift amount is between 1 and 4 inclusive.
6956 if (ShiftAmt == 0 || ShiftAmt > 4)
6957 return false;
6958 break;
6959 }
6960 case Instruction::Trunc:
6961 // Check if this is a noop.
6962 // trunc(sext ty1 to ty2) to ty1.
6963 if (Instr->getType() == Ext->getOperand(0)->getType())
6964 continue;
6965 // FALL THROUGH.
6966 default:
6967 return false;
6968 }
6969
6970 // At this point we can use the bfm family, so this extension is free
6971 // for that use.
6972 }
6973 return true;
6974}
6975
Tim Northover3b0846e2014-05-24 12:50:23 +00006976bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6977 unsigned &RequiredAligment) const {
6978 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6979 return false;
6980 // Cyclone supports unaligned accesses.
6981 RequiredAligment = 0;
6982 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6983 return NumBits == 32 || NumBits == 64;
6984}
6985
6986bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6987 unsigned &RequiredAligment) const {
6988 if (!LoadedType.isSimple() ||
6989 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6990 return false;
6991 // Cyclone supports unaligned accesses.
6992 RequiredAligment = 0;
6993 unsigned NumBits = LoadedType.getSizeInBits();
6994 return NumBits == 32 || NumBits == 64;
6995}
6996
Hao Liu7ec8ee32015-06-26 02:32:07 +00006997/// \brief Lower an interleaved load into a ldN intrinsic.
6998///
6999/// E.g. Lower an interleaved load (Factor = 2):
7000/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7001/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7002/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7003///
7004/// Into:
7005/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7006/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7007/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7008bool AArch64TargetLowering::lowerInterleavedLoad(
7009 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7010 ArrayRef<unsigned> Indices, unsigned Factor) const {
7011 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7012 "Invalid interleave factor");
7013 assert(!Shuffles.empty() && "Empty shufflevector input");
7014 assert(Shuffles.size() == Indices.size() &&
7015 "Unmatched number of shufflevectors and indices");
7016
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007017 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007018
7019 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007020 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007021
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007022 // Skip if we do not have NEON and skip illegal vector types.
7023 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007024 return false;
7025
7026 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7027 // load integer vectors first and then convert to pointer vectors.
7028 Type *EltTy = VecTy->getVectorElementType();
7029 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007030 VecTy =
7031 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007032
7033 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7034 Type *Tys[2] = {VecTy, PtrTy};
7035 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7036 Intrinsic::aarch64_neon_ld3,
7037 Intrinsic::aarch64_neon_ld4};
7038 Function *LdNFunc =
7039 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7040
7041 IRBuilder<> Builder(LI);
7042 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7043
7044 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7045
7046 // Replace uses of each shufflevector with the corresponding vector loaded
7047 // by ldN.
7048 for (unsigned i = 0; i < Shuffles.size(); i++) {
7049 ShuffleVectorInst *SVI = Shuffles[i];
7050 unsigned Index = Indices[i];
7051
7052 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7053
7054 // Convert the integer vector to pointer vector if the element is pointer.
7055 if (EltTy->isPointerTy())
7056 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7057
7058 SVI->replaceAllUsesWith(SubVec);
7059 }
7060
7061 return true;
7062}
7063
7064/// \brief Get a mask consisting of sequential integers starting from \p Start.
7065///
7066/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7067static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7068 unsigned NumElts) {
7069 SmallVector<Constant *, 16> Mask;
7070 for (unsigned i = 0; i < NumElts; i++)
7071 Mask.push_back(Builder.getInt32(Start + i));
7072
7073 return ConstantVector::get(Mask);
7074}
7075
7076/// \brief Lower an interleaved store into a stN intrinsic.
7077///
7078/// E.g. Lower an interleaved store (Factor = 3):
7079/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7080/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7081/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7082///
7083/// Into:
7084/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7085/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7086/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7087/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7088///
7089/// Note that the new shufflevectors will be removed and we'll only generate one
7090/// st3 instruction in CodeGen.
7091bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7092 ShuffleVectorInst *SVI,
7093 unsigned Factor) const {
7094 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7095 "Invalid interleave factor");
7096
7097 VectorType *VecTy = SVI->getType();
7098 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7099 "Invalid interleaved store");
7100
7101 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7102 Type *EltTy = VecTy->getVectorElementType();
7103 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7104
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007105 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007106 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007107
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007108 // Skip if we do not have NEON and skip illegal vector types.
7109 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007110 return false;
7111
7112 Value *Op0 = SVI->getOperand(0);
7113 Value *Op1 = SVI->getOperand(1);
7114 IRBuilder<> Builder(SI);
7115
7116 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7117 // vectors to integer vectors.
7118 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007119 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007120 unsigned NumOpElts =
7121 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7122
7123 // Convert to the corresponding integer vector.
7124 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7125 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7126 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7127
7128 SubVecTy = VectorType::get(IntTy, NumSubElts);
7129 }
7130
7131 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7132 Type *Tys[2] = {SubVecTy, PtrTy};
7133 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7134 Intrinsic::aarch64_neon_st3,
7135 Intrinsic::aarch64_neon_st4};
7136 Function *StNFunc =
7137 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7138
7139 SmallVector<Value *, 5> Ops;
7140
7141 // Split the shufflevector operands into sub vectors for the new stN call.
7142 for (unsigned i = 0; i < Factor; i++)
7143 Ops.push_back(Builder.CreateShuffleVector(
7144 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7145
7146 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7147 Builder.CreateCall(StNFunc, Ops);
7148 return true;
7149}
7150
Tim Northover3b0846e2014-05-24 12:50:23 +00007151static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7152 unsigned AlignCheck) {
7153 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7154 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7155}
7156
7157EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7158 unsigned SrcAlign, bool IsMemset,
7159 bool ZeroMemset,
7160 bool MemcpyStrSrc,
7161 MachineFunction &MF) const {
7162 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7163 // instruction to materialize the v2i64 zero and one store (with restrictive
7164 // addressing mode). Just do two i64 store of zero-registers.
7165 bool Fast;
7166 const Function *F = MF.getFunction();
7167 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007168 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007169 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007170 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007171 return MVT::f128;
7172
Lang Hames90333852015-04-09 03:40:33 +00007173 if (Size >= 8 &&
7174 (memOpAlign(SrcAlign, DstAlign, 8) ||
7175 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7176 return MVT::i64;
7177
7178 if (Size >= 4 &&
7179 (memOpAlign(SrcAlign, DstAlign, 4) ||
7180 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007181 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007182
7183 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007184}
7185
7186// 12-bit optionally shifted immediates are legal for adds.
7187bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7188 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7189 return true;
7190 return false;
7191}
7192
7193// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7194// immediates is the same as for an add or a sub.
7195bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7196 if (Immed < 0)
7197 Immed *= -1;
7198 return isLegalAddImmediate(Immed);
7199}
7200
7201/// isLegalAddressingMode - Return true if the addressing mode represented
7202/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007203bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7204 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007205 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007206 // AArch64 has five basic addressing modes:
7207 // reg
7208 // reg + 9-bit signed offset
7209 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7210 // reg1 + reg2
7211 // reg + SIZE_IN_BYTES * reg
7212
7213 // No global is ever allowed as a base.
7214 if (AM.BaseGV)
7215 return false;
7216
7217 // No reg+reg+imm addressing.
7218 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7219 return false;
7220
7221 // check reg + imm case:
7222 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7223 uint64_t NumBytes = 0;
7224 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007225 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007226 NumBytes = NumBits / 8;
7227 if (!isPowerOf2_64(NumBits))
7228 NumBytes = 0;
7229 }
7230
7231 if (!AM.Scale) {
7232 int64_t Offset = AM.BaseOffs;
7233
7234 // 9-bit signed offset
7235 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7236 return true;
7237
7238 // 12-bit unsigned offset
7239 unsigned shift = Log2_64(NumBytes);
7240 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7241 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7242 (Offset >> shift) << shift == Offset)
7243 return true;
7244 return false;
7245 }
7246
7247 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7248
7249 if (!AM.Scale || AM.Scale == 1 ||
7250 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7251 return true;
7252 return false;
7253}
7254
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007255int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7256 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007257 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007258 // Scaling factors are not free at all.
7259 // Operands | Rt Latency
7260 // -------------------------------------------
7261 // Rt, [Xn, Xm] | 4
7262 // -------------------------------------------
7263 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7264 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007265 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007266 // Scale represents reg2 * scale, thus account for 1 if
7267 // it is not equal to 0 or 1.
7268 return AM.Scale != 0 && AM.Scale != 1;
7269 return -1;
7270}
7271
7272bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7273 VT = VT.getScalarType();
7274
7275 if (!VT.isSimple())
7276 return false;
7277
7278 switch (VT.getSimpleVT().SimpleTy) {
7279 case MVT::f32:
7280 case MVT::f64:
7281 return true;
7282 default:
7283 break;
7284 }
7285
7286 return false;
7287}
7288
7289const MCPhysReg *
7290AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7291 // LR is a callee-save register, but we must treat it as clobbered by any call
7292 // site. Hence we include LR in the scratch registers, which are in turn added
7293 // as implicit-defs for stackmaps and patchpoints.
7294 static const MCPhysReg ScratchRegs[] = {
7295 AArch64::X16, AArch64::X17, AArch64::LR, 0
7296 };
7297 return ScratchRegs;
7298}
7299
7300bool
7301AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7302 EVT VT = N->getValueType(0);
7303 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7304 // it with shift to let it be lowered to UBFX.
7305 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7306 isa<ConstantSDNode>(N->getOperand(1))) {
7307 uint64_t TruncMask = N->getConstantOperandVal(1);
7308 if (isMask_64(TruncMask) &&
7309 N->getOperand(0).getOpcode() == ISD::SRL &&
7310 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7311 return false;
7312 }
7313 return true;
7314}
7315
7316bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7317 Type *Ty) const {
7318 assert(Ty->isIntegerTy());
7319
7320 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7321 if (BitSize == 0)
7322 return false;
7323
7324 int64_t Val = Imm.getSExtValue();
7325 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7326 return true;
7327
7328 if ((int64_t)Val < 0)
7329 Val = ~Val;
7330 if (BitSize == 32)
7331 Val &= (1LL << 32) - 1;
7332
7333 unsigned LZ = countLeadingZeros((uint64_t)Val);
7334 unsigned Shift = (63 - LZ) / 16;
7335 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007336 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007337}
7338
7339// Generate SUBS and CSEL for integer abs.
7340static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7341 EVT VT = N->getValueType(0);
7342
7343 SDValue N0 = N->getOperand(0);
7344 SDValue N1 = N->getOperand(1);
7345 SDLoc DL(N);
7346
7347 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7348 // and change it to SUB and CSEL.
7349 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7350 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7351 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7352 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7353 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007354 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007355 N0.getOperand(0));
7356 // Generate SUBS & CSEL.
7357 SDValue Cmp =
7358 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007359 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007360 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007361 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007362 SDValue(Cmp.getNode(), 1));
7363 }
7364 return SDValue();
7365}
7366
7367// performXorCombine - Attempts to handle integer ABS.
7368static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7369 TargetLowering::DAGCombinerInfo &DCI,
7370 const AArch64Subtarget *Subtarget) {
7371 if (DCI.isBeforeLegalizeOps())
7372 return SDValue();
7373
7374 return performIntegerAbsCombine(N, DAG);
7375}
7376
Chad Rosier17020f92014-07-23 14:57:52 +00007377SDValue
7378AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7379 SelectionDAG &DAG,
7380 std::vector<SDNode *> *Created) const {
7381 // fold (sdiv X, pow2)
7382 EVT VT = N->getValueType(0);
7383 if ((VT != MVT::i32 && VT != MVT::i64) ||
7384 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7385 return SDValue();
7386
7387 SDLoc DL(N);
7388 SDValue N0 = N->getOperand(0);
7389 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007390 SDValue Zero = DAG.getConstant(0, DL, VT);
7391 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007392
7393 // Add (N0 < 0) ? Pow2 - 1 : 0;
7394 SDValue CCVal;
7395 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7396 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7397 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7398
7399 if (Created) {
7400 Created->push_back(Cmp.getNode());
7401 Created->push_back(Add.getNode());
7402 Created->push_back(CSel.getNode());
7403 }
7404
7405 // Divide by pow2.
7406 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007407 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007408
7409 // If we're dividing by a positive value, we're done. Otherwise, we must
7410 // negate the result.
7411 if (Divisor.isNonNegative())
7412 return SRA;
7413
7414 if (Created)
7415 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007416 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007417}
7418
Tim Northover3b0846e2014-05-24 12:50:23 +00007419static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7420 TargetLowering::DAGCombinerInfo &DCI,
7421 const AArch64Subtarget *Subtarget) {
7422 if (DCI.isBeforeLegalizeOps())
7423 return SDValue();
7424
7425 // Multiplication of a power of two plus/minus one can be done more
7426 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7427 // future CPUs have a cheaper MADD instruction, this may need to be
7428 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7429 // 64-bit is 5 cycles, so this is always a win.
7430 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7431 APInt Value = C->getAPIntValue();
7432 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007433 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007434 if (Value.isNonNegative()) {
7435 // (mul x, 2^N + 1) => (add (shl x, N), x)
7436 APInt VM1 = Value - 1;
7437 if (VM1.isPowerOf2()) {
7438 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007439 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7440 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7441 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007442 N->getOperand(0));
7443 }
7444 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7445 APInt VP1 = Value + 1;
7446 if (VP1.isPowerOf2()) {
7447 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007448 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7449 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7450 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007451 N->getOperand(0));
7452 }
7453 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007454 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7455 APInt VNP1 = -Value + 1;
7456 if (VNP1.isPowerOf2()) {
7457 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007458 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7459 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7460 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007461 ShiftedVal);
7462 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007463 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7464 APInt VNM1 = -Value - 1;
7465 if (VNM1.isPowerOf2()) {
7466 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007467 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7468 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007469 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007470 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7471 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007472 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007473 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007474 }
7475 return SDValue();
7476}
7477
Jim Grosbachf7502c42014-07-18 00:40:52 +00007478static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7479 SelectionDAG &DAG) {
7480 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7481 // optimize away operation when it's from a constant.
7482 //
7483 // The general transformation is:
7484 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7485 // AND(VECTOR_CMP(x,y), constant2)
7486 // constant2 = UNARYOP(constant)
7487
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007488 // Early exit if this isn't a vector operation, the operand of the
7489 // unary operation isn't a bitwise AND, or if the sizes of the operations
7490 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007491 EVT VT = N->getValueType(0);
7492 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007493 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7494 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007495 return SDValue();
7496
Jim Grosbach724e4382014-07-23 20:41:43 +00007497 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007498 // make the transformation for non-constant splats as well, but it's unclear
7499 // that would be a benefit as it would not eliminate any operations, just
7500 // perform one more step in scalar code before moving to the vector unit.
7501 if (BuildVectorSDNode *BV =
7502 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007503 // Bail out if the vector isn't a constant.
7504 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007505 return SDValue();
7506
7507 // Everything checks out. Build up the new and improved node.
7508 SDLoc DL(N);
7509 EVT IntVT = BV->getValueType(0);
7510 // Create a new constant of the appropriate type for the transformed
7511 // DAG.
7512 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7513 // The AND node needs bitcasts to/from an integer vector type around it.
7514 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7515 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7516 N->getOperand(0)->getOperand(0), MaskConst);
7517 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7518 return Res;
7519 }
7520
7521 return SDValue();
7522}
7523
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007524static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7525 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007526 // First try to optimize away the conversion when it's conditionally from
7527 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007528 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007529 return Res;
7530
Tim Northover3b0846e2014-05-24 12:50:23 +00007531 EVT VT = N->getValueType(0);
7532 if (VT != MVT::f32 && VT != MVT::f64)
7533 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007534
Tim Northover3b0846e2014-05-24 12:50:23 +00007535 // Only optimize when the source and destination types have the same width.
7536 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7537 return SDValue();
7538
7539 // If the result of an integer load is only used by an integer-to-float
7540 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007541 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007542 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007543 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007544 // Do not change the width of a volatile load.
7545 !cast<LoadSDNode>(N0)->isVolatile()) {
7546 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7547 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7548 LN0->getPointerInfo(), LN0->isVolatile(),
7549 LN0->isNonTemporal(), LN0->isInvariant(),
7550 LN0->getAlignment());
7551
7552 // Make sure successors of the original load stay after it by updating them
7553 // to use the new Chain.
7554 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7555
7556 unsigned Opcode =
7557 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7558 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7559 }
7560
7561 return SDValue();
7562}
7563
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007564/// Fold a floating-point multiply by power of two into floating-point to
7565/// fixed-point conversion.
7566static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7567 const AArch64Subtarget *Subtarget) {
7568 if (!Subtarget->hasNEON())
7569 return SDValue();
7570
7571 SDValue Op = N->getOperand(0);
7572 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7573 return SDValue();
7574
7575 SDValue ConstVec = Op->getOperand(1);
7576 if (!isa<BuildVectorSDNode>(ConstVec))
7577 return SDValue();
7578
7579 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7580 uint32_t FloatBits = FloatTy.getSizeInBits();
7581 if (FloatBits != 32 && FloatBits != 64)
7582 return SDValue();
7583
7584 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7585 uint32_t IntBits = IntTy.getSizeInBits();
7586 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7587 return SDValue();
7588
7589 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7590 if (IntBits > FloatBits)
7591 return SDValue();
7592
7593 BitVector UndefElements;
7594 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7595 int32_t Bits = IntBits == 64 ? 64 : 32;
7596 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7597 if (C == -1 || C == 0 || C > Bits)
7598 return SDValue();
7599
7600 MVT ResTy;
7601 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7602 switch (NumLanes) {
7603 default:
7604 return SDValue();
7605 case 2:
7606 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7607 break;
7608 case 4:
7609 ResTy = MVT::v4i32;
7610 break;
7611 }
7612
7613 SDLoc DL(N);
7614 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7615 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7616 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7617 SDValue FixConv =
7618 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7619 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7620 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7621 // We can handle smaller integers by generating an extra trunc.
7622 if (IntBits < FloatBits)
7623 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7624
7625 return FixConv;
7626}
7627
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007628/// Fold a floating-point divide by power of two into fixed-point to
7629/// floating-point conversion.
7630static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7631 const AArch64Subtarget *Subtarget) {
7632 if (!Subtarget->hasNEON())
7633 return SDValue();
7634
7635 SDValue Op = N->getOperand(0);
7636 unsigned Opc = Op->getOpcode();
7637 if (!Op.getValueType().isVector() ||
7638 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7639 return SDValue();
7640
7641 SDValue ConstVec = N->getOperand(1);
7642 if (!isa<BuildVectorSDNode>(ConstVec))
7643 return SDValue();
7644
7645 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7646 int32_t IntBits = IntTy.getSizeInBits();
7647 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7648 return SDValue();
7649
7650 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7651 int32_t FloatBits = FloatTy.getSizeInBits();
7652 if (FloatBits != 32 && FloatBits != 64)
7653 return SDValue();
7654
7655 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7656 if (IntBits > FloatBits)
7657 return SDValue();
7658
7659 BitVector UndefElements;
7660 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7661 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7662 if (C == -1 || C == 0 || C > FloatBits)
7663 return SDValue();
7664
7665 MVT ResTy;
7666 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7667 switch (NumLanes) {
7668 default:
7669 return SDValue();
7670 case 2:
7671 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7672 break;
7673 case 4:
7674 ResTy = MVT::v4i32;
7675 break;
7676 }
7677
7678 SDLoc DL(N);
7679 SDValue ConvInput = Op.getOperand(0);
7680 bool IsSigned = Opc == ISD::SINT_TO_FP;
7681 if (IntBits < FloatBits)
7682 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7683 ResTy, ConvInput);
7684
7685 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7686 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7687 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7688 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7689 DAG.getConstant(C, DL, MVT::i32));
7690}
7691
Tim Northover3b0846e2014-05-24 12:50:23 +00007692/// An EXTR instruction is made up of two shifts, ORed together. This helper
7693/// searches for and classifies those shifts.
7694static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7695 bool &FromHi) {
7696 if (N.getOpcode() == ISD::SHL)
7697 FromHi = false;
7698 else if (N.getOpcode() == ISD::SRL)
7699 FromHi = true;
7700 else
7701 return false;
7702
7703 if (!isa<ConstantSDNode>(N.getOperand(1)))
7704 return false;
7705
7706 ShiftAmount = N->getConstantOperandVal(1);
7707 Src = N->getOperand(0);
7708 return true;
7709}
7710
7711/// EXTR instruction extracts a contiguous chunk of bits from two existing
7712/// registers viewed as a high/low pair. This function looks for the pattern:
7713/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7714/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7715/// independent.
7716static SDValue tryCombineToEXTR(SDNode *N,
7717 TargetLowering::DAGCombinerInfo &DCI) {
7718 SelectionDAG &DAG = DCI.DAG;
7719 SDLoc DL(N);
7720 EVT VT = N->getValueType(0);
7721
7722 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7723
7724 if (VT != MVT::i32 && VT != MVT::i64)
7725 return SDValue();
7726
7727 SDValue LHS;
7728 uint32_t ShiftLHS = 0;
7729 bool LHSFromHi = 0;
7730 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7731 return SDValue();
7732
7733 SDValue RHS;
7734 uint32_t ShiftRHS = 0;
7735 bool RHSFromHi = 0;
7736 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7737 return SDValue();
7738
7739 // If they're both trying to come from the high part of the register, they're
7740 // not really an EXTR.
7741 if (LHSFromHi == RHSFromHi)
7742 return SDValue();
7743
7744 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7745 return SDValue();
7746
7747 if (LHSFromHi) {
7748 std::swap(LHS, RHS);
7749 std::swap(ShiftLHS, ShiftRHS);
7750 }
7751
7752 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007753 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007754}
7755
7756static SDValue tryCombineToBSL(SDNode *N,
7757 TargetLowering::DAGCombinerInfo &DCI) {
7758 EVT VT = N->getValueType(0);
7759 SelectionDAG &DAG = DCI.DAG;
7760 SDLoc DL(N);
7761
7762 if (!VT.isVector())
7763 return SDValue();
7764
7765 SDValue N0 = N->getOperand(0);
7766 if (N0.getOpcode() != ISD::AND)
7767 return SDValue();
7768
7769 SDValue N1 = N->getOperand(1);
7770 if (N1.getOpcode() != ISD::AND)
7771 return SDValue();
7772
7773 // We only have to look for constant vectors here since the general, variable
7774 // case can be handled in TableGen.
7775 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7776 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7777 for (int i = 1; i >= 0; --i)
7778 for (int j = 1; j >= 0; --j) {
7779 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7780 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7781 if (!BVN0 || !BVN1)
7782 continue;
7783
7784 bool FoundMatch = true;
7785 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7786 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7787 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7788 if (!CN0 || !CN1 ||
7789 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7790 FoundMatch = false;
7791 break;
7792 }
7793 }
7794
7795 if (FoundMatch)
7796 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7797 N0->getOperand(1 - i), N1->getOperand(1 - j));
7798 }
7799
7800 return SDValue();
7801}
7802
7803static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7804 const AArch64Subtarget *Subtarget) {
7805 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7806 if (!EnableAArch64ExtrGeneration)
7807 return SDValue();
7808 SelectionDAG &DAG = DCI.DAG;
7809 EVT VT = N->getValueType(0);
7810
7811 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7812 return SDValue();
7813
7814 SDValue Res = tryCombineToEXTR(N, DCI);
7815 if (Res.getNode())
7816 return Res;
7817
7818 Res = tryCombineToBSL(N, DCI);
7819 if (Res.getNode())
7820 return Res;
7821
7822 return SDValue();
7823}
7824
7825static SDValue performBitcastCombine(SDNode *N,
7826 TargetLowering::DAGCombinerInfo &DCI,
7827 SelectionDAG &DAG) {
7828 // Wait 'til after everything is legalized to try this. That way we have
7829 // legal vector types and such.
7830 if (DCI.isBeforeLegalizeOps())
7831 return SDValue();
7832
7833 // Remove extraneous bitcasts around an extract_subvector.
7834 // For example,
7835 // (v4i16 (bitconvert
7836 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7837 // becomes
7838 // (extract_subvector ((v8i16 ...), (i64 4)))
7839
7840 // Only interested in 64-bit vectors as the ultimate result.
7841 EVT VT = N->getValueType(0);
7842 if (!VT.isVector())
7843 return SDValue();
7844 if (VT.getSimpleVT().getSizeInBits() != 64)
7845 return SDValue();
7846 // Is the operand an extract_subvector starting at the beginning or halfway
7847 // point of the vector? A low half may also come through as an
7848 // EXTRACT_SUBREG, so look for that, too.
7849 SDValue Op0 = N->getOperand(0);
7850 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7851 !(Op0->isMachineOpcode() &&
7852 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7853 return SDValue();
7854 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7855 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7856 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7857 return SDValue();
7858 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7859 if (idx != AArch64::dsub)
7860 return SDValue();
7861 // The dsub reference is equivalent to a lane zero subvector reference.
7862 idx = 0;
7863 }
7864 // Look through the bitcast of the input to the extract.
7865 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7866 return SDValue();
7867 SDValue Source = Op0->getOperand(0)->getOperand(0);
7868 // If the source type has twice the number of elements as our destination
7869 // type, we know this is an extract of the high or low half of the vector.
7870 EVT SVT = Source->getValueType(0);
7871 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7872 return SDValue();
7873
7874 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7875
7876 // Create the simplified form to just extract the low or high half of the
7877 // vector directly rather than bothering with the bitcasts.
7878 SDLoc dl(N);
7879 unsigned NumElements = VT.getVectorNumElements();
7880 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007881 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007882 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7883 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007884 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007885 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7886 Source, SubReg),
7887 0);
7888 }
7889}
7890
7891static SDValue performConcatVectorsCombine(SDNode *N,
7892 TargetLowering::DAGCombinerInfo &DCI,
7893 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007894 SDLoc dl(N);
7895 EVT VT = N->getValueType(0);
7896 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7897
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007898 // Optimize concat_vectors of truncated vectors, where the intermediate
7899 // type is illegal, to avoid said illegality, e.g.,
7900 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7901 // (v2i16 (truncate (v2i64)))))
7902 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007903 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7904 // (v4i32 (bitcast (v2i64))),
7905 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007906 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7907 // on both input and result type, so we might generate worse code.
7908 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7909 if (N->getNumOperands() == 2 &&
7910 N0->getOpcode() == ISD::TRUNCATE &&
7911 N1->getOpcode() == ISD::TRUNCATE) {
7912 SDValue N00 = N0->getOperand(0);
7913 SDValue N10 = N1->getOperand(0);
7914 EVT N00VT = N00.getValueType();
7915
7916 if (N00VT == N10.getValueType() &&
7917 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7918 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007919 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7920 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7921 for (size_t i = 0; i < Mask.size(); ++i)
7922 Mask[i] = i * 2;
7923 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7924 DAG.getVectorShuffle(
7925 MidVT, dl,
7926 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7927 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007928 }
7929 }
7930
Tim Northover3b0846e2014-05-24 12:50:23 +00007931 // Wait 'til after everything is legalized to try this. That way we have
7932 // legal vector types and such.
7933 if (DCI.isBeforeLegalizeOps())
7934 return SDValue();
7935
Tim Northover3b0846e2014-05-24 12:50:23 +00007936 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7937 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7938 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007939 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007940 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007941 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007942 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007943 }
7944
7945 // Canonicalise concat_vectors so that the right-hand vector has as few
7946 // bit-casts as possible before its real operation. The primary matching
7947 // destination for these operations will be the narrowing "2" instructions,
7948 // which depend on the operation being performed on this right-hand vector.
7949 // For example,
7950 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7951 // becomes
7952 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7953
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007954 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00007955 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007956 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007957 MVT RHSTy = RHS.getValueType().getSimpleVT();
7958 // If the RHS is not a vector, this is not the pattern we're looking for.
7959 if (!RHSTy.isVector())
7960 return SDValue();
7961
7962 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7963
7964 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7965 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007966 return DAG.getNode(ISD::BITCAST, dl, VT,
7967 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7968 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7969 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00007970}
7971
7972static SDValue tryCombineFixedPointConvert(SDNode *N,
7973 TargetLowering::DAGCombinerInfo &DCI,
7974 SelectionDAG &DAG) {
7975 // Wait 'til after everything is legalized to try this. That way we have
7976 // legal vector types and such.
7977 if (DCI.isBeforeLegalizeOps())
7978 return SDValue();
7979 // Transform a scalar conversion of a value from a lane extract into a
7980 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7981 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7982 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7983 //
7984 // The second form interacts better with instruction selection and the
7985 // register allocator to avoid cross-class register copies that aren't
7986 // coalescable due to a lane reference.
7987
7988 // Check the operand and see if it originates from a lane extract.
7989 SDValue Op1 = N->getOperand(1);
7990 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7991 // Yep, no additional predication needed. Perform the transform.
7992 SDValue IID = N->getOperand(0);
7993 SDValue Shift = N->getOperand(2);
7994 SDValue Vec = Op1.getOperand(0);
7995 SDValue Lane = Op1.getOperand(1);
7996 EVT ResTy = N->getValueType(0);
7997 EVT VecResTy;
7998 SDLoc DL(N);
7999
8000 // The vector width should be 128 bits by the time we get here, even
8001 // if it started as 64 bits (the extract_vector handling will have
8002 // done so).
8003 assert(Vec.getValueType().getSizeInBits() == 128 &&
8004 "unexpected vector size on extract_vector_elt!");
8005 if (Vec.getValueType() == MVT::v4i32)
8006 VecResTy = MVT::v4f32;
8007 else if (Vec.getValueType() == MVT::v2i64)
8008 VecResTy = MVT::v2f64;
8009 else
Craig Topper2a30d782014-06-18 05:05:13 +00008010 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008011
8012 SDValue Convert =
8013 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8014 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8015 }
8016 return SDValue();
8017}
8018
8019// AArch64 high-vector "long" operations are formed by performing the non-high
8020// version on an extract_subvector of each operand which gets the high half:
8021//
8022// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8023//
8024// However, there are cases which don't have an extract_high explicitly, but
8025// have another operation that can be made compatible with one for free. For
8026// example:
8027//
8028// (dupv64 scalar) --> (extract_high (dup128 scalar))
8029//
8030// This routine does the actual conversion of such DUPs, once outer routines
8031// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008032// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8033// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008034static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008035 switch (N.getOpcode()) {
8036 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008037 case AArch64ISD::DUPLANE8:
8038 case AArch64ISD::DUPLANE16:
8039 case AArch64ISD::DUPLANE32:
8040 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008041 case AArch64ISD::MOVI:
8042 case AArch64ISD::MOVIshift:
8043 case AArch64ISD::MOVIedit:
8044 case AArch64ISD::MOVImsl:
8045 case AArch64ISD::MVNIshift:
8046 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008047 break;
8048 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008049 // FMOV could be supported, but isn't very useful, as it would only occur
8050 // if you passed a bitcast' floating point immediate to an eligible long
8051 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008052 return SDValue();
8053 }
8054
8055 MVT NarrowTy = N.getSimpleValueType();
8056 if (!NarrowTy.is64BitVector())
8057 return SDValue();
8058
8059 MVT ElementTy = NarrowTy.getVectorElementType();
8060 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008061 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008062
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008063 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008064 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8065 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008066 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008067}
8068
8069static bool isEssentiallyExtractSubvector(SDValue N) {
8070 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8071 return true;
8072
8073 return N.getOpcode() == ISD::BITCAST &&
8074 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8075}
8076
8077/// \brief Helper structure to keep track of ISD::SET_CC operands.
8078struct GenericSetCCInfo {
8079 const SDValue *Opnd0;
8080 const SDValue *Opnd1;
8081 ISD::CondCode CC;
8082};
8083
8084/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8085struct AArch64SetCCInfo {
8086 const SDValue *Cmp;
8087 AArch64CC::CondCode CC;
8088};
8089
8090/// \brief Helper structure to keep track of SetCC information.
8091union SetCCInfo {
8092 GenericSetCCInfo Generic;
8093 AArch64SetCCInfo AArch64;
8094};
8095
8096/// \brief Helper structure to be able to read SetCC information. If set to
8097/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8098/// GenericSetCCInfo.
8099struct SetCCInfoAndKind {
8100 SetCCInfo Info;
8101 bool IsAArch64;
8102};
8103
8104/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8105/// an
8106/// AArch64 lowered one.
8107/// \p SetCCInfo is filled accordingly.
8108/// \post SetCCInfo is meanginfull only when this function returns true.
8109/// \return True when Op is a kind of SET_CC operation.
8110static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8111 // If this is a setcc, this is straight forward.
8112 if (Op.getOpcode() == ISD::SETCC) {
8113 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8114 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8115 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8116 SetCCInfo.IsAArch64 = false;
8117 return true;
8118 }
8119 // Otherwise, check if this is a matching csel instruction.
8120 // In other words:
8121 // - csel 1, 0, cc
8122 // - csel 0, 1, !cc
8123 if (Op.getOpcode() != AArch64ISD::CSEL)
8124 return false;
8125 // Set the information about the operands.
8126 // TODO: we want the operands of the Cmp not the csel
8127 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8128 SetCCInfo.IsAArch64 = true;
8129 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8130 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8131
8132 // Check that the operands matches the constraints:
8133 // (1) Both operands must be constants.
8134 // (2) One must be 1 and the other must be 0.
8135 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8136 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8137
8138 // Check (1).
8139 if (!TValue || !FValue)
8140 return false;
8141
8142 // Check (2).
8143 if (!TValue->isOne()) {
8144 // Update the comparison when we are interested in !cc.
8145 std::swap(TValue, FValue);
8146 SetCCInfo.Info.AArch64.CC =
8147 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8148 }
8149 return TValue->isOne() && FValue->isNullValue();
8150}
8151
8152// Returns true if Op is setcc or zext of setcc.
8153static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8154 if (isSetCC(Op, Info))
8155 return true;
8156 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8157 isSetCC(Op->getOperand(0), Info));
8158}
8159
8160// The folding we want to perform is:
8161// (add x, [zext] (setcc cc ...) )
8162// -->
8163// (csel x, (add x, 1), !cc ...)
8164//
8165// The latter will get matched to a CSINC instruction.
8166static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8167 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8168 SDValue LHS = Op->getOperand(0);
8169 SDValue RHS = Op->getOperand(1);
8170 SetCCInfoAndKind InfoAndKind;
8171
8172 // If neither operand is a SET_CC, give up.
8173 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8174 std::swap(LHS, RHS);
8175 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8176 return SDValue();
8177 }
8178
8179 // FIXME: This could be generatized to work for FP comparisons.
8180 EVT CmpVT = InfoAndKind.IsAArch64
8181 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8182 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8183 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8184 return SDValue();
8185
8186 SDValue CCVal;
8187 SDValue Cmp;
8188 SDLoc dl(Op);
8189 if (InfoAndKind.IsAArch64) {
8190 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008191 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8192 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008193 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8194 } else
8195 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8196 *InfoAndKind.Info.Generic.Opnd1,
8197 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8198 CCVal, DAG, dl);
8199
8200 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008201 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008202 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8203}
8204
8205// The basic add/sub long vector instructions have variants with "2" on the end
8206// which act on the high-half of their inputs. They are normally matched by
8207// patterns like:
8208//
8209// (add (zeroext (extract_high LHS)),
8210// (zeroext (extract_high RHS)))
8211// -> uaddl2 vD, vN, vM
8212//
8213// However, if one of the extracts is something like a duplicate, this
8214// instruction can still be used profitably. This function puts the DAG into a
8215// more appropriate form for those patterns to trigger.
8216static SDValue performAddSubLongCombine(SDNode *N,
8217 TargetLowering::DAGCombinerInfo &DCI,
8218 SelectionDAG &DAG) {
8219 if (DCI.isBeforeLegalizeOps())
8220 return SDValue();
8221
8222 MVT VT = N->getSimpleValueType(0);
8223 if (!VT.is128BitVector()) {
8224 if (N->getOpcode() == ISD::ADD)
8225 return performSetccAddFolding(N, DAG);
8226 return SDValue();
8227 }
8228
8229 // Make sure both branches are extended in the same way.
8230 SDValue LHS = N->getOperand(0);
8231 SDValue RHS = N->getOperand(1);
8232 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8233 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8234 LHS.getOpcode() != RHS.getOpcode())
8235 return SDValue();
8236
8237 unsigned ExtType = LHS.getOpcode();
8238
8239 // It's not worth doing if at least one of the inputs isn't already an
8240 // extract, but we don't know which it'll be so we have to try both.
8241 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8242 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8243 if (!RHS.getNode())
8244 return SDValue();
8245
8246 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8247 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8248 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8249 if (!LHS.getNode())
8250 return SDValue();
8251
8252 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8253 }
8254
8255 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8256}
8257
8258// Massage DAGs which we can use the high-half "long" operations on into
8259// something isel will recognize better. E.g.
8260//
8261// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8262// (aarch64_neon_umull (extract_high (v2i64 vec)))
8263// (extract_high (v2i64 (dup128 scalar)))))
8264//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008265static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008266 TargetLowering::DAGCombinerInfo &DCI,
8267 SelectionDAG &DAG) {
8268 if (DCI.isBeforeLegalizeOps())
8269 return SDValue();
8270
Hal Finkelcd8664c2015-12-11 23:11:52 +00008271 SDValue LHS = N->getOperand(1);
8272 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008273 assert(LHS.getValueType().is64BitVector() &&
8274 RHS.getValueType().is64BitVector() &&
8275 "unexpected shape for long operation");
8276
8277 // Either node could be a DUP, but it's not worth doing both of them (you'd
8278 // just as well use the non-high version) so look for a corresponding extract
8279 // operation on the other "wing".
8280 if (isEssentiallyExtractSubvector(LHS)) {
8281 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8282 if (!RHS.getNode())
8283 return SDValue();
8284 } else if (isEssentiallyExtractSubvector(RHS)) {
8285 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8286 if (!LHS.getNode())
8287 return SDValue();
8288 }
8289
Hal Finkelcd8664c2015-12-11 23:11:52 +00008290 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8291 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008292}
8293
8294static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8295 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8296 unsigned ElemBits = ElemTy.getSizeInBits();
8297
8298 int64_t ShiftAmount;
8299 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8300 APInt SplatValue, SplatUndef;
8301 unsigned SplatBitSize;
8302 bool HasAnyUndefs;
8303 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8304 HasAnyUndefs, ElemBits) ||
8305 SplatBitSize != ElemBits)
8306 return SDValue();
8307
8308 ShiftAmount = SplatValue.getSExtValue();
8309 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8310 ShiftAmount = CVN->getSExtValue();
8311 } else
8312 return SDValue();
8313
8314 unsigned Opcode;
8315 bool IsRightShift;
8316 switch (IID) {
8317 default:
8318 llvm_unreachable("Unknown shift intrinsic");
8319 case Intrinsic::aarch64_neon_sqshl:
8320 Opcode = AArch64ISD::SQSHL_I;
8321 IsRightShift = false;
8322 break;
8323 case Intrinsic::aarch64_neon_uqshl:
8324 Opcode = AArch64ISD::UQSHL_I;
8325 IsRightShift = false;
8326 break;
8327 case Intrinsic::aarch64_neon_srshl:
8328 Opcode = AArch64ISD::SRSHR_I;
8329 IsRightShift = true;
8330 break;
8331 case Intrinsic::aarch64_neon_urshl:
8332 Opcode = AArch64ISD::URSHR_I;
8333 IsRightShift = true;
8334 break;
8335 case Intrinsic::aarch64_neon_sqshlu:
8336 Opcode = AArch64ISD::SQSHLU_I;
8337 IsRightShift = false;
8338 break;
8339 }
8340
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008341 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8342 SDLoc dl(N);
8343 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8344 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8345 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8346 SDLoc dl(N);
8347 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8348 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8349 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008350
8351 return SDValue();
8352}
8353
8354// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8355// the intrinsics must be legal and take an i32, this means there's almost
8356// certainly going to be a zext in the DAG which we can eliminate.
8357static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8358 SDValue AndN = N->getOperand(2);
8359 if (AndN.getOpcode() != ISD::AND)
8360 return SDValue();
8361
8362 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8363 if (!CMask || CMask->getZExtValue() != Mask)
8364 return SDValue();
8365
8366 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8367 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8368}
8369
Ahmed Bougachafab58922015-03-10 20:45:38 +00008370static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8371 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008372 SDLoc dl(N);
8373 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8374 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008375 N->getOperand(1).getSimpleValueType(),
8376 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008377 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008378}
8379
Tim Northover3b0846e2014-05-24 12:50:23 +00008380static SDValue performIntrinsicCombine(SDNode *N,
8381 TargetLowering::DAGCombinerInfo &DCI,
8382 const AArch64Subtarget *Subtarget) {
8383 SelectionDAG &DAG = DCI.DAG;
8384 unsigned IID = getIntrinsicID(N);
8385 switch (IID) {
8386 default:
8387 break;
8388 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8389 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8390 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008391 case Intrinsic::aarch64_neon_saddv:
8392 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8393 case Intrinsic::aarch64_neon_uaddv:
8394 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8395 case Intrinsic::aarch64_neon_sminv:
8396 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8397 case Intrinsic::aarch64_neon_uminv:
8398 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8399 case Intrinsic::aarch64_neon_smaxv:
8400 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8401 case Intrinsic::aarch64_neon_umaxv:
8402 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008403 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008404 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008405 N->getOperand(1), N->getOperand(2));
8406 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008407 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008408 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008409 case Intrinsic::aarch64_neon_fmaxnm:
8410 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8411 N->getOperand(1), N->getOperand(2));
8412 case Intrinsic::aarch64_neon_fminnm:
8413 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8414 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008415 case Intrinsic::aarch64_neon_smull:
8416 case Intrinsic::aarch64_neon_umull:
8417 case Intrinsic::aarch64_neon_pmull:
8418 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008419 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008420 case Intrinsic::aarch64_neon_sqshl:
8421 case Intrinsic::aarch64_neon_uqshl:
8422 case Intrinsic::aarch64_neon_sqshlu:
8423 case Intrinsic::aarch64_neon_srshl:
8424 case Intrinsic::aarch64_neon_urshl:
8425 return tryCombineShiftImm(IID, N, DAG);
8426 case Intrinsic::aarch64_crc32b:
8427 case Intrinsic::aarch64_crc32cb:
8428 return tryCombineCRC32(0xff, N, DAG);
8429 case Intrinsic::aarch64_crc32h:
8430 case Intrinsic::aarch64_crc32ch:
8431 return tryCombineCRC32(0xffff, N, DAG);
8432 }
8433 return SDValue();
8434}
8435
8436static SDValue performExtendCombine(SDNode *N,
8437 TargetLowering::DAGCombinerInfo &DCI,
8438 SelectionDAG &DAG) {
8439 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8440 // we can convert that DUP into another extract_high (of a bigger DUP), which
8441 // helps the backend to decide that an sabdl2 would be useful, saving a real
8442 // extract_high operation.
8443 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008444 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008445 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008446 unsigned IID = getIntrinsicID(ABDNode);
8447 if (IID == Intrinsic::aarch64_neon_sabd ||
8448 IID == Intrinsic::aarch64_neon_uabd) {
8449 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8450 if (!NewABD.getNode())
8451 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008452
Hal Finkelcd8664c2015-12-11 23:11:52 +00008453 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8454 NewABD);
8455 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008456 }
8457
8458 // This is effectively a custom type legalization for AArch64.
8459 //
8460 // Type legalization will split an extend of a small, legal, type to a larger
8461 // illegal type by first splitting the destination type, often creating
8462 // illegal source types, which then get legalized in isel-confusing ways,
8463 // leading to really terrible codegen. E.g.,
8464 // %result = v8i32 sext v8i8 %value
8465 // becomes
8466 // %losrc = extract_subreg %value, ...
8467 // %hisrc = extract_subreg %value, ...
8468 // %lo = v4i32 sext v4i8 %losrc
8469 // %hi = v4i32 sext v4i8 %hisrc
8470 // Things go rapidly downhill from there.
8471 //
8472 // For AArch64, the [sz]ext vector instructions can only go up one element
8473 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8474 // take two instructions.
8475 //
8476 // This implies that the most efficient way to do the extend from v8i8
8477 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8478 // the normal splitting to happen for the v8i16->v8i32.
8479
8480 // This is pre-legalization to catch some cases where the default
8481 // type legalization will create ill-tempered code.
8482 if (!DCI.isBeforeLegalizeOps())
8483 return SDValue();
8484
8485 // We're only interested in cleaning things up for non-legal vector types
8486 // here. If both the source and destination are legal, things will just
8487 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008488 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008489 EVT ResVT = N->getValueType(0);
8490 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8491 return SDValue();
8492 // If the vector type isn't a simple VT, it's beyond the scope of what
8493 // we're worried about here. Let legalization do its thing and hope for
8494 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008495 SDValue Src = N->getOperand(0);
8496 EVT SrcVT = Src->getValueType(0);
8497 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008498 return SDValue();
8499
Tim Northover3b0846e2014-05-24 12:50:23 +00008500 // If the source VT is a 64-bit vector, we can play games and get the
8501 // better results we want.
8502 if (SrcVT.getSizeInBits() != 64)
8503 return SDValue();
8504
8505 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8506 unsigned ElementCount = SrcVT.getVectorNumElements();
8507 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8508 SDLoc DL(N);
8509 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8510
8511 // Now split the rest of the operation into two halves, each with a 64
8512 // bit source.
8513 EVT LoVT, HiVT;
8514 SDValue Lo, Hi;
8515 unsigned NumElements = ResVT.getVectorNumElements();
8516 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8517 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8518 ResVT.getVectorElementType(), NumElements / 2);
8519
8520 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8521 LoVT.getVectorNumElements());
8522 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008523 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008524 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008525 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008526 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8527 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8528
8529 // Now combine the parts back together so we still have a single result
8530 // like the combiner expects.
8531 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8532}
8533
8534/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8535/// value. The load store optimizer pass will merge them to store pair stores.
8536/// This has better performance than a splat of the scalar followed by a split
8537/// vector store. Even if the stores are not merged it is four stores vs a dup,
8538/// followed by an ext.b and two stores.
8539static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8540 SDValue StVal = St->getValue();
8541 EVT VT = StVal.getValueType();
8542
8543 // Don't replace floating point stores, they possibly won't be transformed to
8544 // stp because of the store pair suppress pass.
8545 if (VT.isFloatingPoint())
8546 return SDValue();
8547
8548 // Check for insert vector elements.
8549 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8550 return SDValue();
8551
8552 // We can express a splat as store pair(s) for 2 or 4 elements.
8553 unsigned NumVecElts = VT.getVectorNumElements();
8554 if (NumVecElts != 4 && NumVecElts != 2)
8555 return SDValue();
8556 SDValue SplatVal = StVal.getOperand(1);
8557 unsigned RemainInsertElts = NumVecElts - 1;
8558
8559 // Check that this is a splat.
8560 while (--RemainInsertElts) {
8561 SDValue NextInsertElt = StVal.getOperand(0);
8562 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8563 return SDValue();
8564 if (NextInsertElt.getOperand(1) != SplatVal)
8565 return SDValue();
8566 StVal = NextInsertElt;
8567 }
8568 unsigned OrigAlignment = St->getAlignment();
8569 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8570 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8571
8572 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008573 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008574 // Most of the time the three stores should be replaced by store pair
8575 // instructions (stp).
8576 SDLoc DL(St);
8577 SDValue BasePtr = St->getBasePtr();
8578 SDValue NewST1 =
8579 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8580 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8581
8582 unsigned Offset = EltOffset;
8583 while (--NumVecElts) {
8584 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008585 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008586 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8587 St->getPointerInfo(), St->isVolatile(),
8588 St->isNonTemporal(), Alignment);
8589 Offset += EltOffset;
8590 }
8591 return NewST1;
8592}
8593
Tim Northover339c83e2015-11-10 00:44:23 +00008594static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8595 SelectionDAG &DAG,
8596 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008597 if (!DCI.isBeforeLegalize())
8598 return SDValue();
8599
8600 StoreSDNode *S = cast<StoreSDNode>(N);
8601 if (S->isVolatile())
8602 return SDValue();
8603
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008604 // FIXME: The logic for deciding if an unaligned store should be split should
8605 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8606 // a call to that function here.
8607
Tim Northover3b0846e2014-05-24 12:50:23 +00008608 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008609 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008610 if (!Subtarget->isCyclone())
8611 return SDValue();
8612
Sanjay Patel924879a2015-08-04 15:49:57 +00008613 // Don't split at -Oz.
8614 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008615 return SDValue();
8616
8617 SDValue StVal = S->getValue();
8618 EVT VT = StVal.getValueType();
8619
8620 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8621 // those up regresses performance on micro-benchmarks and olden/bh.
8622 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8623 return SDValue();
8624
8625 // Split unaligned 16B stores. They are terrible for performance.
8626 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8627 // extensions can use this to mark that it does not want splitting to happen
8628 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8629 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8630 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8631 S->getAlignment() <= 2)
8632 return SDValue();
8633
8634 // If we get a splat of a scalar convert this vector store to a store of
8635 // scalars. They will be merged into store pairs thereby removing two
8636 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008637 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008638 return ReplacedSplat;
8639
8640 SDLoc DL(S);
8641 unsigned NumElts = VT.getVectorNumElements() / 2;
8642 // Split VT into two.
8643 EVT HalfVT =
8644 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8645 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008646 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008647 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008648 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008649 SDValue BasePtr = S->getBasePtr();
8650 SDValue NewST1 =
8651 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8652 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8653 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008654 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008655 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8656 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8657 S->getAlignment());
8658}
8659
8660/// Target-specific DAG combine function for post-increment LD1 (lane) and
8661/// post-increment LD1R.
8662static SDValue performPostLD1Combine(SDNode *N,
8663 TargetLowering::DAGCombinerInfo &DCI,
8664 bool IsLaneOp) {
8665 if (DCI.isBeforeLegalizeOps())
8666 return SDValue();
8667
8668 SelectionDAG &DAG = DCI.DAG;
8669 EVT VT = N->getValueType(0);
8670
8671 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8672 SDNode *LD = N->getOperand(LoadIdx).getNode();
8673 // If it is not LOAD, can not do such combine.
8674 if (LD->getOpcode() != ISD::LOAD)
8675 return SDValue();
8676
8677 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8678 EVT MemVT = LoadSDN->getMemoryVT();
8679 // Check if memory operand is the same type as the vector element.
8680 if (MemVT != VT.getVectorElementType())
8681 return SDValue();
8682
8683 // Check if there are other uses. If so, do not combine as it will introduce
8684 // an extra load.
8685 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8686 ++UI) {
8687 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8688 continue;
8689 if (*UI != N)
8690 return SDValue();
8691 }
8692
8693 SDValue Addr = LD->getOperand(1);
8694 SDValue Vector = N->getOperand(0);
8695 // Search for a use of the address operand that is an increment.
8696 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8697 Addr.getNode()->use_end(); UI != UE; ++UI) {
8698 SDNode *User = *UI;
8699 if (User->getOpcode() != ISD::ADD
8700 || UI.getUse().getResNo() != Addr.getResNo())
8701 continue;
8702
8703 // Check that the add is independent of the load. Otherwise, folding it
8704 // would create a cycle.
8705 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8706 continue;
8707 // Also check that add is not used in the vector operand. This would also
8708 // create a cycle.
8709 if (User->isPredecessorOf(Vector.getNode()))
8710 continue;
8711
8712 // If the increment is a constant, it must match the memory ref size.
8713 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8714 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8715 uint32_t IncVal = CInc->getZExtValue();
8716 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8717 if (IncVal != NumBytes)
8718 continue;
8719 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8720 }
8721
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008722 // Finally, check that the vector doesn't depend on the load.
8723 // Again, this would create a cycle.
8724 // The load depending on the vector is fine, as that's the case for the
8725 // LD1*post we'll eventually generate anyway.
8726 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8727 continue;
8728
Tim Northover3b0846e2014-05-24 12:50:23 +00008729 SmallVector<SDValue, 8> Ops;
8730 Ops.push_back(LD->getOperand(0)); // Chain
8731 if (IsLaneOp) {
8732 Ops.push_back(Vector); // The vector to be inserted
8733 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8734 }
8735 Ops.push_back(Addr);
8736 Ops.push_back(Inc);
8737
8738 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008739 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008740 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8741 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8742 MemVT,
8743 LoadSDN->getMemOperand());
8744
8745 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008746 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008747 NewResults.push_back(SDValue(LD, 0)); // The result of load
8748 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8749 DCI.CombineTo(LD, NewResults);
8750 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8751 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8752
8753 break;
8754 }
8755 return SDValue();
8756}
8757
Tim Northover339c83e2015-11-10 00:44:23 +00008758/// Simplify \Addr given that the top byte of it is ignored by HW during
8759/// address translation.
8760static bool performTBISimplification(SDValue Addr,
8761 TargetLowering::DAGCombinerInfo &DCI,
8762 SelectionDAG &DAG) {
8763 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8764 APInt KnownZero, KnownOne;
8765 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8766 DCI.isBeforeLegalizeOps());
8767 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8768 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8769 DCI.CommitTargetLoweringOpt(TLO);
8770 return true;
8771 }
8772 return false;
8773}
8774
8775static SDValue performSTORECombine(SDNode *N,
8776 TargetLowering::DAGCombinerInfo &DCI,
8777 SelectionDAG &DAG,
8778 const AArch64Subtarget *Subtarget) {
8779 SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8780 if (Split.getNode())
8781 return Split;
8782
8783 if (Subtarget->supportsAddressTopByteIgnored() &&
8784 performTBISimplification(N->getOperand(2), DCI, DAG))
8785 return SDValue(N, 0);
8786
8787 return SDValue();
8788}
8789
8790 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008791/// LoopVectorizer for the across vector reduction. It consists of
8792/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8793/// are reduced, where s is an induction variable from 0 to
8794/// log2(NumVectorElements).
8795static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8796 unsigned Op,
8797 SelectionDAG &DAG) {
8798 EVT VTy = OpV->getOperand(0).getValueType();
8799 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008800 return SDValue();
8801
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008802 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008803 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8804 if (NumVecElts != 4)
8805 return SDValue();
8806 } else {
8807 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8808 return SDValue();
8809 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008810
8811 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008812 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008813 // Iterate over each step of the across vector reduction.
8814 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008815 SDValue CurOp = PreOp.getOperand(0);
8816 SDValue Shuffle = PreOp.getOperand(1);
8817 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008818 // Try to swap the 1st and 2nd operand as add and min/max instructions
8819 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008820 CurOp = PreOp.getOperand(1);
8821 Shuffle = PreOp.getOperand(0);
8822 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8823 return SDValue();
8824 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008825
8826 // Check if the input vector is fed by the operator we want to handle,
8827 // except the last step; the very first input vector is not necessarily
8828 // the same operator we are handling.
8829 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8830 return SDValue();
8831
Chad Rosier6c36eff2015-09-03 18:13:57 +00008832 // Check if it forms one step of the across vector reduction.
8833 // E.g.,
8834 // %cur = add %1, %0
8835 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8836 // %pre = add %cur, %shuffle
8837 if (Shuffle.getOperand(0) != CurOp)
8838 return SDValue();
8839
8840 int NumMaskElts = 1 << CurStep;
8841 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8842 // Check mask values in each step.
8843 // We expect the shuffle mask in each step follows a specific pattern
8844 // denoted here by the <M, U> form, where M is a sequence of integers
8845 // starting from NumMaskElts, increasing by 1, and the number integers
8846 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8847 // of undef in U should be NumVecElts - NumMaskElts.
8848 // E.g., for <8 x i16>, mask values in each step should be :
8849 // step 0 : <1,u,u,u,u,u,u,u>
8850 // step 1 : <2,3,u,u,u,u,u,u>
8851 // step 2 : <4,5,6,7,u,u,u,u>
8852 for (int i = 0; i < NumVecElts; ++i)
8853 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8854 (i >= NumMaskElts && !(Mask[i] < 0)))
8855 return SDValue();
8856
8857 PreOp = CurOp;
8858 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008859 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008860 bool IsIntrinsic = false;
8861
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008862 switch (Op) {
8863 default:
8864 llvm_unreachable("Unexpected operator for across vector reduction");
8865 case ISD::ADD:
8866 Opcode = AArch64ISD::UADDV;
8867 break;
8868 case ISD::SMAX:
8869 Opcode = AArch64ISD::SMAXV;
8870 break;
8871 case ISD::UMAX:
8872 Opcode = AArch64ISD::UMAXV;
8873 break;
8874 case ISD::SMIN:
8875 Opcode = AArch64ISD::SMINV;
8876 break;
8877 case ISD::UMIN:
8878 Opcode = AArch64ISD::UMINV;
8879 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008880 case ISD::FMAXNUM:
8881 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8882 IsIntrinsic = true;
8883 break;
8884 case ISD::FMINNUM:
8885 Opcode = Intrinsic::aarch64_neon_fminnmv;
8886 IsIntrinsic = true;
8887 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008888 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008889 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00008890
8891 return IsIntrinsic
8892 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8893 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8894 : DAG.getNode(
8895 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8896 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8897 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008898}
8899
8900/// Target-specific DAG combine for the across vector min/max reductions.
8901/// This function specifically handles the final clean-up step of the vector
8902/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8903/// pattern, which narrows down and finds the final min/max value from all
8904/// elements of the vector.
8905/// For example, for a <16 x i8> vector :
8906/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8907/// %smax0 = smax %arr, svn0
8908/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8909/// %smax1 = smax %smax0, %svn1
8910/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8911/// %smax2 = smax %smax1, svn2
8912/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8913/// %sc = setcc %smax2, %svn3, gt
8914/// %n0 = extract_vector_elt %sc, #0
8915/// %n1 = extract_vector_elt %smax2, #0
8916/// %n2 = extract_vector_elt $smax2, #1
8917/// %result = select %n0, %n1, n2
8918/// becomes :
8919/// %1 = smaxv %0
8920/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008921static SDValue
8922performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8923 const AArch64Subtarget *Subtarget) {
8924 if (!Subtarget->hasNEON())
8925 return SDValue();
8926
8927 SDValue N0 = N->getOperand(0);
8928 SDValue IfTrue = N->getOperand(1);
8929 SDValue IfFalse = N->getOperand(2);
8930
8931 // Check if the SELECT merges up the final result of the min/max
8932 // from a vector.
8933 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8934 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8935 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8936 return SDValue();
8937
8938 // Expect N0 is fed by SETCC.
8939 SDValue SetCC = N0.getOperand(0);
8940 EVT SetCCVT = SetCC.getValueType();
8941 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8942 SetCCVT.getVectorElementType() != MVT::i1)
8943 return SDValue();
8944
8945 SDValue VectorOp = SetCC.getOperand(0);
8946 unsigned Op = VectorOp->getOpcode();
8947 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00008948 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8949 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008950 return SDValue();
8951
8952 EVT VTy = VectorOp.getValueType();
8953 if (!VTy.isVector())
8954 return SDValue();
8955
Jun Bum Lim0aace132015-10-09 14:11:25 +00008956 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008957 return SDValue();
8958
Jun Bum Lim0aace132015-10-09 14:11:25 +00008959 EVT EltTy = VTy.getVectorElementType();
8960 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8961 if (EltTy != MVT::f32)
8962 return SDValue();
8963 } else {
8964 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8965 return SDValue();
8966 }
8967
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008968 // Check if extracting from the same vector.
8969 // For example,
8970 // %sc = setcc %vector, %svn1, gt
8971 // %n0 = extract_vector_elt %sc, #0
8972 // %n1 = extract_vector_elt %vector, #0
8973 // %n2 = extract_vector_elt $vector, #1
8974 if (!(VectorOp == IfTrue->getOperand(0) &&
8975 VectorOp == IfFalse->getOperand(0)))
8976 return SDValue();
8977
8978 // Check if the condition code is matched with the operator type.
8979 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8980 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8981 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8982 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00008983 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8984 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8985 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8986 CC != ISD::SETGE) ||
8987 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8988 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8989 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008990 return SDValue();
8991
8992 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008993 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008994 return SDValue();
8995
8996 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008997 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008998 return SDValue();
8999
9000 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009001 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009002 return SDValue();
9003
9004 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9005}
9006
9007/// Target-specific DAG combine for the across vector add reduction.
9008/// This function specifically handles the final clean-up step of the vector
9009/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9010/// pattern, which adds all elements of a vector together.
9011/// For example, for a <4 x i32> vector :
9012/// %1 = vector_shuffle %0, <2,3,u,u>
9013/// %2 = add %0, %1
9014/// %3 = vector_shuffle %2, <1,u,u,u>
9015/// %4 = add %2, %3
9016/// %result = extract_vector_elt %4, 0
9017/// becomes :
9018/// %0 = uaddv %0
9019/// %result = extract_vector_elt %0, 0
9020static SDValue
9021performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9022 const AArch64Subtarget *Subtarget) {
9023 if (!Subtarget->hasNEON())
9024 return SDValue();
9025 SDValue N0 = N->getOperand(0);
9026 SDValue N1 = N->getOperand(1);
9027
9028 // Check if the input vector is fed by the ADD.
9029 if (N0->getOpcode() != ISD::ADD)
9030 return SDValue();
9031
9032 // The vector extract idx must constant zero because we only expect the final
9033 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009034 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009035 return SDValue();
9036
9037 EVT VTy = N0.getValueType();
9038 if (!VTy.isVector())
9039 return SDValue();
9040
9041 EVT EltTy = VTy.getVectorElementType();
9042 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9043 return SDValue();
9044
Jun Bum Lim0aace132015-10-09 14:11:25 +00009045 if (VTy.getSizeInBits() < 64)
9046 return SDValue();
9047
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009048 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009049}
9050
Tim Northover3b0846e2014-05-24 12:50:23 +00009051/// Target-specific DAG combine function for NEON load/store intrinsics
9052/// to merge base address updates.
9053static SDValue performNEONPostLDSTCombine(SDNode *N,
9054 TargetLowering::DAGCombinerInfo &DCI,
9055 SelectionDAG &DAG) {
9056 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9057 return SDValue();
9058
9059 unsigned AddrOpIdx = N->getNumOperands() - 1;
9060 SDValue Addr = N->getOperand(AddrOpIdx);
9061
9062 // Search for a use of the address operand that is an increment.
9063 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9064 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9065 SDNode *User = *UI;
9066 if (User->getOpcode() != ISD::ADD ||
9067 UI.getUse().getResNo() != Addr.getResNo())
9068 continue;
9069
9070 // Check that the add is independent of the load/store. Otherwise, folding
9071 // it would create a cycle.
9072 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9073 continue;
9074
9075 // Find the new opcode for the updating load/store.
9076 bool IsStore = false;
9077 bool IsLaneOp = false;
9078 bool IsDupOp = false;
9079 unsigned NewOpc = 0;
9080 unsigned NumVecs = 0;
9081 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9082 switch (IntNo) {
9083 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9084 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9085 NumVecs = 2; break;
9086 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9087 NumVecs = 3; break;
9088 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9089 NumVecs = 4; break;
9090 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9091 NumVecs = 2; IsStore = true; break;
9092 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9093 NumVecs = 3; IsStore = true; break;
9094 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9095 NumVecs = 4; IsStore = true; break;
9096 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9097 NumVecs = 2; break;
9098 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9099 NumVecs = 3; break;
9100 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9101 NumVecs = 4; break;
9102 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9103 NumVecs = 2; IsStore = true; break;
9104 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9105 NumVecs = 3; IsStore = true; break;
9106 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9107 NumVecs = 4; IsStore = true; break;
9108 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9109 NumVecs = 2; IsDupOp = true; break;
9110 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9111 NumVecs = 3; IsDupOp = true; break;
9112 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9113 NumVecs = 4; IsDupOp = true; break;
9114 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9115 NumVecs = 2; IsLaneOp = true; break;
9116 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9117 NumVecs = 3; IsLaneOp = true; break;
9118 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9119 NumVecs = 4; IsLaneOp = true; break;
9120 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9121 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9122 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9123 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9124 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9125 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9126 }
9127
9128 EVT VecTy;
9129 if (IsStore)
9130 VecTy = N->getOperand(2).getValueType();
9131 else
9132 VecTy = N->getValueType(0);
9133
9134 // If the increment is a constant, it must match the memory ref size.
9135 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9136 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9137 uint32_t IncVal = CInc->getZExtValue();
9138 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9139 if (IsLaneOp || IsDupOp)
9140 NumBytes /= VecTy.getVectorNumElements();
9141 if (IncVal != NumBytes)
9142 continue;
9143 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9144 }
9145 SmallVector<SDValue, 8> Ops;
9146 Ops.push_back(N->getOperand(0)); // Incoming chain
9147 // Load lane and store have vector list as input.
9148 if (IsLaneOp || IsStore)
9149 for (unsigned i = 2; i < AddrOpIdx; ++i)
9150 Ops.push_back(N->getOperand(i));
9151 Ops.push_back(Addr); // Base register
9152 Ops.push_back(Inc);
9153
9154 // Return Types.
9155 EVT Tys[6];
9156 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9157 unsigned n;
9158 for (n = 0; n < NumResultVecs; ++n)
9159 Tys[n] = VecTy;
9160 Tys[n++] = MVT::i64; // Type of write back register
9161 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009162 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009163
9164 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9165 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9166 MemInt->getMemoryVT(),
9167 MemInt->getMemOperand());
9168
9169 // Update the uses.
9170 std::vector<SDValue> NewResults;
9171 for (unsigned i = 0; i < NumResultVecs; ++i) {
9172 NewResults.push_back(SDValue(UpdN.getNode(), i));
9173 }
9174 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9175 DCI.CombineTo(N, NewResults);
9176 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9177
9178 break;
9179 }
9180 return SDValue();
9181}
9182
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009183// Checks to see if the value is the prescribed width and returns information
9184// about its extension mode.
9185static
9186bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9187 ExtType = ISD::NON_EXTLOAD;
9188 switch(V.getNode()->getOpcode()) {
9189 default:
9190 return false;
9191 case ISD::LOAD: {
9192 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9193 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9194 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9195 ExtType = LoadNode->getExtensionType();
9196 return true;
9197 }
9198 return false;
9199 }
9200 case ISD::AssertSext: {
9201 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9202 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9203 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9204 ExtType = ISD::SEXTLOAD;
9205 return true;
9206 }
9207 return false;
9208 }
9209 case ISD::AssertZext: {
9210 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9211 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9212 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9213 ExtType = ISD::ZEXTLOAD;
9214 return true;
9215 }
9216 return false;
9217 }
9218 case ISD::Constant:
9219 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00009220 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00009221 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009222 return true;
9223 return false;
9224 }
9225 }
9226
9227 return true;
9228}
9229
9230// This function does a whole lot of voodoo to determine if the tests are
9231// equivalent without and with a mask. Essentially what happens is that given a
9232// DAG resembling:
9233//
9234// +-------------+ +-------------+ +-------------+ +-------------+
9235// | Input | | AddConstant | | CompConstant| | CC |
9236// +-------------+ +-------------+ +-------------+ +-------------+
9237// | | | |
9238// V V | +----------+
9239// +-------------+ +----+ | |
9240// | ADD | |0xff| | |
9241// +-------------+ +----+ | |
9242// | | | |
9243// V V | |
9244// +-------------+ | |
9245// | AND | | |
9246// +-------------+ | |
9247// | | |
9248// +-----+ | |
9249// | | |
9250// V V V
9251// +-------------+
9252// | CMP |
9253// +-------------+
9254//
9255// The AND node may be safely removed for some combinations of inputs. In
9256// particular we need to take into account the extension type of the Input,
9257// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9258// width of the input (this can work for any width inputs, the above graph is
9259// specific to 8 bits.
9260//
9261// The specific equations were worked out by generating output tables for each
9262// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9263// problem was simplified by working with 4 bit inputs, which means we only
9264// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9265// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9266// patterns present in both extensions (0,7). For every distinct set of
9267// AddConstant and CompConstants bit patterns we can consider the masked and
9268// unmasked versions to be equivalent if the result of this function is true for
9269// all 16 distinct bit patterns of for the current extension type of Input (w0).
9270//
9271// sub w8, w0, w1
9272// and w10, w8, #0x0f
9273// cmp w8, w2
9274// cset w9, AArch64CC
9275// cmp w10, w2
9276// cset w11, AArch64CC
9277// cmp w9, w11
9278// cset w0, eq
9279// ret
9280//
9281// Since the above function shows when the outputs are equivalent it defines
9282// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9283// would be expensive to run during compiles. The equations below were written
9284// in a test harness that confirmed they gave equivalent outputs to the above
9285// for all inputs function, so they can be used determine if the removal is
9286// legal instead.
9287//
9288// isEquivalentMaskless() is the code for testing if the AND can be removed
9289// factored out of the DAG recognition as the DAG can take several forms.
9290
9291static
9292bool isEquivalentMaskless(unsigned CC, unsigned width,
9293 ISD::LoadExtType ExtType, signed AddConstant,
9294 signed CompConstant) {
9295 // By being careful about our equations and only writing the in term
9296 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9297 // make them generally applicable to all bit widths.
9298 signed MaxUInt = (1 << width);
9299
9300 // For the purposes of these comparisons sign extending the type is
9301 // equivalent to zero extending the add and displacing it by half the integer
9302 // width. Provided we are careful and make sure our equations are valid over
9303 // the whole range we can just adjust the input and avoid writing equations
9304 // for sign extended inputs.
9305 if (ExtType == ISD::SEXTLOAD)
9306 AddConstant -= (1 << (width-1));
9307
9308 switch(CC) {
9309 case AArch64CC::LE:
9310 case AArch64CC::GT: {
9311 if ((AddConstant == 0) ||
9312 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9313 (AddConstant >= 0 && CompConstant < 0) ||
9314 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9315 return true;
9316 } break;
9317 case AArch64CC::LT:
9318 case AArch64CC::GE: {
9319 if ((AddConstant == 0) ||
9320 (AddConstant >= 0 && CompConstant <= 0) ||
9321 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9322 return true;
9323 } break;
9324 case AArch64CC::HI:
9325 case AArch64CC::LS: {
9326 if ((AddConstant >= 0 && CompConstant < 0) ||
9327 (AddConstant <= 0 && CompConstant >= -1 &&
9328 CompConstant < AddConstant + MaxUInt))
9329 return true;
9330 } break;
9331 case AArch64CC::PL:
9332 case AArch64CC::MI: {
9333 if ((AddConstant == 0) ||
9334 (AddConstant > 0 && CompConstant <= 0) ||
9335 (AddConstant < 0 && CompConstant <= AddConstant))
9336 return true;
9337 } break;
9338 case AArch64CC::LO:
9339 case AArch64CC::HS: {
9340 if ((AddConstant >= 0 && CompConstant <= 0) ||
9341 (AddConstant <= 0 && CompConstant >= 0 &&
9342 CompConstant <= AddConstant + MaxUInt))
9343 return true;
9344 } break;
9345 case AArch64CC::EQ:
9346 case AArch64CC::NE: {
9347 if ((AddConstant > 0 && CompConstant < 0) ||
9348 (AddConstant < 0 && CompConstant >= 0 &&
9349 CompConstant < AddConstant + MaxUInt) ||
9350 (AddConstant >= 0 && CompConstant >= 0 &&
9351 CompConstant >= AddConstant) ||
9352 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9353
9354 return true;
9355 } break;
9356 case AArch64CC::VS:
9357 case AArch64CC::VC:
9358 case AArch64CC::AL:
9359 case AArch64CC::NV:
9360 return true;
9361 case AArch64CC::Invalid:
9362 break;
9363 }
9364
9365 return false;
9366}
9367
9368static
9369SDValue performCONDCombine(SDNode *N,
9370 TargetLowering::DAGCombinerInfo &DCI,
9371 SelectionDAG &DAG, unsigned CCIndex,
9372 unsigned CmpIndex) {
9373 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9374 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9375 unsigned CondOpcode = SubsNode->getOpcode();
9376
9377 if (CondOpcode != AArch64ISD::SUBS)
9378 return SDValue();
9379
9380 // There is a SUBS feeding this condition. Is it fed by a mask we can
9381 // use?
9382
9383 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9384 unsigned MaskBits = 0;
9385
9386 if (AndNode->getOpcode() != ISD::AND)
9387 return SDValue();
9388
9389 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9390 uint32_t CNV = CN->getZExtValue();
9391 if (CNV == 255)
9392 MaskBits = 8;
9393 else if (CNV == 65535)
9394 MaskBits = 16;
9395 }
9396
9397 if (!MaskBits)
9398 return SDValue();
9399
9400 SDValue AddValue = AndNode->getOperand(0);
9401
9402 if (AddValue.getOpcode() != ISD::ADD)
9403 return SDValue();
9404
9405 // The basic dag structure is correct, grab the inputs and validate them.
9406
9407 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9408 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9409 SDValue SubsInputValue = SubsNode->getOperand(1);
9410
9411 // The mask is present and the provenance of all the values is a smaller type,
9412 // lets see if the mask is superfluous.
9413
9414 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9415 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9416 return SDValue();
9417
9418 ISD::LoadExtType ExtType;
9419
9420 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9421 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9422 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9423 return SDValue();
9424
9425 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9426 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9427 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9428 return SDValue();
9429
9430 // The AND is not necessary, remove it.
9431
9432 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9433 SubsNode->getValueType(1));
9434 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9435
9436 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9437 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9438
9439 return SDValue(N, 0);
9440}
9441
Tim Northover3b0846e2014-05-24 12:50:23 +00009442// Optimize compare with zero and branch.
9443static SDValue performBRCONDCombine(SDNode *N,
9444 TargetLowering::DAGCombinerInfo &DCI,
9445 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009446 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9447 if (NV.getNode())
9448 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009449 SDValue Chain = N->getOperand(0);
9450 SDValue Dest = N->getOperand(1);
9451 SDValue CCVal = N->getOperand(2);
9452 SDValue Cmp = N->getOperand(3);
9453
9454 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9455 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9456 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9457 return SDValue();
9458
9459 unsigned CmpOpc = Cmp.getOpcode();
9460 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9461 return SDValue();
9462
9463 // Only attempt folding if there is only one use of the flag and no use of the
9464 // value.
9465 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9466 return SDValue();
9467
9468 SDValue LHS = Cmp.getOperand(0);
9469 SDValue RHS = Cmp.getOperand(1);
9470
9471 assert(LHS.getValueType() == RHS.getValueType() &&
9472 "Expected the value type to be the same for both operands!");
9473 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9474 return SDValue();
9475
Artyom Skrobov314ee042015-11-25 19:41:11 +00009476 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009477 std::swap(LHS, RHS);
9478
Artyom Skrobov314ee042015-11-25 19:41:11 +00009479 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009480 return SDValue();
9481
9482 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9483 LHS.getOpcode() == ISD::SRL)
9484 return SDValue();
9485
9486 // Fold the compare into the branch instruction.
9487 SDValue BR;
9488 if (CC == AArch64CC::EQ)
9489 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9490 else
9491 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9492
9493 // Do not add new nodes to DAG combiner worklist.
9494 DCI.CombineTo(N, BR, false);
9495
9496 return SDValue();
9497}
9498
Geoff Berry9e934b02016-01-04 18:55:47 +00009499// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9500// as well as whether the test should be inverted. This code is required to
9501// catch these cases (as opposed to standard dag combines) because
9502// AArch64ISD::TBZ is matched during legalization.
9503static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9504 SelectionDAG &DAG) {
9505
9506 if (!Op->hasOneUse())
9507 return Op;
9508
9509 // We don't handle undef/constant-fold cases below, as they should have
9510 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9511 // etc.)
9512
9513 // (tbz (trunc x), b) -> (tbz x, b)
9514 // This case is just here to enable more of the below cases to be caught.
9515 if (Op->getOpcode() == ISD::TRUNCATE &&
9516 Bit < Op->getValueType(0).getSizeInBits()) {
9517 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9518 }
9519
9520 if (Op->getNumOperands() != 2)
9521 return Op;
9522
9523 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9524 if (!C)
9525 return Op;
9526
9527 switch (Op->getOpcode()) {
9528 default:
9529 return Op;
9530
9531 // (tbz (and x, m), b) -> (tbz x, b)
9532 case ISD::AND:
9533 if ((C->getZExtValue() >> Bit) & 1)
9534 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9535 return Op;
9536
9537 // (tbz (shl x, c), b) -> (tbz x, b-c)
9538 case ISD::SHL:
9539 if (C->getZExtValue() <= Bit &&
9540 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9541 Bit = Bit - C->getZExtValue();
9542 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9543 }
9544 return Op;
9545
9546 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9547 case ISD::SRA:
9548 Bit = Bit + C->getZExtValue();
9549 if (Bit >= Op->getValueType(0).getSizeInBits())
9550 Bit = Op->getValueType(0).getSizeInBits() - 1;
9551 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9552
9553 // (tbz (srl x, c), b) -> (tbz x, b+c)
9554 case ISD::SRL:
9555 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9556 Bit = Bit + C->getZExtValue();
9557 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9558 }
9559 return Op;
9560
9561 // (tbz (xor x, -1), b) -> (tbnz x, b)
9562 case ISD::XOR:
9563 if ((C->getZExtValue() >> Bit) & 1)
9564 Invert = !Invert;
9565 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9566 }
9567}
9568
9569// Optimize test single bit zero/non-zero and branch.
9570static SDValue performTBZCombine(SDNode *N,
9571 TargetLowering::DAGCombinerInfo &DCI,
9572 SelectionDAG &DAG) {
9573 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9574 bool Invert = false;
9575 SDValue TestSrc = N->getOperand(1);
9576 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9577
9578 if (TestSrc == NewTestSrc)
9579 return SDValue();
9580
9581 unsigned NewOpc = N->getOpcode();
9582 if (Invert) {
9583 if (NewOpc == AArch64ISD::TBZ)
9584 NewOpc = AArch64ISD::TBNZ;
9585 else {
9586 assert(NewOpc == AArch64ISD::TBNZ);
9587 NewOpc = AArch64ISD::TBZ;
9588 }
9589 }
9590
9591 SDLoc DL(N);
9592 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9593 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9594}
9595
Tim Northover3b0846e2014-05-24 12:50:23 +00009596// vselect (v1i1 setcc) ->
9597// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9598// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9599// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9600// such VSELECT.
9601static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9602 SDValue N0 = N->getOperand(0);
9603 EVT CCVT = N0.getValueType();
9604
9605 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9606 CCVT.getVectorElementType() != MVT::i1)
9607 return SDValue();
9608
9609 EVT ResVT = N->getValueType(0);
9610 EVT CmpVT = N0.getOperand(0).getValueType();
9611 // Only combine when the result type is of the same size as the compared
9612 // operands.
9613 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9614 return SDValue();
9615
9616 SDValue IfTrue = N->getOperand(1);
9617 SDValue IfFalse = N->getOperand(2);
9618 SDValue SetCC =
9619 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9620 N0.getOperand(0), N0.getOperand(1),
9621 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9622 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9623 IfTrue, IfFalse);
9624}
9625
9626/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9627/// the compare-mask instructions rather than going via NZCV, even if LHS and
9628/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9629/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009630static SDValue performSelectCombine(SDNode *N,
9631 TargetLowering::DAGCombinerInfo &DCI) {
9632 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009633 SDValue N0 = N->getOperand(0);
9634 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009635
Ahmed Bougachac004c602015-04-27 21:43:12 +00009636 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009637 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009638
Ahmed Bougachac004c602015-04-27 21:43:12 +00009639 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9640 // scalar SetCCResultType. We also don't expect vectors, because we assume
9641 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9642 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9643 "Scalar-SETCC feeding SELECT has unexpected result type!");
9644
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009645 // If NumMaskElts == 0, the comparison is larger than select result. The
9646 // largest real NEON comparison is 64-bits per lane, which means the result is
9647 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009648 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009649
9650 // Don't try to do this optimization when the setcc itself has i1 operands.
9651 // There are no legal vectors of i1, so this would be pointless.
9652 if (SrcVT == MVT::i1)
9653 return SDValue();
9654
Tim Northover3c0915e2014-08-29 15:34:58 +00009655 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009656 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009657 return SDValue();
9658
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009659 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009660 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9661
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009662 // Also bail out if the vector CCVT isn't the same size as ResVT.
9663 // This can happen if the SETCC operand size doesn't divide the ResVT size
9664 // (e.g., f64 vs v3f32).
9665 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9666 return SDValue();
9667
Ahmed Bougachac004c602015-04-27 21:43:12 +00009668 // Make sure we didn't create illegal types, if we're not supposed to.
9669 assert(DCI.isBeforeLegalize() ||
9670 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9671
Tim Northover3b0846e2014-05-24 12:50:23 +00009672 // First perform a vector comparison, where lane 0 is the one we're interested
9673 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009674 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009675 SDValue LHS =
9676 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9677 SDValue RHS =
9678 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9679 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9680
9681 // Now duplicate the comparison mask we want across all other lanes.
9682 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9683 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009684 Mask = DAG.getNode(ISD::BITCAST, DL,
9685 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009686
9687 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9688}
9689
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009690/// Get rid of unnecessary NVCASTs (that don't change the type).
9691static SDValue performNVCASTCombine(SDNode *N) {
9692 if (N->getValueType(0) == N->getOperand(0).getValueType())
9693 return N->getOperand(0);
9694
9695 return SDValue();
9696}
9697
Tim Northover3b0846e2014-05-24 12:50:23 +00009698SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9699 DAGCombinerInfo &DCI) const {
9700 SelectionDAG &DAG = DCI.DAG;
9701 switch (N->getOpcode()) {
9702 default:
9703 break;
9704 case ISD::ADD:
9705 case ISD::SUB:
9706 return performAddSubLongCombine(N, DCI, DAG);
9707 case ISD::XOR:
9708 return performXorCombine(N, DAG, DCI, Subtarget);
9709 case ISD::MUL:
9710 return performMulCombine(N, DAG, DCI, Subtarget);
9711 case ISD::SINT_TO_FP:
9712 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009713 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009714 case ISD::FP_TO_SINT:
9715 case ISD::FP_TO_UINT:
9716 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009717 case ISD::FDIV:
9718 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009719 case ISD::OR:
9720 return performORCombine(N, DCI, Subtarget);
9721 case ISD::INTRINSIC_WO_CHAIN:
9722 return performIntrinsicCombine(N, DCI, Subtarget);
9723 case ISD::ANY_EXTEND:
9724 case ISD::ZERO_EXTEND:
9725 case ISD::SIGN_EXTEND:
9726 return performExtendCombine(N, DCI, DAG);
9727 case ISD::BITCAST:
9728 return performBitcastCombine(N, DCI, DAG);
9729 case ISD::CONCAT_VECTORS:
9730 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009731 case ISD::SELECT: {
9732 SDValue RV = performSelectCombine(N, DCI);
9733 if (!RV.getNode())
9734 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9735 return RV;
9736 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009737 case ISD::VSELECT:
9738 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009739 case ISD::LOAD:
9740 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9741 return SDValue(N, 0);
9742 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009743 case ISD::STORE:
9744 return performSTORECombine(N, DCI, DAG, Subtarget);
9745 case AArch64ISD::BRCOND:
9746 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009747 case AArch64ISD::TBNZ:
9748 case AArch64ISD::TBZ:
9749 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009750 case AArch64ISD::CSEL:
9751 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009752 case AArch64ISD::DUP:
9753 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009754 case AArch64ISD::NVCAST:
9755 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009756 case ISD::INSERT_VECTOR_ELT:
9757 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009758 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009759 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009760 case ISD::INTRINSIC_VOID:
9761 case ISD::INTRINSIC_W_CHAIN:
9762 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9763 case Intrinsic::aarch64_neon_ld2:
9764 case Intrinsic::aarch64_neon_ld3:
9765 case Intrinsic::aarch64_neon_ld4:
9766 case Intrinsic::aarch64_neon_ld1x2:
9767 case Intrinsic::aarch64_neon_ld1x3:
9768 case Intrinsic::aarch64_neon_ld1x4:
9769 case Intrinsic::aarch64_neon_ld2lane:
9770 case Intrinsic::aarch64_neon_ld3lane:
9771 case Intrinsic::aarch64_neon_ld4lane:
9772 case Intrinsic::aarch64_neon_ld2r:
9773 case Intrinsic::aarch64_neon_ld3r:
9774 case Intrinsic::aarch64_neon_ld4r:
9775 case Intrinsic::aarch64_neon_st2:
9776 case Intrinsic::aarch64_neon_st3:
9777 case Intrinsic::aarch64_neon_st4:
9778 case Intrinsic::aarch64_neon_st1x2:
9779 case Intrinsic::aarch64_neon_st1x3:
9780 case Intrinsic::aarch64_neon_st1x4:
9781 case Intrinsic::aarch64_neon_st2lane:
9782 case Intrinsic::aarch64_neon_st3lane:
9783 case Intrinsic::aarch64_neon_st4lane:
9784 return performNEONPostLDSTCombine(N, DCI, DAG);
9785 default:
9786 break;
9787 }
9788 }
9789 return SDValue();
9790}
9791
9792// Check if the return value is used as only a return value, as otherwise
9793// we can't perform a tail-call. In particular, we need to check for
9794// target ISD nodes that are returns and any other "odd" constructs
9795// that the generic analysis code won't necessarily catch.
9796bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9797 SDValue &Chain) const {
9798 if (N->getNumValues() != 1)
9799 return false;
9800 if (!N->hasNUsesOfValue(1, 0))
9801 return false;
9802
9803 SDValue TCChain = Chain;
9804 SDNode *Copy = *N->use_begin();
9805 if (Copy->getOpcode() == ISD::CopyToReg) {
9806 // If the copy has a glue operand, we conservatively assume it isn't safe to
9807 // perform a tail call.
9808 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9809 MVT::Glue)
9810 return false;
9811 TCChain = Copy->getOperand(0);
9812 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9813 return false;
9814
9815 bool HasRet = false;
9816 for (SDNode *Node : Copy->uses()) {
9817 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9818 return false;
9819 HasRet = true;
9820 }
9821
9822 if (!HasRet)
9823 return false;
9824
9825 Chain = TCChain;
9826 return true;
9827}
9828
9829// Return whether the an instruction can potentially be optimized to a tail
9830// call. This will cause the optimizers to attempt to move, or duplicate,
9831// return instructions to help enable tail call optimizations for this
9832// instruction.
9833bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9834 if (!CI->isTailCall())
9835 return false;
9836
9837 return true;
9838}
9839
9840bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9841 SDValue &Offset,
9842 ISD::MemIndexedMode &AM,
9843 bool &IsInc,
9844 SelectionDAG &DAG) const {
9845 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9846 return false;
9847
9848 Base = Op->getOperand(0);
9849 // All of the indexed addressing mode instructions take a signed
9850 // 9 bit immediate offset.
9851 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9852 int64_t RHSC = (int64_t)RHS->getZExtValue();
9853 if (RHSC >= 256 || RHSC <= -256)
9854 return false;
9855 IsInc = (Op->getOpcode() == ISD::ADD);
9856 Offset = Op->getOperand(1);
9857 return true;
9858 }
9859 return false;
9860}
9861
9862bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9863 SDValue &Offset,
9864 ISD::MemIndexedMode &AM,
9865 SelectionDAG &DAG) const {
9866 EVT VT;
9867 SDValue Ptr;
9868 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9869 VT = LD->getMemoryVT();
9870 Ptr = LD->getBasePtr();
9871 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9872 VT = ST->getMemoryVT();
9873 Ptr = ST->getBasePtr();
9874 } else
9875 return false;
9876
9877 bool IsInc;
9878 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9879 return false;
9880 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9881 return true;
9882}
9883
9884bool AArch64TargetLowering::getPostIndexedAddressParts(
9885 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9886 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9887 EVT VT;
9888 SDValue Ptr;
9889 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9890 VT = LD->getMemoryVT();
9891 Ptr = LD->getBasePtr();
9892 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9893 VT = ST->getMemoryVT();
9894 Ptr = ST->getBasePtr();
9895 } else
9896 return false;
9897
9898 bool IsInc;
9899 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9900 return false;
9901 // Post-indexing updates the base, so it's not a valid transform
9902 // if that's not the same as the load's pointer.
9903 if (Ptr != Base)
9904 return false;
9905 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9906 return true;
9907}
9908
Tim Northoverf8bfe212014-07-18 13:07:05 +00009909static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9910 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00009911 SDLoc DL(N);
9912 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00009913
9914 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9915 return;
9916
Tim Northoverf8bfe212014-07-18 13:07:05 +00009917 Op = SDValue(
9918 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9919 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009920 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00009921 0);
9922 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9923 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9924}
9925
Charlie Turner434d4592015-10-16 15:38:25 +00009926static void ReplaceReductionResults(SDNode *N,
9927 SmallVectorImpl<SDValue> &Results,
9928 SelectionDAG &DAG, unsigned InterOp,
9929 unsigned AcrossOp) {
9930 EVT LoVT, HiVT;
9931 SDValue Lo, Hi;
9932 SDLoc dl(N);
9933 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9934 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9935 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9936 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9937 Results.push_back(SplitVal);
9938}
9939
Tim Northover3b0846e2014-05-24 12:50:23 +00009940void AArch64TargetLowering::ReplaceNodeResults(
9941 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9942 switch (N->getOpcode()) {
9943 default:
9944 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00009945 case ISD::BITCAST:
9946 ReplaceBITCASTResults(N, Results, DAG);
9947 return;
Charlie Turner434d4592015-10-16 15:38:25 +00009948 case AArch64ISD::SADDV:
9949 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9950 return;
9951 case AArch64ISD::UADDV:
9952 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9953 return;
9954 case AArch64ISD::SMINV:
9955 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9956 return;
9957 case AArch64ISD::UMINV:
9958 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9959 return;
9960 case AArch64ISD::SMAXV:
9961 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9962 return;
9963 case AArch64ISD::UMAXV:
9964 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9965 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00009966 case ISD::FP_TO_UINT:
9967 case ISD::FP_TO_SINT:
9968 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9969 // Let normal code take care of it by not adding anything to Results.
9970 return;
9971 }
9972}
9973
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00009974bool AArch64TargetLowering::useLoadStackGuardNode() const {
9975 return true;
9976}
9977
Sanjay Patel1dd15592015-07-28 23:05:48 +00009978unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +00009979 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9980 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +00009981 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +00009982}
9983
Chandler Carruth9d010ff2014-07-03 00:23:43 +00009984TargetLoweringBase::LegalizeTypeAction
9985AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9986 MVT SVT = VT.getSimpleVT();
9987 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9988 // v4i16, v2i32 instead of to promote.
9989 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9990 || SVT == MVT::v1f32)
9991 return TypeWidenVector;
9992
9993 return TargetLoweringBase::getPreferredVectorAction(VT);
9994}
9995
Robin Morisseted3d48f2014-09-03 21:29:59 +00009996// Loads and stores less than 128-bits are already atomic; ones above that
9997// are doomed anyway, so defer to the default libcall and blame the OS when
9998// things go wrong.
9999bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10000 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10001 return Size == 128;
10002}
10003
10004// Loads and stores less than 128-bits are already atomic; ones above that
10005// are doomed anyway, so defer to the default libcall and blame the OS when
10006// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010007TargetLowering::AtomicExpansionKind
10008AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010009 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010010 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010011}
10012
10013// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010014TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010015AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010016 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010017 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010018}
10019
Ahmed Bougacha52468672015-09-11 17:08:28 +000010020bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10021 AtomicCmpXchgInst *AI) const {
Robin Morisset25c8e312014-09-17 00:06:58 +000010022 return true;
10023}
10024
Tim Northover3b0846e2014-05-24 12:50:23 +000010025Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10026 AtomicOrdering Ord) const {
10027 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10028 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +000010029 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010030
10031 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10032 // intrinsic must return {i64, i64} and we have to recombine them into a
10033 // single i128 here.
10034 if (ValTy->getPrimitiveSizeInBits() == 128) {
10035 Intrinsic::ID Int =
10036 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10037 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10038
10039 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10040 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10041
10042 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10043 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10044 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10045 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10046 return Builder.CreateOr(
10047 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10048 }
10049
10050 Type *Tys[] = { Addr->getType() };
10051 Intrinsic::ID Int =
10052 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10053 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10054
10055 return Builder.CreateTruncOrBitCast(
10056 Builder.CreateCall(Ldxr, Addr),
10057 cast<PointerType>(Addr->getType())->getElementType());
10058}
10059
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010060void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10061 IRBuilder<> &Builder) const {
10062 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10063 Builder.CreateCall(
10064 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10065}
10066
Tim Northover3b0846e2014-05-24 12:50:23 +000010067Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10068 Value *Val, Value *Addr,
10069 AtomicOrdering Ord) const {
10070 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +000010071 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010072
10073 // Since the intrinsics must have legal type, the i128 intrinsics take two
10074 // parameters: "i64, i64". We must marshal Val into the appropriate form
10075 // before the call.
10076 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10077 Intrinsic::ID Int =
10078 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10079 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10080 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10081
10082 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10083 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10084 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010085 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010086 }
10087
10088 Intrinsic::ID Int =
10089 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10090 Type *Tys[] = { Addr->getType() };
10091 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10092
David Blaikieff6409d2015-05-18 22:13:54 +000010093 return Builder.CreateCall(Stxr,
10094 {Builder.CreateZExtOrBitCast(
10095 Val, Stxr->getFunctionType()->getParamType(0)),
10096 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010097}
Tim Northover3c55cca2014-11-27 21:02:42 +000010098
10099bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10100 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10101 return Ty->isArrayTy();
10102}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010103
10104bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10105 EVT) const {
10106 return false;
10107}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010108
10109Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10110 if (!Subtarget->isTargetAndroid())
10111 return TargetLowering::getSafeStackPointerLocation(IRB);
10112
10113 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10114 // definition of TLS_SLOT_SAFESTACK in
10115 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10116 const unsigned TlsOffset = 0x48;
10117 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10118 Function *ThreadPointerFunc =
10119 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10120 return IRB.CreatePointerCast(
10121 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10122 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10123}
Manman Rencbe4f942015-12-16 21:04:19 +000010124
10125void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10126 // Update IsSplitCSR in AArch64unctionInfo.
10127 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10128 AFI->setIsSplitCSR(true);
10129}
10130
10131void AArch64TargetLowering::insertCopiesSplitCSR(
10132 MachineBasicBlock *Entry,
10133 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10134 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10135 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10136 if (!IStart)
10137 return;
10138
10139 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10140 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010141 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010142 for (const MCPhysReg *I = IStart; *I; ++I) {
10143 const TargetRegisterClass *RC = nullptr;
10144 if (AArch64::GPR64RegClass.contains(*I))
10145 RC = &AArch64::GPR64RegClass;
10146 else if (AArch64::FPR64RegClass.contains(*I))
10147 RC = &AArch64::FPR64RegClass;
10148 else
10149 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10150
10151 unsigned NewVR = MRI->createVirtualRegister(RC);
10152 // Create copy from CSR to a virtual register.
10153 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10154 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10155 // nounwind. If we want to generalize this later, we may need to emit
10156 // CFI pseudo-instructions.
10157 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10158 Attribute::NoUnwind) &&
10159 "Function should be nounwind in insertCopiesSplitCSR!");
10160 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010161 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010162 .addReg(*I);
10163
Manman Ren4632e8e2016-01-15 20:13:28 +000010164 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010165 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010166 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10167 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010168 .addReg(NewVR);
10169 }
10170}